python unittests with multiple setups?

The other answers on this question are valid in as much as they make it possible to actually perform the tests under multiple environments, but in playing around with the options I think I like a more self contained approach. I'm using suites and results to organize and display results of tests. In order to run one tests with two environments rather than two tests I took this approach - create a TestSuite subclass.

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)

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()

If your code does not call socket.setdefaulttimeout then you can run tests the following way:

import socket
socket.setdeaulttimeout(60)
old_setdefaulttimeout, socket.setdefaulttimeout = socket.setdefaulttimeout, None
unittest.main()
socket.setdefaulttimeout = old_setdefaulttimeout

It is a hack, but it can work


I would do it like this:

  1. Make all of your tests derive from your own TestCase class, let's call it SynapticTestCase.

  2. In SynapticTestCase.setUp(), examine an environment variable to determine whether to set the socket timeout or not.

  3. Run your entire test suite twice, once with the environment variable set one way, then again with it set the other way.

  4. Write a small shell script to invoke the test suite both ways.