pytest简易教程(08):fixture标志传参
pytest简易教程汇总,详见:https://www.cnblogs.com/uncleyong/p/17982846
特点
1 2 3 4 5 | 1. 采用pytest.mark.xxx(参数)标志所需要的参数,然后在fixture中可以做一些逻辑处理 2. fixture采用request获取参数 3. 传参的个数可以是多个,类型可以为简单类型或者复杂对象 |
示例
简单类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : 韧 # @wx :ren168632201 # @Blog :https://www.cnblogs.com/uncleyong/ import pytest @pytest.fixture def fun(request): marker = request.node.get_closest_marker( "mydata" ) if marker is None: data = None else : data = marker.args[0] + 1 return data @pytest.mark.mydata(1) def test_data(fun): print( "fun={}" .format(fun)) if __name__ == '__main__' : pytest.main([ '-vs' ]) |
结果:
复杂类型
也可以是其它类型,比如列表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : 韧 # @wx :ren168632201 # @Blog :https://www.cnblogs.com/uncleyong/ import pytest @pytest.fixture def fun(request): marker = request.node.get_closest_marker( "mydata" ) if marker is None: data = None else : data = marker.args[0] data[-1]=666 return data @pytest.mark.mydata([1,2,3]) def test_data(fun): print( "fun={}" .format(fun)) if __name__ == '__main__' : pytest.main([ '-vs' ]) |
结果:
可以传多个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : 韧 # @wx :ren168632201 # @Blog :https://www.cnblogs.com/uncleyong/ import pytest @pytest.fixture def fun(request): marker = request.node.get_closest_marker( "mydata" ) marker2 = request.node.get_closest_marker( "mydata2" ) if marker is None: data = None else : data = marker.args[0] data[-1]=666 if marker2 is None: data2 = None else : data2 = marker2.args[0] + 1 return data,data2 @pytest.mark.mydata([1,2,3]) @pytest.mark.mydata2(1) def test_data(fun): print( "fun={}" .format(fun)) if __name__ == '__main__' : pytest.main([ '-vs' ]) |
结果:
补充:命令行执行,需要在pytest.ini文件中加配置:
1 2 3 4 | [pytest] markers = mydata mydata2 |
结果:
__EOF__

本文作者:持之以恒(韧)
关于博主:擅长性能、全链路、自动化、企业级自动化持续集成(DevTestOps)、测开等
面试必备:项目实战(性能、自动化)、简历笔试,https://www.cnblogs.com/uncleyong/p/15777706.html
测试提升:从测试小白到高级测试修炼之路,https://www.cnblogs.com/uncleyong/p/10530261.html
欢迎分享:如果您觉得文章对您有帮助,欢迎转载、分享,也可以点击文章右下角【推荐】一下!
关于博主:擅长性能、全链路、自动化、企业级自动化持续集成(DevTestOps)、测开等
面试必备:项目实战(性能、自动化)、简历笔试,https://www.cnblogs.com/uncleyong/p/15777706.html
测试提升:从测试小白到高级测试修炼之路,https://www.cnblogs.com/uncleyong/p/10530261.html
欢迎分享:如果您觉得文章对您有帮助,欢迎转载、分享,也可以点击文章右下角【推荐】一下!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2022-02-23 答疑记录:jmeter从返回的html中提取指定内容