在 Python 中动态参数化多个测试

Lou*_*Lou 5 python pytest python-3.x parametrized-testing

我正在尝试使用 Pytest 编写动态测试套件,其中测试数据保存在单独的文件中,例如 YAML 文件或 .csv。我想运行多个测试,所有这些测试都从同一个文件进行参数化。假设我有一个测试文件test_foo.py,如下所示:

import pytest

@pytest.mark.parametrize("num1, num2, output", ([2, 2, 4], [3, 7, 10], [48, 52, 100]))
def test_addnums(num1, num2, output):
    assert foo.addnums(num1, num2) == output

@pytest.mark.parametrize("foo, bar", ([1, 2], ['moo', 'mar'], [0.5, 3.14]))
def test_foobar(foo, bar):
    assert type(foo) == type(bar)
Run Code Online (Sandbox Code Playgroud)

使用参数化装饰器,我可以在 pytest 中运行多个测试,并且按预期工作:

test_foo.py::test_addnums[2-2-4] PASSED                                                                                                                                                            
test_foo.py::test_addnums[3-7-10] PASSED                                                                                                                                                           
test_foo.py::test_addnums[48-52-100] PASSED                                                                                                                                                        
test_foo.py::test_foobar[1-2] PASSED                                                                                                                                                               
test_foo.py::test_foobar[moo-mar] PASSED                                                                                                                                                           
test_foo.py::test_foobar[0.5-3.14] PASSED
Run Code Online (Sandbox Code Playgroud)

但我想动态地参数化这些测试。我的意思是,我想将所有测试的测试数据写入一个单独的文件中,以便当我运行 pytest 时,它将应用我写入每个测试函数的所有测试数据。假设我有一个类似于以下内容的 YAML 文件:

test_addnums:
  params: [num1, num2, output]
  values:
    - [2, 2, 4]
    - [3, 7, 10]
    - [48, 52, 100]

test_foobar:
  params: [foo, bar]
  values:
    - [1, 2]
    - [moo, mar]
    - [0.5, 3.14]
Run Code Online (Sandbox Code Playgroud)

然后,我想要读取此 YAML 文件并使用该数据来参数化测试文件中的所有测试函数。

我知道这个pytest_generate_tests钩子,并且我一直在尝试使用它来动态加载测试。我尝试将之前传递给parametrize装饰器的相同参数和数据值添加到metafunc.parametrize挂钩中:

def pytest_generate_tests(metafunc):
    metafunc.parametrize("num1, num2, output", ([2, 2, 4], [3, 7, 10], [48, 52, 100]))
    metafunc.parametrize("foo, bar", ([1, 2], ['moo', 'mar'], [0.5, 3.14]))

def test_addnums(num1, num2, output):
    assert foo.addnums(num1, num2) == output

def test_foobar(foo, bar):
    assert type(foo) == type(bar)
Run Code Online (Sandbox Code Playgroud)

然而,这不起作用,因为 pytest 尝试将测试数据应用于每个函数:

collected 0 items / 1 error                                           

=============================== ERRORS ================================
____________________ ERROR collecting test_foo.py _____________________
In test_addnums: function uses no argument 'foo'
======================= short test summary info =======================
ERROR test_foo.py
!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!
========================== 1 error in 0.16s ===========================
Run Code Online (Sandbox Code Playgroud)

我想知道的是:如何使用 pytest动态参数化多个测试?我使用 pdb 内省了 pytest,据我所知,metafunc只知道您在文件中定义的第一个测试。在上面的示例中,test_addnums首先定义了 ,因此当我vars(metafunc)在 pdb 调试器中打印时,它会显示以下值:

(Pdb) pp vars(metafunc)
{'_arg2fixturedefs': {},
 '_calls': [<_pytest.python.CallSpec2 object at 0x7f4330b6e860>,
            <_pytest.python.CallSpec2 object at 0x7f4330b6e0b8>,
            <_pytest.python.CallSpec2 object at 0x7f4330b6e908>],
 'cls': None,
 'config': <_pytest.config.Config object at 0x7f43310dbdd8>,
 'definition': <FunctionDefinition test_addnums>,
 'fixturenames': ['num1', 'num2', 'output'],
 'function': <function test_addnums at 0x7f4330b5a6a8>,
 'module': <module 'test_foo' from '<PATH>/test_foo.py'>}
Run Code Online (Sandbox Code Playgroud)

但是,如果我切换test_foobartest_addnums函数,并颠倒调用顺序parametrize,它会显示有关的信息test_foobar

(Pdb) pp vars(metafunc)
{'_arg2fixturedefs': {},
 '_calls': [<_pytest.python.CallSpec2 object at 0x7f6d20d5e828>,
            <_pytest.python.CallSpec2 object at 0x7f6d20d5e860>,
            <_pytest.python.CallSpec2 object at 0x7f6d20d5e898>],
 'cls': None,
 'config': <_pytest.config.Config object at 0x7f6d212cbd68>,
 'definition': <FunctionDefinition test_foobar>,
 'fixturenames': ['foo', 'bar'],
 'function': <function test_foobar at 0x7f6d20d4a6a8>,
 'module': <module 'test_foo' from '<PATH>/test_foo.py'>}
Run Code Online (Sandbox Code Playgroud)

所以看起来 metafunc 实际上并没有在我的测试文件中存储有关每个测试函数的信息。因此,我无法使用fixturenamesfunction属性,因为它们仅适用于一个特定函数,而不适用于所有函数。

如果是这种情况,那么我如何访问所有其他测试函数并单独参数化它们?

MrB*_*men 7

您可以使用 来执行此操作pytest_generate_tests,正如您所尝试的那样,您只需为每个函数选择正确的参数进行参数化(为了简单起见,我将解析 yaml 的结果放入全局字典中):

all_params = {
    "test_addnums": {
        "params": ["num1", "num2", "output"],
        "values":
            [
                [2, 2, 4],
                [3, 7, 10],
                [48, 52, 100]
            ]
    },
    "test_foobar":
        {
            "params": ["foo", "bar"],
            "values": [
                [1, 2],
                ["moo", "mar"],
                [0.5, 3.14]
            ]
        }
}


def pytest_generate_tests(metafunc):
    fct_name = metafunc.function.__name__
    if fct_name in all_params:
        params = all_params[fct_name]
        metafunc.parametrize(params["params"], params["values"])


def test_addnums(num1, num2, output):
    assert num1 + num2 == output


def test_foobar(foo, bar):
    assert type(foo) == type(bar)
Run Code Online (Sandbox Code Playgroud)

这是相关的输出:

$python -m pytest -v param_multiple_tests.py
...
collected 6 items

param_multiple_tests.py::test_addnums[2-2-4] PASSED
param_multiple_tests.py::test_addnums[3-7-10] PASSED
param_multiple_tests.py::test_addnums[48-52-100] PASSED
param_multiple_tests.py::test_foobar[1-2] PASSED
param_multiple_tests.py::test_foobar[moo-mar] PASSED
param_multiple_tests.py::test_foobar[0.5-3.14] PASSED
===================== 6 passed in 0.27s =======================
Run Code Online (Sandbox Code Playgroud)

我认为您在文档中错过的是pytest_generate_tests每个测试单独调用。更常见的使用方法是检查夹具名称而不是测试名称,例如:

$python -m pytest -v param_multiple_tests.py
...
collected 6 items

param_multiple_tests.py::test_addnums[2-2-4] PASSED
param_multiple_tests.py::test_addnums[3-7-10] PASSED
param_multiple_tests.py::test_addnums[48-52-100] PASSED
param_multiple_tests.py::test_foobar[1-2] PASSED
param_multiple_tests.py::test_foobar[moo-mar] PASSED
param_multiple_tests.py::test_foobar[0.5-3.14] PASSED
===================== 6 passed in 0.27s =======================
Run Code Online (Sandbox Code Playgroud)