pytest.mark.parametrize 是pytest用来参数化测试的一个装饰器,它允许你为测试函数或测试类提供多组参数list, 这样就可以使用每组参数执行测试函数或测试类,实现参数化驱动,接收的是元组集

参数类型简介

pytest.mark.parametrize 可接收三个参数,常用的有两个,第一个是函数中需要引用的参数名,第二个是参数值,会自动解析参数值并赋值到参数名上,按顺序将最小的迭代单元赋值到参数上

参数名:必填参数,传字符串类型,字符串中可以定义一个或者多个参数名,用逗号分隔开

参数值:必填参数,可迭代的对象,比如列表、元组、集合等等, 注意:参数值可以使用变量,但是不能传装饰器

ids:可选参数,标记每一组数据,在测试输出中展示,如下图所示

基本用法

点击查看代码
import pytest

# 单个参数
@pytest.mark.parametrize("number", [1, 2, 3])
def test_square(number):
assert number * number == number**2 # 多个参数
@pytest.mark.parametrize("a, b, expected", [
(1, 2, 3),
(4, 5, 9),
(10, -1, 9)
])
def test_add(a, b, expected):
assert a + b == expected

高级用法

1. 参数化类(所有方法使用相同参数)

点击查看代码
@pytest.mark.parametrize("n", [5, 10])
class TestMath:
def test_double(self, n):
assert n * 2 == 2 * n def test_triple(self, n):
assert n * 3 == 3 * n

2. 嵌套参数化(参数组合)

点击查看代码
@pytest.mark.parametrize("x", [0, 1])
@pytest.mark.parametrize("y", [2, 3])
def test_combinations(x, y):
# 将生成4组测试: (0,2), (0,3), (1,2), (1,3)
assert x + y == y + x

3. 使用ID自定义测试名称

点击查看代码
@pytest.mark.parametrize("input, expected", [
(3, 9),
(4, 16),
(5, 25)
], ids=["3^2=9", "4^2=16", "5^2=25"]) # 自定义测试ID
def test_square_ids(input, expected):
assert input**2 == expected

4. 从函数动态生成参数

点击查看代码
def generate_data():
return [(i, i*10) for i in range(1, 4)] @pytest.mark.parametrize("input, expected", generate_data())
def test_dynamic_params(input, expected):
assert input * 10 == expected

5. 参数化+Fixture组合

点击查看代码
@pytest.fixture
def db_connection():
return {"status": "connected"} @pytest.mark.parametrize("user", ["alice", "bob", "charlie"])
def test_users(db_connection, user):
assert db_connection["status"] == "connected"
print(f"Testing user: {user}")

最佳实践

1.参数命名:使用有意义的参数名

点击查看代码
# 推荐
@pytest.mark.parametrize("username, password", [("user1", "pass1")]) # 不推荐
@pytest.mark.parametrize("a, b", [("user1", "pass1")])

2.复杂数据结构:使用字典提高可读性

点击查看代码
@pytest.mark.parametrize("data", [
{"input": {"a": 1, "b": 2}, "expected": 3},
{"input": {"a": -1, "b": 1}, "expected": 0}
])
def test_complex(data):
result = data["input"]["a"] + data["input"]["b"]
assert result == data["expected"]

3.共享参数:定义在模块顶部

点击查看代码
# 在文件顶部定义
COMMON_PARAMS = [
(1, 1, 2),
(2, 3, 5),
(5, 5, 10)
] @pytest.mark.parametrize("a, b, expected", COMMON_PARAMS)
def test_addition(a, b, expected):
assert a + b == expected

4.跳过特定用例:使用 pytest.param

点击查看代码
@pytest.mark.parametrize("a, b, expected", [
(1, 2, 3),
pytest.param(1, "a", TypeError, marks=pytest.mark.xfail),
(5, 5, 10)
])
def test_mixed_types(a, b, expected):
if isinstance(expected, type):
with pytest.raises(expected):
a + b
else:
assert a + b == expected

pytest.mark.parametrize 传参的更多相关文章

  1. pytest 12 函数传参和fixture传参数request

    前沿: 有的case,需要依赖于某些特定的case才可以执行,比如,登陆获取到的cookie,每次都需要带着他,为了确保是同一个用户,必须带着和登陆获取到的同一个cookies. 大部分的用例都会先登 ...

  2. Pytest系列(9) - 参数化@pytest.mark.parametrize

    如果你还想从头学起Pytest,可以看看这个系列的文章哦! https://www.cnblogs.com/poloyy/category/1690628.html 前言 pytest允许在多个级别启 ...

  3. pytest自动化6:pytest.mark.parametrize装饰器--测试用例参数化

    前言:pytest.mark.parametrize装饰器可以实现测试用例参数化. parametrizing 1.  下面是一个简单是实例,检查一定的输入和期望输出测试功能的典型例子 2.  标记单 ...

  4. pytest.mark.parametrize()参数化应用二,读取json文件

    class TestEnorll(): def get_data(self): """ 读取json文件 :return: """ data ...

  5. pytest.mark.parametrize()参数化的应用一

    from page.LoginPage import Loginpage import os, sys, pytest base_dir = os.path.dirname(os.path.dirna ...

  6. pytest - 测试函数的传参:fixture,参数化。必须传入实参

    测试函数的参数只有2个来源:fixture返回,参数化(ddt) 传入的参数必须是实参 pytest - 参数化 在测试用例的前面加上: @pytest.mark.parametrize(" ...

  7. 5.@pytest.mark.parametrize()数据驱动

    简介: pytest.mark.parametrize 是 pytest 的内置装饰器,它允许你在 function 或者 class 上定义多组参数和 fixture 来实现数据驱动. @pytes ...

  8. python+接口参数化(ddt和pytest.mark.parametrize())使用

    一.ddt(基于unittest) 实例:字典解包[{},{}] test_data=t.read_excel(mode,case_list)@ddt class Interface(unittest ...

  9. 【pytest】@pytest.fixture与@pytest.mark.parametrize结合实现参数化

    背景:测试数据既要在fixture方法中使用,同时也在测试用例中使用 使用方法:在使用parametrize的时候添加"indirect=True"参数.pytest可以实现将参数 ...

  10. pytest用例传参的多种方式

    1.接收外部传参 *函数获取需要的参数,再传入 *函数获登录信息,直接使用 2.其它方式传参 *依据dict取值 *tuple数组

随机推荐

  1. DeepSeek 开源周回顾「GitHub 热点速览」

    上周,DeepSeek 发布的开源项目用一个词形容就是:榨干性能!由于篇幅有限,这里仅列出项目名称和简介,感兴趣的同学可以前往 DeepSeek 的开源组织页面,深入探索每个项目的精彩之处! 第一天 ...

  2. 机器人技术的突破让OpenAI过时了

    机器人技术的突破让OpenAI过时了 Ignacio de Gregorio 最近,Figure AI,一家价值数十亿美元的AI机器人公司,宣布取消与OpenAI的合作伙伴关系,这一举动看起来是相当大 ...

  3. event.stopPropagation

    先记录一下坑:     var btn = test.getElementsByTagName('label');         btn[0].active = 'active';          ...

  4. 【Bug记录】uniapp开发时pages.json和manifest.json注释报错解决方案

    pages.json和manifest.json注释报错问题解决 增强 pages.json和 manifest.json 开发体验 json文件写注释 用 VsCode 开发 uni-app 项目时 ...

  5. python包管理工具pip使用手册

    pip是什么? pip 是 Python 标准库管理器,也就是一个工具让你安装不同的类库来使用. 当你要安装某些类库时,都会使用 pip,那 pip 除了安装类库之外,还能做什么呢? 首先,我们进入 ...

  6. Shell脚本实现服务器多台免密

    简介 本脚本(auto_ssh_batch.sh)用于在多台主机之间快速配置SSH免密登录,并支持远程传输脚本/文件及执行命令.通过 pass 文件提供统一认证凭据,通过 nodes 文件定义目标主机 ...

  7. Oracle中IMP导入数据时提示字符集不一致解决

     生产环境中经常使用到Oracle的IMP导入和EXP导出来功能来达到数据迁移的目的,通常在源数据库和目标数据库中查询字符集是否致, 测试环境中导入IMP导入报错信息如下: 导入命令如下: [orac ...

  8. MySQL中怎么分析性能?

    MySQL中主要有4种方式可以分析数据库性能,分别是慢查询日志,profile,Com_xxx和explain. 慢查询日志 先用下面命令查询慢查询日志是否开启, show variables lik ...

  9. 关于DevExpress VCL汉化方法

    用法1:在工程中加入控件cxLocalizer; 在程序中加入如下语句: Localizer.LoadFromFile('DevLocal.ini'); Localizer.Language := ' ...

  10. 【JDBC第1章】JDBC概述

    第1章:JDBC概述 1.1 数据的持久化 持久化(persistence):把数据保存到可掉电式存储设备中以供之后使用.大多数情况下,特别是企业级应用,数据持久化意味着将内存中的数据保存到硬盘上加以 ...