[英]How to test a class' inherited methods in pytest
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
为该类添加了一个新的fixture:
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方法感兴趣。 请参考文档并解释这是如何适用的。
这样做的一个方法是使用夹具名称house
的所有测试方法(即使它的测试TreeHouse
),并覆盖其在每个测试上下文值 :
class TestTreeHouse(TestHouse):
@pytest.fixture
def house(self, tree_house):
return tree_house
def test_groundedness(self, house):
assert not house.is_on_the_ground()
还要注意TestTreeHouse
从继承TestHouse
。 由于pytest只是枚举类的方法 (即没有用@pytest.test()
装饰器完成“注册”),所以TestHouse
定义的所有测试都将在它的子类中被发现,而无需任何进一步的干预。
您可以使用pytest参数化将多个参数传递给同一个测试,在这种情况下,参数很可能是被测试的类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.