20、pytest中的参数化

官方实例

python 复制代码
# content of test_expectation.py

import pytest

@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
python 复制代码
# content of test_expectation_class
import pytest

@pytest.mark.parametrize("n, expected",[(1,2),(3,4)])
class TestClass:
    def test_simple_case(self, n, expected):
        assert n + 1 == expected
        
    def test_weird_simple_case(self, n, expected):
        assert (n * 1) + 1 == expected
python 复制代码
# content of test_parametrize_glob.py
import pytest

pytestmark = pytest.mark.parametrize("n,expected",[(1,2),(3,4)])

class TestClass:
    def test_simple_case(self, n, expected):
        assert n + 1 == expected

    def test_weird_simple_case(self, n, expected):
        assert (n * 1) + 1 == expected

解读与实操

内置的pytest.mark.parametrize装饰器允许对测试函数的参数进行参数化。

注意:参数值按原样传递给测试(没有任何副本),例如,如果你传递一个列表或字典作为参数值,并且测试用例代码对它进行了修改,那么这些修改将在随后的测试用例调用中反映出来。

请注意,你也可以在类或模块上使用参数化标记,类中的函数将调用带有参数集内容。

要将模块中的所有测试参数化,可以将其赋值给pytestmark全局变量。

场景应用

测试函数相同,只是传入参数不同,就可以用这种方法扩展测试用例。特别是针对列表的搜索功能,同一个搜索函数,但是存在多个搜索项。

相关推荐
小凯1234514 小时前
pytest框架-详解(学习pytest框架这一篇就够了)
python·学习·pytest
逻极14 小时前
pytest 入门指南:Python 测试框架从零到一(2025 实战版)
开发语言·python·pytest
网络安全-老纪15 小时前
一文2000字手把手教你自动化测试Selenium+pytest+数据驱动
自动化测试·软件测试·selenium·测试工具·pytest
程序员潇潇15 小时前
pytest 参数化测试用例构建
自动化测试·软件测试·功能测试·程序人生·职场和发展·测试用例·pytest
我的xiaodoujiao1 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 51--CI/CD 4--推送本地代码到Git远程仓库
python·学习·测试工具·ci/cd·pytest
先做个垃圾出来………1 天前
pytest冒烟测试用例过滤执行实例
windows·测试用例·pytest
清水白石0082 天前
《解锁 Python 潜能:从异步基石到 pytest-asyncio 高级测试实战与最佳实践》
运维·python·pytest
清水白石0084 天前
Fixture 的力量:pytest fixture 如何重新定义测试数据管理
数据库·python·pytest
七夜zippoe5 天前
单元测试进阶:pytest高级特性与实战秘籍
单元测试·pytest·持续集成·猴子补丁·fixtrue
我的xiaodoujiao9 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 48--本地环境部署Jenkins服务
python·学习·测试工具·pytest