Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python unittests with multiple setups?

I'm working on a module using sockets with hundreds of test cases. Which is nice. Except now I need to test all of the cases with and without socket.setdefaulttimeout( 60 )... Please don't tell me cut and paste all the tests and set/remove a default timeout in setup/teardown.

Honestly, I get that having each test case laid out on it's own is good practice, but i also don't like to repeat myself. This is really just testing in a different context not different tests.

i see that unittest supports module level setup/teardown fixtures, but it isn't obvious to me how to convert my one test module into testing itself twice with two different setups.

any help would be much appreciated.

like image 287
underrun Avatar asked Jul 22 '12 23:07

underrun


2 Answers

you could do something like this:

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()
like image 165
Bazyli Debowski Avatar answered Sep 22 '22 23:09

Bazyli Debowski


You could also inherit and rerun the original suite, but overwrite the whole setUp or a part of it:

class TestOriginal(TestCommon):
    def SetUp(self):
        # common setUp here

        self.current_setUp()

    def current_setUp(self):
        # your first setUp
        pass

    def test_one(self):
        # your test
        pass

    def test_two(self):
        # another test
        pass

class TestWithNewSetup(TestOriginal):
    def current_setUp(self):
        # overwrite your first current_setUp
like image 44
a regular fellow Avatar answered Sep 23 '22 23:09

a regular fellow