【问题标题】:Can we call a pytest fixture conditionally?我们可以有条件地调用 pytest 夹具吗?
【发布时间】:2021-09-23 11:38:56
【问题描述】:

我的用例是仅在满足特定条件时才调用夹具。但是由于我们需要调用 pytest 夹具作为测试函数的参数,所以每次运行测试时都会调用它。

我想做这样的事情:

@pytest.parameterize("a", [1, 2, 3])
def test_method(a):
    if a == 2:
       method_fixture

【问题讨论】:

  • 你可以使用side_effect

标签: python pytest fixtures


【解决方案1】:

是的,您可以将indirect=True 用于参数以使该参数引用固定装置。

import pytest


@pytest.fixture
def thing(request):
    if request.param == 2:
        return func()
    return None


@pytest.mark.parametrize("thing", [1, 2, 3], indirect=True)
def test_indirect(thing):
    pass  # thing will either be the retval of `func()` or NOne

具有依赖的“夹具”

如编辑中所述,如果您的灯具相互依赖,您可能需要改用 pytest_generate_tests 挂钩。

例如这将使用不相等的值对测试进行参数化。

import itertools


def pytest_generate_tests(metafunc):
    if metafunc.function.__name__ == "test_combo":
        a_values = [1, 2, 3, 4]
        b_values = [2, 3, 4, 5]
        all_combos = itertools.product(a_values, b_values)
        combos = [
            pair
            for pair in all_combos
            if pair[0] != pair[1]
        ]
        metafunc.parametrize(["a", "b"], combos)


def test_combo(a, b):
    assert a != b

【讨论】:

  • 感谢您的回复,@AKX!如果parametrize中有多个参数怎么办?例如,``` @pytest.mark.parametrize("a", [1, 2, 3]) @pytest.mark.parametrize("b", [1, 2, 3]) def test_something(a, b ): if a != b: method_fixture #只在“a”不等于“b”时调用fixture ```
  • 查看我的编辑。希望对您有所帮助...
  • 它有帮助!像魅力一样工作!谢谢@AKX!!
猜你喜欢
  • 1970-01-01
  • 2013-10-10
  • 1970-01-01
  • 2018-09-27
  • 2020-04-15
  • 1970-01-01
  • 2016-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多