pytest源码_pytest文档74参数化parametrize加marks标记(pytest.param)

本文介绍了如何在pytest中使用pytest.param进行参数化测试,包括设置参数值、应用skip标记以及自定义测试用例ID。通过示例展示了如何通过pytest.param创建测试数据并指定测试用例的跳过行为,以及为测试用例添加更具描述性的ID。
摘要由CSDN通过智能技术生成

前言

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 `.
.. 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参数的时候,用例会默认拿请求的参数当用例标题dfc661810899db6adcce888f0cfd4d85.png

添加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

运行结果f1f758b7f57b11772ccab2ff88958b7b.png

2021年第六期《python接口自动化+测试开发》课程,1月9号开学(火热报名中!)

本期上课时间:1月9号-4月18号,每周六、周日晚上20:30-22:30联系微信/QQ:283340479

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值