如何在pytest中测试类的继承方法

2023-11-25

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方法来做到这一点。请参考文档并解释其如何适用于此处。


一种方法是使用灯具名称house对于所有测试方法(即使它正在测试TreeHouse), and 在每个测试上下文中覆盖其值:

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. Since pytest 只是枚举类的方法(即,没有进行“注册”,例如@pytest.test()装饰器),所有测试定义在TestHouse将在它的子类中发现,无需任何进一步的干预。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在pytest中测试类的继承方法 的相关文章