house.py
:如何测试一个类的继承了pytest
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()
在那个poi nt,代码有效,但有些情况未经过测试。例如,要完成,我需要再次测试TreeHouse
中从House
继承的方法。
从TestHouse
重写相同的测试不会干。
如何在不重复代码的情况下测试TreeHouse
(在这种情况下为is_habitable
)的继承方法?
我想重新测试TreeHouse
与其超类运行相同的测试,但不是为新的或重写的方法/属性。
经过一番研究,我发现了矛盾的来源。在pytest文档中进行挖掘后,我无法理解适用于此场景的内容。
我对pytest感兴趣。请参考文档并解释如何适用于此。
你的最后一行应该是'assert not tree_house.is_on_the_ground()' –
感谢编辑@PaulH – Bastian
@PaulH我想我也可以摆脱其他断言中的== == True。 – Bastian