pytest 将命令行选项传递给测试脚本但不测试函数

pytest pass cmd line options to test scripts but not to test function

我的 test_sample.py 就像:

import pytest

a,b = myclass('cmdopts').get_spec()

def gen_args(a, b):
    for i in a:
        for j in b:
            yield (i,j)
@pytest.mark.parametrize('a,b', gen_args(a,b))
def test_c1(a, b):
    assert a == b

我的问题是如何将 cmdopts 传递给测试脚本,而不是 test_c1 函数?

pytest.mark.parametrize 不适合以这种方式使用。

使用 pytest_addoption 的 pytest 你可以使用 metafunc.parametrize

注入你的 a, b 参数

使用此技术还可以在环境变量中设置参数。

conftest.py

def pytest_addoption(parser):
    parser.addoption("--a", action="store")
    parser.addoption("--b", action="store")


def pytest_generate_tests(metafunc):
    for par_name, par_value in (
            ('a',metafunc.config.option.a),
            ('b',metafunc.config.option.b)
        ):
        if par_name in metafunc.fixturenames and par_value:
            metafunc.parametrize(par_name, [par_value])

test_sample.py

def test_c1(a, b):
    assert a == b

CLI

$ pytest test_sample.py --a 42 --b 42

collected 1 item                                                                                                                                                                            

test_sample.py .                                                                                                                                                                      [100%]

= 1 passed in 0.01s =


$ pytest test_sample.py --a 42 --b 24

collected 1 item                                                                                                                                                                            

test_sample.py F                                                                                                                                                                      [100%]

= FAILURES =
_ test_c1[42-24] _

a = '42', b = '24'

    def test_c1(a, b):
>       assert a == b
E       AssertionError: assert '42' == '24'
E         - 24
E         + 42

test_sample.py:2: AssertionError
================================================================================== short test summary info ==================================================================================
FAILED test_sample.py::test_c1[42-24] - AssertionError: assert '42' == '24'
===================================================================================== 1 failed in 0.07s

此处类似:How to pass arguments in pytest by command line