parametrize参数化
1.pytest.mark.parametrize装饰器可以实现用例参数化
第一个参数是字符串,多个参数中间用逗号隔开
第二个参数是list,多组数据用元祖类型
下面这个例子使用@parametrize装饰器定义了3个不同的(test_input,expected) 元组,以便该test_eval函数依次使用它们运行3次:
@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
只有最后一对输入输出执行失败:
现在我们使用pytest.mark.xfail
将最后一对参数标记成“ xfailed(预期失败)”
@pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), pytest.param("6*9", 42, marks=pytest.mark.xfail)])
def test_eval(test_input, expected):
assert eval(test_input) == expected
2.参数组合,下面的x和y组成4组数据
@pytest.mark.parametrize("x", [0, 1])
@pytest.mark.parametrize("y", [2, 3])
empty_parameter_set_mark,空实参处理
默认情况下,如果@pytest.mark.parametrize的argnames中的参数没有接收到任何的实参的话,用例的结果将会被置为skiped;
允许为参数化中的空参数集选择操作,如果参数化的列表是一个空列表,比如参数是某个函数动态生成的empty_parameter_set_mark
允许为参数化中的空参数集选择操作。
1)skip 跳过带有空参数集的测试(默认),执行用例默认跳过skiped
#parametrize装饰器列表中参数值是空
@pytest.mark.parametrize("test_input,expected", [])
def test_eval(test_input, expected):
assert eval(test_input) == expected
2)xfail 将带有空参数集的测试标记为xfail(run = False)
在pytest.ini文件中添加empty_parameter_set_mark = xfail
,再执行空参数用例,默认失败xfailed
[pytest]
empty_parameter_set_mark = xfail
3)fail_at_collect 如果参数收集空参数集,则会引发异常
[pytest]
empty_parameter_set_mark = fail_at_collect
pytest_generate_tests,根据命令行生成参数组合
有时可能想要实现自己的参数化方案或实现某种动态性来确定灯具的参数或范围。为此,可以使用pytest_generate_tests在收集测试函数时调用的钩子。
通过传入的 metafunc对象,您可以检查请求的测试上下文,最重要的是,可以调用metafunc.parametrize()引起参数化。
假设我们要使用不同的计算参数执行测试,并且参数范围应由命令行参数确定。让我们首先编写一个简单的(不做任何事情)计算测试
def test_compute(param1):
assert param1 < 4
现在,我们在conftest.py中添加如下测试配置:
#content of conftest.py
def pytest_addoption(parser):
parser.addoption("--all", action="store_true", help="run all combinations")
def pytest_generate_tests(metafunc):
if "param1" in metafunc.fixturenames:
if metafunc.config.getoption("all"):
end = 5
else:
end = 2
metafunc.parametrize("param1", range(end))
pytest-datadir读取文件信息
pytest-datadir是一个第三方插件,需要安装
pip install pytest-datadir
用于操作测试数据目录和文件的插件。pytest-datadir他会寻找包含测试模块名字的文件夹或者全局的一个文件夹名字为data下的数据。
参考地址:
https://www.cnblogs.com/peiminer/p/9871242.html
skip跳过测试用例
pytest.mark.skip可以标记无法在某些平台上运行的测试功能,或者你希望失败的测试功能。支持skip函数,类,模块。
建议不要在使用继承的类上使用skipif。 pytest中的一个已知错误标记可能会导致超类中的意外行为
1.无条件地跳过模块中的所有测试:
pytestmark = pytest.mark.skip(“all tests still WIP”)
2.根据某些条件跳过模块中的所有测试
pytestmark = pytest.mark.skipif(sys.platform == “win32”, “tests for linux
˓→ only”
3.如果缺少某些导入,则跳过模块中的所有测试
pexpect = pytest.importorskip(“pexpect”)