如何扩展 pytest 基类并覆盖固定装置

问题描述 投票:0回答:1

我有一个基本测试类,它实现了一些我想重用的测试。想法是从此类继承并重写固定装置以为基类测试提供必要的输入数据。像这样的东西:

base_class.py
class TestBase:
    @pytest.fixture(scope="module")
    def base_settings(self) -> dict:
        return None
    
    def test_settings(base_settings):
        assert base_settings["value_a"] > base_settings["value_b"]
test_my_class.py
class TestMyClass(TestBase):
    # override the base_settings fixture in TestBase
    @pytest.fixture(scope="module")
    def base_settings(self) -> dict:
        return {"value_a": 4, "value_b": 3}
}

当我现在执行 test_my_class.py 时,我希望

test_settings
测试能够通过(value_a 大于 value_b),但它却抱怨 base_settings 为 None -> 使用基类中的固定装置而不是 TestMyClass 中的固定装置。我怎样才能解决这个问题?我还尝试通过
__init__
方法传递参数,但 pytest 似乎不支持此功能。

python class pytest fixtures
1个回答
0
投票

我刚刚在 pytest 8.0.1 中进行了测试,它的工作方式符合您的预期。 可能发生的情况是 pytest 自行执行您的

TestBase
,仅仅因为您将其命名为 Test...
,因此它会像任何其他测试类一样被收集。

在下面的示例中,运行了 2 个测试,其中一个测试按预期失败,不是因为它得到

None

,而是因为我将 
value_a
value_b
 都设置为 
3
,只是为了证明夹具确实在各个测试之间被覆盖课程:

import pytest class Base: @pytest.fixture(scope="class") def base_settings(self) -> dict: return None def test_settings(self, base_settings): assert base_settings["value_a"] > base_settings["value_b"] class TestMyClassA(Base): @pytest.fixture(scope="class") def base_settings(self) -> dict: return {"value_a": 4, "value_b": 3} class TestMyClassB(Base): @pytest.fixture(scope="class") def base_settings(self) -> dict: return {"value_a": 3, "value_b": 3}

注意:我将scope

更改为
class
,因为它看起来更合乎逻辑,但原来的
module
应该也可以工作。

© www.soinside.com 2019 - 2024. All rights reserved.