pytest 官网 -《How to parametrize fixtures and test functions》
如何使用的话,先看一下官网给出的例子
# content of test_strings.py
def test_valid_string(stringinput):
assert stringinput.isalpha()
# content of conftest.py
def pytest_addoption(parser):
parser.addoption(
"--stringinput",
action="append",
default=[],
help="list of stringinputs to pass to test functions",
)
def pytest_generate_tests(metafunc):
if "stringinput" in metafunc.fixturenames:
metafunc.parametrize("stringinput", metafunc.config.getoption("stringinput"))
$ pytest -q --stringinput="hello" --stringinput="world" test_strings.py
.. [100%]
2 passed in 0.12s
理解一下上面的意思,pytest_generate_tests是一个内置 hook函数, pytest运行这个hook时,对引用了 stringinput 的测试用例进行参数化。
如何进行的呢?
就是通过metafunc进行的, metafunc是测试用例节点元信息对象,修改metafunc就修改测试用例,调用parametrize方法就可以参数化,实际上与装饰器pytest.mark.parametrize()作用一样