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

2024-10-17 06:14:30 发布

您现在位置:Python中文网/ 问答频道 /正文

{

class House:
    def is_habitable(self):
        return True

    def is_on_the_ground(self):
        return True

conftest.py

^{pr2}$

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中为tree house添加了一个新的测试类:

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()

在这一点上,代码可以工作,但是有些情况还没有经过测试。例如,为了完成,我需要再次测试从TreeHouse中的House继承的方法。在

TestHouse重写相同的测试不会是干的。在

如何在不复制代码的情况下测试TreeHouse(在本例中是is_habitable)的继承方法?在

我希望使用与超级类运行相同的测试来重新测试TreeHouse,而不是针对新的或重写的方法/属性。在

经过一番研究,我遇到了矛盾的来源。在阅读了pytest文档之后,我无法理解适用于这个场景的是什么。在

我对pytest的pytest方法感兴趣。请参考文件并解释如何适用于此。在


Tags: thepytestselfreturnpytestison
2条回答

一种方法是对所有测试方法使用fixture名称house(即使它正在测试TreeHouse),并且override its value in each test context

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 merely enumerates methods of classes(即,没有“注册”完成,例如,@pytest.test()装饰器),所有在{}中定义的测试都将在其子类中被发现,而无需任何进一步的干预。在

您可以使用pytest parameterization将多个参数传递给同一测试,在这种情况下,参数很可能是正在测试的类。在

相关问题 更多 >