With python3 and the unnittest library is there a setup and teardown mechanism that applies to the full test run? I see one for module and class, but not a single run setup and teardown for the whole test suite.
3
votes
1 Answers
0
votes
My solution is create a parent class and put the test fixtures into it. Other tests class can inherit this parent class.
E.g.
init_test.py
:
import unittest
class InitTest(unittest.TestCase):
def setUp(self):
self.user = {'id': '1'}
def tearDown(self):
self.user = None
test_a.py
:
from init_test import InitTest
class TestA(InitTest):
def test_foo(self):
self.assertEqual(self.user, {'id': '1'})
test_b.py
:
from init_test import InitTest
class TestB(InitTest):
def test_bar(self):
self.assertEqual(self.user, {'id': '1'})
test_suites.py
:
import unittest
from test_a import TestA
from test_b import TestB
if __name__ == '__main__':
test_loader = unittest.TestLoader()
test_classes = [TestA, TestB]
suites = []
for test_class in test_classes:
suite = test_loader.loadTestsFromTestCase(test_class)
suites.append(suite)
big_suite = unittest.TestSuite(suites)
unittest.TextTestRunner().run(big_suite)
Unit test result:
..
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
Name Stmts Miss Cover Missing
-------------------------------------------------------------------------
src/stackoverflow/54365191/init_test.py 6 0 100%
src/stackoverflow/54365191/test_a.py 4 0 100%
src/stackoverflow/54365191/test_b.py 4 0 100%
src/stackoverflow/54365191/test_suites.py 12 0 100%
-------------------------------------------------------------------------
TOTAL 26 0 100%
Source code: https://github.com/mrdulin/python-codelab/tree/master/src/stackoverflow/54365191