Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python unittest从多个基本测试类继承?_Python_Inheritance_Testing_Python Unittest - Fatal编程技术网

如何使用Python unittest从多个基本测试类继承?

如何使用Python unittest从多个基本测试类继承?,python,inheritance,testing,python-unittest,Python,Inheritance,Testing,Python Unittest,我正在编写一些测试,希望在不同的测试用例类之间共享安装和拆卸方法。为此,我想您可以使用一个只实现setUp和tearDown方法并从中继承的基本测试类。然而,在某些情况下,我也希望使用来自多个设置的变量。下面是一个例子: class Base(unittest.TestCase): def setUp(self): self.shared = 'I am shared between everyone' def tearDown(self): d

我正在编写一些测试,希望在不同的测试用例类之间共享安装和拆卸方法。为此,我想您可以使用一个只实现setUp和tearDown方法并从中继承的基本测试类。然而,在某些情况下,我也希望使用来自多个设置的变量。下面是一个例子:

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()
以下是输出:

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

有可能实现这样的类继承权吗

Python支持链式继承

您可以使
类Base2()
继承自Base,然后只添加所需的内容

像这样:

class Base2(Base):
    def setUp(self):
        super(Base2, self).setUp()
        self.partial_shared = 'I am shared between only some tests'
然后从中继承:

class Test3(Base2):

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

嗨,伊戈尔,谢谢你的回复。我尝试了您的建议,并得到了以下错误:
TypeError:error调用元类Base时无法为Base、Base和Base2创建一致的方法解析顺序(MRO)。我需要检查一下。