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
in TreeHouse
.
重写相同的测试TestHouse
不会是干的。
如何测试继承的方法TreeHouse
(在这种情况下is_habitable
)没有重复的代码?
我想要重新测试TreeHouse
与其超类运行相同的测试,但不适用于新的或重写的方法/属性。
经过一些研究,我发现了相互矛盾的来源。在深入研究 pytest 文档后,我无法理解什么适用于这种情况。
我感兴趣的是pytest方法来做到这一点。请参考文档并解释其如何适用于此处。