python - Pytest:请求 fixture 的嵌套使用

标签 python python-3.x pytest

我想获得一些关于如何使用多层参数化 pytest fixtures 运行 pytests 的帮助。

我有一个基于请求的全局 fixture ,用于选择我要测试的系统的基本实现:

@fixture()
def a_provider():
    yield 'a'


@fixture()
def b_provider():
    yield 'b'


@fixture(params=["a_provider", "b_provider"])
def letter_provider(request):
    yield request.getfixturevalue(request.param)

我现在想在后端针对不同的测试用例运行一些额外的参数化测试。


@fixture()
def one(letter_provider):
    yield letter_provider * 1


@fixture()
def two(letter_provider):
    yield letter_provider * 2


@fixture(params=["one", "two"])
def letter_cases(request):
    yield request.getfixturevalue(request.param)

使用这两层固定装置,我希望能够运行由基本实现参数化的两个测试。

def test_foo(letter_provider):
    """
    Should run once for "a" and once for "b"
    """
    assert letter_provider in {"a", "b"}

以及使用所有额外案例的测试

def test_bar(letter_cases):
    """
    test should be executed 4 times for : a, aa, b, bb
    """
    assert letter_cases in {
        "a", "aa",
        "b", "bb",
    }

目前,我的测试设置失败了:

test setup failed
'letter_provider'

The above exception was the direct cause of the following exception:
letter_provider

During handling of the above exception, another exception occurred:
The requested fixture has no parameter defined for test:
    tests/test_example.py::test_bar[one]

Requested fixture 'letter_provider' defined in:
tests/test_example.py:15

我如何设置我的测试套件来运行这些级别的参数化?

最佳答案

在调用 getfixturevalue() 时,通过将两个 fixture 添加为 letter_cases,确保 fixture 缓存中填充了 onetwo fixture 值 依赖:

@fixture(params=["one", "two"])
def letter_cases(request, <b>one, two</b>):
    yield request.getfixturevalue(request.param)

关于python - Pytest:请求 fixture 的嵌套使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65993136/

相关文章:

unit-testing - 如果不等于真实值 num_steps 则发出警报

python - Pytest:查找每个测试的开始和结束时间

python - MongoDB Atlas 中新集群的默认密码

python - 没有创建它应该创建的 csv 文件

python-3.x - 无法连接到 HTTPS URL,因为 SSL 模块不可用

python - 更好的方法去堆叠 Pandas 行?

python - 无法读取使用不同方法写入的文件的内容

python - 列表列表的总和;返回总和列表

python - 理解 python 中的 lambda 并使用它来传递多个参数

Python 带条件断言