pytest文档67-pytest.mark.parametrize 中使用 fixture

前言

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

使用案例

我们需要在测试用例里面参数化,参数化的数据来源于前面不同fixture的返回值,示例

import pytest


@pytest.fixture
def a():
    return 'a'


@pytest.fixture
def b():
    return 'b'


@pytest.mark.parametrize('arg', [a, b])
def test_foo(arg):
    assert len(arg) == 1

这时候运行会报错


..\test_xx.py F
arg = <function a at 0x000001C7E77CE7B8>

    @pytest.mark.parametrize('arg', [a, b])
    def test_foo(arg):
>       assert len(arg) == 1
E       TypeError: object of type 'function' has no len()

\test_xx.py:16: TypeError
F
arg = <function b at 0x000001C7E77CE8C8>

    @pytest.mark.parametrize('arg', [a, b])
    def test_foo(arg):
>       assert len(arg) == 1
E       TypeError: object of type 'function' has no len()

\test_xx.py:16: TypeError

关于此问题的讨论可以看github 上的issue Using fixtures in pytest.mark.parametrize #349

使用 fixture 参数化

可以使用 fixture 的参数化来解决上面的问题,通过 request.getfixturevalue(“fixture name”) 方法来获取fixture的返回值
有些文档看到的是 request.getfuncargvalue 那是早期的版本,目前新版本改名换成了 request.getfixturevalue
getfixturevalue 的作用是获取 fixture 的返回值

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

@pytest.fixture
def a():
    return 'a'


@pytest.fixture
def b():
    return 'b'


@pytest.fixture(params=['a', 'b'])
def arg(request):
    return request.getfixturevalue(request.param)


def test_foo(arg):
    assert len(arg) == 1

这样运行就不会有问题了

实例场景

web自动化的时候,想在 chrome 和 firefox 浏览器上测试同一功能的测试用例

import pytest
from selenium import webdriver

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

@pytest.fixture
def chrome():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

@pytest.fixture
def firefox():
    driver = webdriver.Firefox()
    yield driver
    driver.quit()


@pytest.fixture(params=['chrome', 'firefox'])
def driver(request):
    '''启动浏览器参数化'''
    return request.getfixturevalue(request.param)


def test_foo(driver):
    '''测试用例'''
    driver.get("https://www.cnblogs.com/yoyoketang/")

这样就可以分别打开 chrome 和 fixfox 执行测试用例了
关于此问题的更多讨论可以看github 上的issue Using fixtures in pytest.mark.parametrize #349
还有另外一个解决方案,使用 pytest-lazy-fixture 插件解决 https://www.cnblogs.com/yoyoketang/p/14096749.html

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

posted @   上海-悠悠  阅读(2856)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· 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笔试题
点击右上角即可分享
微信分享提示