【问题标题】:Python nose test inheritance: load unit test fixtures from subclassesPython 鼻子测试继承:从子类加载单元测试夹具
【发布时间】:2013-02-18 02:39:30
【问题描述】:

我正在将 Python 项目的测试套件从 unittest 转换为 nose。该项目的现有框架(基于 unittest)相当笨重,包含大量用于测试发现和运行的高度定制的代码,因此我正在尝试迁移到鼻子以使一切更加精简。

但是,我在生成测试套件的代码方面遇到了问题。

项目的框架有两种运行测试的方式。一个是

class TestSomething(unittest.TestCase):

    def setUp(self):
        ...

    def test_x(self):
        ...

    def test_y(self):
        ...

suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestSomething))

这是“直截了当”的方式,它是所有 Nose 示例和教程所展示的,并且有效。但是,第二种方法是定义一个包含所有测试逻辑的测试类,然后在包含不同设置配置的各种子类中创建测试用例,并从超类继承测试:

class TestSomething(unittest.TestCase):

    def test_x(self):
        ...

    def test_y(self):
        ...

class TestCase1(TestSomething):

    def setUp(self):
        ...

class TestCase2(TestSomething):

    def setUp(self):
        ...

suite = unittest.TestSuite()

cases = [TestCase1,TestCase2]
suite.addTests([unittest.makeSuite(case) for case in cases])

这就是鼻子失败的原因。它尝试先运行测试方法,这显然不起作用,因为超类中没有 setUp() 并且 test_x() 和 test_y() 中使用的许多变量尚未定义。

我在任何地方都没有找到任何这样的例子,而且 Nose 的(相当稀疏且难以浏览)文档似乎也没有提到它。这怎么能和鼻子一起工作?任何帮助将不胜感激。

【问题讨论】:

    标签: python unit-testing nose nosetests


    【解决方案1】:

    首先,正如 unutbu 所指出的,您不应该给 TestSomething 一个以 Test 开头的名称,因为 nose 会自动将此类类视为测试用例。此外,nose 运行他找到的所有 TestCase 子类,因此这样做:

    class Something(unittest.TestCase):
        ...
    

    给出完全相同的结果。我认为您不应该从 TestCase 继承并将该类用作混合:

    class Something(object):
        def test_x(self):
            # here the various assertEqual etc. do not resolve, but you can use them
            # as if they were present, since in real test-cases they will be inherited
            # from unittest.TestCase.
            ...
        ...
    
    class TestCase1(unittest.TestCase, Something):
        def setUp(self):
            ...
    

    另一种方法是将类的__test__ 属性设置为False

    class TestSomething(unittest.TestCase):
        __test__ = False
        def test_x(self):
            ...
    
    
    class TestCase1(TestSomething):
        __test__ = True  #must put this
        def setUp(self):
            ...
    

    您也可以使用nose.istestnose.nottest 来标记哪个类是测试用例,哪个不是:

    @tools.nottest
    class TestSomething(unittest.TestCase):
        def test_x(self):
            ...
    
    @tools.istest
    class TestCase1(TestSomething):
        sef setUp(self):
            ...
    

    【讨论】:

    • 使用鼻子装饰器成功了;回想起来,现在看起来很明显,但有时最明显的解决方案是最难以捉摸的......非常感谢您的提示!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多