我对Python的单元测试有疑问!让我们说我有一个docker容器设置来处理特定的api端点(让我们说用户,例如:my_site/users/etc/etc/etc
)。这个容器有很多不同的层被分解和处理。处理实际调用和响应,逻辑层,数据层的类。我想围绕特定的调用编写测试(只是检查状态代码)。
有许多不同的类充当给定端点的处理程序。我必须为每一个设置不同的东西,但是,每个东西都从Application继承并使用它的一些方法。我想为我的单位测试做setUp class
所以我不必每次都重新建立这个。任何建议都会有帮助。到目前为止,我主要看到继承是测试的一个坏主意,但是,我只想将它用于setUp。这是一个例子:
class SetUpClass(unittest.TestCase):
def setUp(self):
self._some_data = data_set.FirstOne()
self._another_data_set = data_set.SecondOne()
def get_app(self):
config = Config()
return Application(config,
first_one=self._some_data,
second_one=self._another_data_set)
class TestFirstHandler(SetUpClass, unittest.TestCase):
def setUp(self):
new_var = something
def tearDown(self):
pass
def test_this_handler(self):
# This specific handler needs the application to function
# but I don't want to define it in this test class
res = self.fetch('some_url/users')
self.assertEqual(res.code, 200)
class TestSecondHandler(SetUpClass, unittest.TestCase):
def setUp(self):
different_var_thats_specific_to_this_handler = something_else
def tearDown(self):
pass
def test_this_handler(self):
# This specific handler needs the application to function
# but I don't want to define it in this test class
res = self.fetch('some_url/users/account/?something_custom={}'.format('WOW'))
self.assertEqual(res.code, 200)
再次感谢!!
答案 0 :(得分:1)
正如评论中所提到的,您只需要学习如何使用super()
。您也不需要在基类列表中重复TestCase
。
这是Python 3的简单版本:
class TestFirstHandler(SetUpClass):
def setUp(self):
super().setUp()
new_var = something
def tearDown(self): # Easier to not declare this if it's empty.
super().tearDown()
def test_this_handler(self):
# This specific handler needs the application to function
# but I don't want to define it in this test class
res = self.fetch('some_url/users')
self.assertEqual(res.code, 200)