Python中有一个重要的特性是,装饰器、类属性、模块变量都是模块加载时立即执行的。因此在使用@pytest.mark.parametrize进行参数话的时候,数据一般是确定的,如下例:
import pytest
DATA = [
    "a.txt",
    "b.txt",
    "c.txt",
]
@pytest.mark.parametrize('filepath', DATA)
def test_a(filepath):
    print('test_a', filepath)即使你将DATA改成通过函数获取,也无法动态根据一些参数,例如:
import pytest
def get_data():
    return [
        "a.txt",
        "b.txt",
        "c.txt",
    ]
@pytest.mark.parametrize('filepath', get_data()) # get_data在模块导入时就立即执行
def test_a(filepath):
    print('test_a', filepath)即使get_data设计有参数, 在装饰器调用时,参数也必须是去定的。
使用fixture函数的params参数(也是装饰器)也是一样的问题(需要确定的数据)。
如果想动态比如根据命令行参数进行参数话,需要用到pytest_generate_tests,示例如下:
# conftest.py
def pytest_addoption(parser):
    parser.addoption(
        "--filepath", action="append",
        default=[], help="run file list"
    )
def pytest_generate_tests(metafunc):
    if "filepath" in metafunc.fixturenames:
        metafunc.parametrize("filepath",
                             metafunc.config.getoption("filepath"))# test_a.py
def test_a(filepath):
    print('test_a', filepath)运行命令
pytest test_a.py -sv --filepath a.txt --filepath b.txt --filepath c.txt效果如下图:

参考:https://docs.pytest.org/en/7.1.x/how-to/parametrize.html#basic-pytest-generate-tests-example
    
    










