mardi 1 août 2017

How to inherit from multiple base test classes using pythons unittest?

I'm writing some tests and want to share setUp and tearDown methods between different TestCase classes. To do this I figured you can use a base test class which only implements the setUp and tearDown methods and inherit from it. However, I also have situations where I'd like to use variables from multiple setUp's. Here's an example:

class Base(unittest.TestCase):
    def setUp(self):
        self.shared = 'I am shared between everyone'

    def tearDown(self):
        del self.shared


class Base2(unittest.TestCase):
    def setUp(self):
        self.partial_shared = 'I am shared between only some tests'

    def tearDown(self):
        del self.partial_shared


class Test1(Base):

    def test(self):
        print self.shared
        test_var = 'I only need Base'
        print test_var



class Test2(Base2):

    def test(self):
        print self.partial_shared
        test_var = 'I only need Base2'


class Test3(Base, Base2):

    def test(self):
        test_var = 'I need both Base and Base2'
        print self.shared
        print self.partial_shared


if __name__=='__main__':
    unittest.main()

Here is the output:

..EI am shared between everyone
I only need Base
I am shared between only some tests
I am shared between everyone

======================================================================
ERROR: test (__main__.Test3)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/b3053674/Documents/PyCoTools/PyCoTools/Tests/base_tests.py", line 134, in test
    print self.partial_shared
AttributeError: 'Test3' object has no attribute 'partial_shared'

----------------------------------------------------------------------
Ran 3 tests in 0.004s

FAILED (errors=1)

Is it possible to implement a class heirachy such as this?

Aucun commentaire:

Enregistrer un commentaire