Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I currently have a couple of unit tests that share a typical arrangement of tests. Here's a model: 

import unittest

class BaseTest(unittest.TestCase):

    def testCommon(self):

        print 'Calling BaseTest:testCommon'

        value = 5

        self.assertEquals(value, 5)

class SubTest1(BaseTest):

    def testSub1(self):

        print 'Calling SubTest1:testSub1'

        sub = 3

        self.assertEquals(sub, 3)

class SubTest2(BaseTest):

    def testSub2(self):

        print 'Calling SubTest2:testSub2'

        sub = 4

        self.assertEquals(sub, 4)

if __name__ == '__main__':

    unittest.main()

Output:

Calling BaseTest:testCommon

.Calling BaseTest:testCommon

.Calling SubTest1:testSub1

.Calling BaseTest:testCommon

.Calling SubTest2:testSub2

.

----------------------------------------------------------------------

Ran 5 tests in 0.000s

OK

Is there an approach to revise the above so the absolute first testCommon isn't called? 

1 Answer

0 votes
by (26.4k points)

You can use Multiple inheritance, so your class with regular tests doesn't itself inherit from TestCase.

import unittest

class CommonTests(object):

    def testCommon(self):

        print 'Calling BaseTest:testCommon'

        value = 5

        self.assertEquals(value, 5)

class SubTest1(unittest.TestCase, CommonTests):

    def testSub1(self):

        print 'Calling SubTest1:testSub1'

        sub = 3

        self.assertEquals(sub, 3)

class SubTest2(unittest.TestCase, CommonTests):

    def testSub2(self):

        print 'Calling SubTest2:testSub2'

        sub = 4

        self.assertEquals(sub, 4)

if __name__ == '__main__':

    unittest.main()

Are you interested to learn the concepts of Python? Join the python training course fast!

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...