遇一山,过一山,处处有风景;只要勇敢向前,一路尽是繁花盛开。 | (点击查看→)【测试干货】python/java自动化、持续集成、性能、测开、简历、笔试面试等

pytest简易教程(09):fixture返回值(实现参数化)

 

pytest简易教程汇总,详见https://www.cnblogs.com/uncleyong/p/17982846

特点

1
2
3
4
5
1. fixture可以通过设计params,让依赖该fixture的用例迭代执行
 
2. params数据可以为[列表],(元组),{集合},{字典}
 
3. params数据在fixture中通过request变量来接收

 

示例:fixture返回值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/
 
import pytest
 
@pytest.fixture
def fun():
    return 666
 
class TestX:
    def test_case(self, fun):
        print("---test_case")
        print(f"data={fun}")

  

结果:

 

如果fixture有返回值,用@pytest.mark.usefixtures()报错,无法获取到返回值

1
2
3
4
5
@pytest.mark.usefixtures(fun)
class TestX:
    def test_case(self):
        print("---test_case")
        print(f"data={fun}")

  

结果:

 

示例:fixture返回params中的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/
 
import pytest
 
@pytest.fixture(params=['韧','全栈测试笔记','性能测试','自动化测试','测试开发'])
def fun(request):  # 必须是request这个参数名
    return request.param  # 依次取列表中的每个值返回
 
class TestX:
    def test_case(self, fun):
        print(f"---test_case,data={fun}")

  

结果:

 

示例:也可以yield返回

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/
 
import pytest
 
 
@pytest.fixture(params=['韧', '全栈测试笔记', '性能测试', '自动化测试', '测试开发'])
def fun(request):  # 必须是request这个参数名
    print("---前置")
    yield request.param  # 依次取列表中的每个值返回
    print("---后置")
 
class TestX:
    def test_case(self, fun):
        print(f"---test_case,data={fun}")

  

结果:

 

笛卡尔积

应用场景:需要传多个参数的不同组合,比如注册接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/
 
import pytest
 
data=['韧','全栈测试笔记','性能测试']
data2=[1,2,3]
@pytest.fixture(params=data)
def fun(request):  # 必须是request这个参数名
    return request.param  # 依次取列表中的每个值返回
 
@pytest.fixture(params=data2)
def fun2(request):
    return request.param
 
class TestX:
    def test_case(self, fun, fun2):
        print(f"---test_case,data={fun},{fun2}")

 

结果:

 

posted @   全栈测试笔记  阅读(478)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2022-02-23 答疑记录:jmeter从返回的html中提取指定内容
浏览器标题切换
浏览器标题切换end
点击右上角即可分享
微信分享提示