pytest文档74-参数化parametrize加marks标记(pytest.param)
前言
pytest 使用 parametrize 参数化的时候,有多组测试数据,需要对其中的一些测试数据加标记跳过,可以用pytest.param实现。
pytest.param
先看下 pytest.param 源码,可以传三个参数
- param values :按顺序传参数集值的变量args
- keyword marks : marks关键字参数,要应用于此参数集的单个标记或标记列表。
- keyword str id: id字符串关键字参数,测试用例的id属性
def param(*values, **kw):
"""Specify a parameter in `pytest.mark.parametrize`_ calls or
:ref:`parametrized fixtures <fixture-parametrize-marks>`.
.. code-block:: python
@pytest.mark.parametrize("test_input,expected", [
("3+5", 8),
pytest.param("6*9", 42, marks=pytest.mark.xfail),
])
def test_eval(test_input, expected):
assert eval(test_input) == expected
:param values: variable args of the values of the parameter set, in order.
:keyword marks: a single mark or a list of marks to be applied to this parameter set.
:keyword str id: the id to attribute to this parameter set.
"""
return ParameterSet.param(*values, **kw)
使用示例
import pytest
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
@pytest.mark.parametrize("test_input,expected", [
("3+5", 8),
pytest.param("6*9", 42, marks=pytest.mark.xfail),
])
def test_eval(test_input, expected):
assert eval(test_input) == expected
运行结果:1 passed, 1 xfailed in 0.08 seconds
skip跳过用例
上面的案例是标记xfail,想标记skip跳过用例也是可以的
import pytest
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
@pytest.mark.parametrize("user,psw",
[("yoyo1", "123456"),
("yoyo2", "123456"),
pytest.param("yoyo3", "123456", marks=pytest.mark.skip)])
def test_login(user, psw):
print(user + " : " + psw)
assert 1 == 1
运行结果:2 passed, 1 skipped in 0.03 seconds
上面的2个参数也可以用pytest.param格式
import pytest
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
@pytest.mark.parametrize("user,psw",
[pytest.param("yoyo1", "123456"),
pytest.param("yoyo2", "123456"),
pytest.param("yoyo3", "123456", marks=pytest.mark.skip)])
def test_login1(user, psw):
print(user + " : " + psw)
assert 1 == 1
id参数
id参数是给用例添加标题内容,没加id参数的时候,用例会默认拿请求的参数当用例标题
添加id参数
import pytest
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
@pytest.mark.parametrize("user,psw",
[pytest.param("yoyo1", "123456", id="test case1: yoyo1"),
pytest.param("yoyo2", "123456", id="test case2: yoyo2"),
pytest.param("yoyo3", "123456", marks=pytest.mark.skip, id="test case3: yoyo3")])
def test_login1(user, psw):
print(user + " : " + psw)
assert 1 == 1
运行结果