How to test a class' inherited methods in pytest

后端 未结 2 1305
春和景丽
春和景丽 2021-01-17 23:58

house.py:

class House:
    def is_habitable(self):
        return True

    def is_on_the_ground(self):
        return True

相关标签:
2条回答
  • 2021-01-18 00:32

    You can use pytest parameterization to pass multiple arguments to the same test, in this case, the argument would most likely be the class being tested.

    0 讨论(0)
  • 2021-01-18 00:41

    One way to do this would be to use the fixture name house for all test methods (even if it's testing a TreeHouse), and 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()
    

    Also note TestTreeHouse inherits from TestHouse. Since pytest merely enumerates methods of classes (i.e. there is no "registration" done with, say, a @pytest.test() decorator), all tests defined in TestHouse will be discovered in subclasses of it, without any further intervention.

    0 讨论(0)
提交回复
热议问题