parametrize变量传递的应用场景是什么,具体用法是怎样
Admin 2022-08-17 群英技术资讯 730 次浏览
ok,大背景是这样的。
现在有小伙伴来需求了,她要在setup_before()里去造数,通过请求另一个接口,这个请求也需要使用token。
那么,问题也就可以转化为:
这里把实际代码抽象一下,转化为简易代码,方便演示和理解:
# 目录结构 -- /demo_top -- /demo_sub __init__.py conftest.py test_case.py __init__.py conftest.py
以下分别是/demo_top/conftest.py、/demo_top/demo_sub/conftest.py、/demo_top/demo_sub/test_case.py的内容。
# content of /demo_top/conftest.py import pytest @pytest.fixture() def gen_token(request): params = request.param print("\n根目录下gen_token()拿到的参数:", params) if params[0] + params[1] == 5: return "api_token" else: return None
这里,模拟生成token的fixture函数,当传过来的值相加等于5,就会返回"api_token",否则返回None。
# content of /demo_top/demo_sub/conftest.py import pytest @pytest.fixture() def setup_before(request, gen_token): print("执行子级setup_before,拿到的传参:", request.param) print("执行子级setup_before,拿到gen_token的返回值:", gen_token) if gen_token: yield "造数完成" print("测试用例test_case执行完毕,清理测试数据") else: pytest.skip("跳过")
这里模拟了给测试用例造数据的fixture函数,如果没拿到token的话,就跳过测试用例。
# content of /demo_top/demo_sub/test_case.py import pytest test_param = [(1, 4)] @pytest.mark.parametrize("gen_token", test_param, indirect=True) @pytest.mark.parametrize("setup_before", test_param, indirect=True) def test_case1(gen_token, setup_before): print("\n测试用例里拿到的gen_token返回值:", gen_token) print("测试用例里拿到的setup_before返回值:", setup_before) print("执行测试用例test_case1...") if __name__ == '__main__': pytest.main(['-s', 'test_case.py'])
这是测试用例文件了,里面有个测试函数test_case1,因为它需要用到2个fixture函数返回的值,所以gen_token, setup_before都请求。
fixture之间的相互调用,在之前的文章里已经有过详述了。既然这里setup_before依赖gen_token,之间传递调用即可setup_before(request, gen_token)。
在各环节做了些print打印出信息,帮助理解执行过程。
test_case.py [100%] ============================== 1 passed in 0.08s ============================== 根目录下gen_token()拿到的参数: (1, 4) 执行子级setup_before,拿到的传参: (1, 4) 执行子级setup_before,拿到gen_token的返回值: api_token . 测试用例里拿到的gen_token返回值: api_token 执行测试用例test_case1... 测试用例test_case执行完毕,清理测试数据 Process finished with exit code 0
再看下gen_token不返回token的情况,改下传参test_param = [(2, 4)]。
test_case.py [100%] ============================= 1 skipped in 0.08s ==============================s 根目录下gen_token()拿到的参数: (2, 4) 执行子级setup_before,拿到的传参: (2, 4) 执行子级setup_before,拿到gen_token的返回值: None Skipped: 跳过 Process finished with exit code 0
测试用例不执行。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
装饰器(Decorators)是 Python 的一个重要部分,本文由浅入深给大家介绍了python 装饰器Decorators原理,感兴趣的朋友跟随小编一起看看吧
python编码格式导致csv读取错误问题(csv.reader, pandas.csv_read),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
提供日志记录的接口和众多处理模块,供用户存储各种格式的日志,帮助调试程序或者记录程序运行过程中的输出信息,这篇文章主要介绍了Python 内置logging 使用讲解,需要的朋友可以参考下
本文给大家分享了作者整理的五个python游戏开发的案例,通过具体设计思路,代码等方面详细了解python游戏开发的过程,非常的详细,希望大家能够喜欢
在本篇文章里小编给大家整理的是一篇关于python引入其他文件夹下的py文件具体方法,有兴趣朋友们可以跟着学习参考下。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008