I currently have a few unit tests which share a common set of tests. Here’s an example:
JavaScript
x
27
27
1
import unittest
2
3
class BaseTest(unittest.TestCase):
4
5
def testCommon(self):
6
print 'Calling BaseTest:testCommon'
7
value = 5
8
self.assertEquals(value, 5)
9
10
class SubTest1(BaseTest):
11
12
def testSub1(self):
13
print 'Calling SubTest1:testSub1'
14
sub = 3
15
self.assertEquals(sub, 3)
16
17
18
class SubTest2(BaseTest):
19
20
def testSub2(self):
21
print 'Calling SubTest2:testSub2'
22
sub = 4
23
self.assertEquals(sub, 4)
24
25
if __name__ == '__main__':
26
unittest.main()
27
The output of the above is:
JavaScript
1
11
11
1
Calling BaseTest:testCommon
2
.Calling BaseTest:testCommon
3
.Calling SubTest1:testSub1
4
.Calling BaseTest:testCommon
5
.Calling SubTest2:testSub2
6
.
7
----------------------------------------------------------------------
8
Ran 5 tests in 0.000s
9
10
OK
11
Is there a way to rewrite the above so that the very first testCommon
is not called?
EDIT: Instead of running 5 tests above, I want it to run only 4 tests, 2 from the SubTest1 and another 2 from SubTest2. It seems that Python unittest is running the original BaseTest on its own and I need a mechanism to prevent that from happening.
Advertisement
Answer
Use multiple inheritance, so your class with common tests doesn’t itself inherit from TestCase.
JavaScript
1
26
26
1
import unittest
2
3
class CommonTests(object):
4
def testCommon(self):
5
print 'Calling BaseTest:testCommon'
6
value = 5
7
self.assertEquals(value, 5)
8
9
class SubTest1(unittest.TestCase, CommonTests):
10
11
def testSub1(self):
12
print 'Calling SubTest1:testSub1'
13
sub = 3
14
self.assertEquals(sub, 3)
15
16
17
class SubTest2(unittest.TestCase, CommonTests):
18
19
def testSub2(self):
20
print 'Calling SubTest2:testSub2'
21
sub = 4
22
self.assertEquals(sub, 4)
23
24
if __name__ == '__main__':
25
unittest.main()
26