【发布时间】:2017-09-04 15:46:03
【问题描述】:
house.py:
class House:
def is_habitable(self):
return True
def is_on_the_ground(self):
return True
conftest.py:
import pytest
from house import House
@pytest.fixture(scope='class')
def house():
return House()
test_house.py:
class TestHouse:
def test_habitability(self, house):
assert house.is_habitable()
def test_groundedness(self, house):
assert house.is_on_the_ground()
到目前为止,一切都在测试中。
现在我添加一个子类并覆盖house.py 中的一个方法:
class House:
def is_habitable(self):
return True
def is_on_the_ground(self):
return True
class TreeHouse(House):
def is_on_the_ground(self):
return False
我还在conftest.py 中为该类添加了一个新夹具:
import pytest
from house import House
from house import TreeHouse
@pytest.fixture(scope='class')
def house():
return House()
@pytest.fixture(scope='class')
def tree_house():
return TreeHouse()
我在test_house.py中为树屋添加了一个新的测试类:
class TestHouse:
def test_habitability(self, house):
assert house.is_habitable()
def test_groundedness(self, house):
assert house.is_on_the_ground()
class TestTreeHouse:
def test_groundedness(self, tree_house):
assert not tree_house.is_on_the_ground()
此时,代码可以工作,但有些情况没有经过测试。例如,为了完整,我需要再次测试从House 中继承的方法TreeHouse。
从 TestHouse 重写相同的测试不会 DRY。
如何在不重复代码的情况下测试TreeHouse(本例为is_habitable)的继承方法?
我想要重新测试TreeHouse 与它的超类运行的相同测试,但不适用于新的或覆盖的方法/属性。
经过一些研究,我发现了相互矛盾的来源。在深入研究 pytest 文档后,我无法理解适用于这种情况的内容。
我对 pytest 方法很感兴趣。请参考文档并在此处解释如何应用。
【问题讨论】:
-
你的最后一行应该是
assert not tree_house.is_on_the_ground() -
感谢@PaulH 的编辑
-
@PaulH 我想我也可以摆脱其他断言中的
== True。 -
是的。
assert not tree_house.is_on_the_ground()解决了你的问题吗?应该处理的事情 -
@Bastian 另一个是如果非覆盖方法称为覆盖方法,有时我在查看人们的示例时会得到隧道视野;)