pytest的参数化

参数化有两种方式:

1、

@pytest.mark.parametrize

2、利用conftest.py里的

pytest_generate_tests

 

1中的例子如下:

@pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 42)])
def test_eval(test_input, expected):
    assert eval(test_input) == expected

 2中的例子(自己定义参数化,pytest_generate_tests 是在收集测试方法时会被调用)的:

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"))

a_test.py
def test_valid_string(stringinput):
    assert stringinput.isalpha()

执行测试:
pytest -q --stringinput="hello" --stringinput="world" a_test.py


参数化参考地址:
https://docs.pytest.org/en/latest/parametrize.html#pytest-mark-parametrize-parametrizing-test-functions

相关文章

目录1、前言2、mark的使用(一)注册自定义标记(二)在测试...
用例执行状态用例执行完成后,每条用例都有自己的状态,常见...
什么是conftest.py可以理解成一个专门存放fixture的配置文件...
前言pytest默认执行用例是根据项目下的文件名称按ascii码去收...
前言:什么是元数据?元数据是关于数据的描述,存储着关于数...