为什么派生类中的测试会重新运行父类测试?

wim*_*wim 7 python nosetests pytest python-unittest

当测试设置中存在显着重叠时,它可以使DRY保持使用继承.但这会导致不必要的重复测试执行问题:

from unittest import TestCase

class TestPotato(TestCase):
    def test_in_parent(self):
        print 'in parent'

class TestSpud(TestPotato):
    def test_in_child(self):
        print 'in child'
Run Code Online (Sandbox Code Playgroud)

测试此模块运行test_in_parent两次.

$ python -m unittest example
in parent
.in child
.in parent
.
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK
Run Code Online (Sandbox Code Playgroud)

为什么?这是设计的吗?可以通过以某种方式配置测试运行器来禁用它吗?

我可以通过将setup移动到一个非发现的类来解决这个问题,然后使用多个继承,但它似乎有点hacky和不必要.

注意:在其他运行器中出现相同的问题,例如nose(nosetests -s example.py)和pytest(py.test example.py)

Łuk*_*ski 5

测试跑步者会查找以开头的所有方法test。子类中存在继承的方法-因此,将它们检测为要运行的测试。为了避免这种情况,您应该提取父类中的通用代码,并且不要继承任何实际的测试。

from unittest import TestCase

class PotatoTestTemplate(TestCase):
    def setUp():
        pass

class PotatoTest1(PotatoTestTemplate):
    def test1(self):
        pass

class PotatoTest2(PotatoTestTemplate):
    def test1(self):
        pass
Run Code Online (Sandbox Code Playgroud)