【问题标题】:How to synchronize parametrization across pytest fixtures?如何在 pytest 夹具之间同步参数化?
【发布时间】:2020-11-27 09:28:21
【问题描述】:

我有两个装置 AB 具有相同的 params 参数传递给 pytest.fixture()。此外,BA 作为参数:

import pytest

@pytest.fixture(params=[1, 2])
def A(request):
    if request.param == 1:
        # do stuff to get matrix_1
        return matrix_1
    if request.param == 2:
        # do stuff to get matrix_2
        return matrix_2

@pytest.fixture(params=[1, 2])
def B(request, A):
    if request.param == 1:
        # do stuff with A to get matrix_3
        return matrix_3
    if request.param == 2:
        # do stuff with A to get matrix_4
        return matrix_4

我还有一个函数test_method,它接受夹具Bmy_class(一个返回MyClass() 实例的夹具)作为参数并测试my_class 的方法。该方法将B 作为参数。我认为这些信息对于这个问题并不一定重要,它只是为了上下文:

from my_module import MyClass

@pytest.fixture
def my_class():
    return MyClass()

def test_method(my_class, B):
    # do stuff to get the expected value
    actual = my_class.method(B)
    assert actual == expected

问题是整个结构只有在AB 在每个时间点都具有相同的参数时才有意义,即A 不能有request.param = 1,而Brequest.param = 2。这些变量不打算在程序中以其他方式使用,如果它们被测试的代码会中断。

有没有办法在夹具之间共享或同步参数化?或者以某种方式重新设计代码,使其不成问题?谢谢!

【问题讨论】:

    标签: python unit-testing testing pytest code-organization


    【解决方案1】:

    在 OP 的 cmets 之后更新

    在您的代码中,您创建了四个测试而不是两个,其中两个相同。您可以使用只提供参数而不参数化派生的夹具的基本夹具:

    @pytest.fixture(params=[1, 2])
    def Base(request):
        return request.param
    
    @pytest.fixture
    def A(Base):
        if Base == 1:
            return value_1
        if Base == 2:
            return value_2
    
    
    @pytest.fixture
    def B(Base):
        if Base == 1:
            return value_3
        if Base == 2:
            return value_4
    

    【讨论】:

    • 谢谢!问题是 A 不返回标量值,而是一个复杂的矩阵(我应该对此更清楚)。如果我必须测试 A 是否与 B 内部的矩阵相等,那将违背 A 的目的。我将更正问题以反映 A 不是标量值。我想我可以尝试将 A 变成一个类,它具有 request.param 作为其属性之一(可以测试 B 内部的相等性),但我希望有一个更优雅的解决方案
    • 我想解决这个问题的另一种方法是在同一个夹具中定义 A 和 B 并作为列表或其他内容返回。但这也有点不礼貌
    • 也许我可以添加另一个夹具 C,它返回 request.param 值并充当 A 和 B 中的参数,而不是 @pytest.fixture(params=...)?
    • 你说得对,我相应地更新了答案。你的最后一个提议是最好的。
    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2022-12-08
    相关资源
    最近更新 更多