分享Pytest fixture参数传递的几种方式

作者:aduocd 时间:2023-06-15 01:25:28 

1.背景

最近使用Pytest中的fixtureconftest时,遇到需要在conftest中的setup和teardown方法里传递参数。这里记录下几种实现的方式。

2.fixture中参数传递的几种方式

1)fixture中的函数返回

conftest.py
@pytest.fixture(scope="class")
def setup_func():
    test_data = [{"k1": "v1"}, {"k2": "v2"}]
    return test_data
testcase.py
def test_func(setup_func)
    print(setup_func)

结果:

执行一条用例,输出:[{"k1": "v1"}, {"k2": "v2"}]

2)与@pytest.mark.parametrize的结合

conftest.py
@pytest.fixture(scope="class")
def setup_func(request):
    print(request.param)
    return request.param
testcase.py
test_data = [{"k1": "v1"}, {"k2": "v2"}]
@pytest.mark.parametrize('setup_func', test_data, indirect=True)
def test_func(setup_func)
    setup_func

结果:

执行两条用例,分别输出:{"k1": "v1"}, {"k2": "v2"}

注:

当 indirect=False 时,“setup_func”被当成普通变量; 
当 indirect=True 时,“setup_func”被当成函数执行,且 “test_data”作为函数中的参数传递

3)fixture中的方法嵌套传递

confitest.py
@pytest.fixture(scope="class")
def setup_func1():
    test_data1 = [{"k1": "v1"}, {"k2": "v2"}]
    return test_data1

@pytest.fixture(scope="class")
def setup_func2(setup_func1):
    a = setup_func1
    b = [{"k11": "v11"}, {"k22": "v22"}]
    return (a, b)
testcase.py
def test_aaa(self, setup_func2):
        print(setup_func2)

结果:

执行一条用例,输出:([{'k1': 'v1'}, {'k2': 'v2'}], [{'k11': 'v11'}, {'k22': 'v22'}])

4)测试方法中产生数据后,直接调用teardown

@python.fixture(scope="class")
def teardown_func():
    def _teardown_func(param1, param2):
        func()
    return _teardown_func

来源:https://blog.csdn.net/aduocd/article/details/124106135

标签:Pytest,fixture,参数,传递,方式
0
投稿

猜你喜欢

  • 关于Pycharm安装第三方库超时 Read time-out的问题

    2022-03-08 10:12:43
  • 通过优化CSS代码 减小对系统资源的占用

    2010-08-03 12:33:00
  • python数据可视化Seaborn画热力图

    2022-01-17 22:55:05
  • Python下载指定页面上图片的方法

    2023-08-16 09:32:37
  • php 伪造本地文件包含漏洞的代码

    2023-11-17 06:36:40
  • 移除Selenium中window.navigator.webdriver值

    2023-07-11 16:21:36
  • centos下mysql主从复制设置详解

    2024-01-20 23:27:06
  • Windows10下mysql 5.7.21 Installer版安装图文教程

    2024-01-18 10:52:23
  • 详细聊聊为什么Python中0.2+0.1不等于0.3

    2021-08-19 12:12:35
  • Python全栈之列表数据类型详解

    2023-05-05 15:27:10
  • MySQL 通过索引优化含ORDER BY的语句

    2024-01-12 19:16:06
  • Python数据可视化之简单折线图的绘制

    2021-05-25 11:59:30
  • javascript设计模式交流(二) Prototype Pattern

    2007-11-29 14:01:00
  • Python设计模式中的创建型工厂模式

    2023-05-09 17:47:02
  • Vue+Axios实现文件上传自定义进度条

    2024-05-29 22:24:57
  • python实现某考试系统生成word试卷

    2022-05-20 18:29:09
  • 如何通过配置自动实现ValueList中hql语句的整型参数转换

    2024-01-24 14:59:21
  • Python 保存矩阵为Excel的实现方法

    2022-07-23 07:05:00
  • Python基本数据类型详细介绍

    2021-10-14 07:02:50
  • Python Django框架中表单的用法详解

    2021-11-06 04:24:41
  • asp之家 网络编程 m.aspxhome.com