python unittests有多个设置?

und*_*run 8 python sockets unit-testing fixtures

我正在使用带有数百个测试用例的套接字的模块.这很好.除了现在我需要使用和不使用socket.setdefaulttimeout(60)测试所有情况...请不要告诉我剪切和粘贴所有测试并在setup/teardown中设置/删除默认超时.

老实说,我认为每个测试用例都是好的做法,但我也不喜欢重复自己.这实际上只是在不同的测试环境中进行测试.

我看到unittest支持模块级别设置/拆卸夹具,但对我来说,如何将我的一个测试模块转换为两次不同的设置两次测试本身并不明显.

任何帮助将非常感激.

Baz*_*ski 6

您可以执行以下操作:

class TestCommon(unittest.TestCase):
    def method_one(self):
        # code for your first test
        pass

    def method_two(self):
        # code for your second test
        pass

class TestWithSetupA(TestCommon):
    def SetUp(self):
        # setup for context A
        do_setup_a_stuff()

    def test_method_one(self):
        self.method_one()

    def test_method_two(self):
        self.method_two()

class TestWithSetupB(TestCommon):
    def SetUp(self):
        # setup for context B
        do_setup_b_stuff()

    def test_method_one(self):
        self.method_one()

    def test_method_two(self):
        self.method_two()
Run Code Online (Sandbox Code Playgroud)


und*_*run 5

关于这个问题的其他答案是有效的,因为它们使在多种环境下实际执行测试成为可能,但是在使用选项时,我认为我喜欢更独立的方法。我正在使用套件和结果来组织和显示测试结果。为了在两个环境中运行一个测试而不是两个测试,我采用了这种方法 - 创建一个 TestSuite 子类。

class FixtureSuite(unittest.TestSuite):
    def run(self, result, debug=False):
        socket.setdefaulttimeout(30)
        super().run(result, debug)
        socket.setdefaulttimeout(None)
...
suite1 = unittest.TestSuite(testCases)
suite2 = FixtureSuite(testCases)
fullSuite = unittest.TestSuite([suite1,suite2])
unittest.TextTestRunner(verbosity=2).run(fullSuite)
Run Code Online (Sandbox Code Playgroud)