2017-09-04 422 views
2
方法

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感兴趣。请参考文档并解释如何适用于此。

+0

你的最后一行应该是'assert not tree_house.is_on_the_ground()' –

+0

感谢编辑@PaulH – Bastian

+0

@PaulH我想我也可以摆脱其他断言中的== == True。 – Bastian

回答

3

的一种方法是使用夹具名称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() 

同样来自TestHouse注意TestTreeHouse继承。由于pytest merely enumerates methods of classes(即没有用“@pytest.test()”修饰符完成“注册”),在TestHouse中定义的所有测试都将在其子类中发现,而无需任何进一步干预。

+1

我喜欢这个答案。在这个答案:https://stackoverflow.com/a/44431292/1075374虽然,据说pytest禁止类层次结构,虽然链接不解释它。你对此有何看法? – Bastian

+0

我试过了,出于某种原因'自我'迷路了。 'TestTreeHouse.test_habitability' - >'TypeError:is_habitable()缺少1个需要的位置参数:'self''。第二次测试也会发生同样的情况。任何想法? – Bastian

+0

也许你从'tree_house' fixture中返回* class对象*'TreeHouse',而不是类的实例:'TreeHouse()' – theY4Kman

0

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

+0

感谢您的链接。我使用参数来重复使用不同参数/参数的测试。但我不明白在这种情况下如何工作。您是否想通过澄清和显示一些工作代码来进一步扩展您的答案,而不仅仅是指向文档的链接? – Bastian