pytest文档68-pytest-lazy-fixture 插件解决 pytest.mark.parametrize 中使用 fixture 问题

前言

测试用例参数化的时候,使用 pytest.mark.parametrize 参数化传测试数据,如果我们想引用前面 不同fixture 返回的数据当测试用例的入参,前面一篇用fixture 参数化 prams 来间接解决这个问题。
接下来用 pytest-lazy-fixture 插件可以直接在测试用例中参数化时 pytest.mark.parametrize 中使用 fixture

pytest-lazy-fixture 插件

pytest-lazy-fixture 插件是为了解决测试用例中用 @pytest.mark.parametrize 参数化调用fixture的问题,先pip安装

pip install pytest-lazy-fixture

目前使用的版本是 0.6.3

>pip show pytest-lazy-fixture
Name: pytest-lazy-fixture
Version: 0.6.3
Summary: It helps to use fixtures in pytest.mark.parametrize
Home-page: https://github.com/tvorog/pytest-lazy-fixture
Author: Marsel Zaripov
Author-email: marszaripov@gmail.com
License: MIT
Location: e:\python36\lib\site-packages
Requires: pytest
Required-by:

parametrize 使用示例

参数化的时候,其中一些测试数据,来源于前面的 fixture

import pytest
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/


@pytest.fixture(params=[1, 2])
def one(request):
    return request.param


@pytest.mark.parametrize('arg1,arg2', [
    ('val1', pytest.lazy_fixture('one')),
])
def test_func(arg1, arg2):
    print(arg1, arg2)
    assert arg2 in [1, 2]

运行结果

..\test_y.py val1 1
.val1 2
.

============== 2 passed in 0.04 seconds ===========

fixture 参数化 params

在 fixture 参数化的 params 中也可以使用

import pytest
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/

@pytest.fixture
def one():
    return 1


@pytest.fixture
def two():
    return 2


@pytest.fixture(params=[
    pytest.lazy_fixture('one'),
    pytest.lazy_fixture('two')
])
def some(request):
    return request.param


def test_func(some):
    assert some in [1, 2]

pytest-lazy-fixture 相关的使用可以查看github 地址https://github.com/TvoroG/pytest-lazy-fixture

网易云完整视频课程《pytest+yaml 框架使用与开发》https://study.163.com/course/courseMain.htm?courseId=1213419817&share=2&shareId=480000002230338

posted @   上海-悠悠  阅读(2018)  评论(3编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-12-07 关于面试总结4-python笔试题
点击右上角即可分享
微信分享提示