pytest conftest通过fixture实现变量共享

conftest.py

scope="module" 只对当前执行的python文件 作用

复制代码
@pytest.fixture(scope="module")
def global_variable():
    my_dict = {}
    yield my_dict

test_case7.py

复制代码
import pytest

list1 = []


def test_case001(global_variable):

    data1 = '123'
    global_variable.update({'test_case_data1': data1})


def test_case002(global_variable):
    print('\n', global_variable)
    data2 = '123'
    global_variable.update({'test_case_data2': data2})

def test_case003(global_variable):

    print('\n', global_variable)

if __name__ == '__main__':
    pytest.main(['s', 'v', 'test_case7.py'])
    pass

test_case8.py

复制代码
import pytest


def test_case001(global_variable):

    print('\n', global_variable)

if __name__ == '__main__':
    pytest.main(['s', 'v', 'test_case8.py'])
    pass

scope="session" 可跨py文件共享变量

复制代码
# 在 conftest.py 中定义全局变量
@pytest.fixture(scope="session")
def global_variable():
    my_dict = {}
    yield my_dict

Pytest fixture 的四种作用域:session、module、class 和 function-CSDN博客

相关推荐
bjwuzh3 天前
使用pytest实现参数化后,控制台输出的日志是乱码
pytest
2025年一定要上岸4 天前
pytest框架 - 第二集 allure报告
pytest
头疼的程序员5 天前
allure生成测试报告(搭配Pytest、allure-pytest)
测试工具·pytest
文人sec6 天前
接口自动化测试设计思路--设计实战
python·https·单元测试·自动化·pytest
测试开发Kevin7 天前
从投入产出、效率、上手难易度等角度综合对比 pytest 和 unittest 框架
python·pytest
测试开发Kevin10 天前
以pytest_addoption 为例,讲解pytest框架中钩子函数的应用
python·pytest
川石教育15 天前
Pytest中的fixture装饰器详解
python自动化测试·pytest·pytest自动化测试框架·pytest测试框架·pytest单元测试框架
春风又。15 天前
接口自动化——参数化
python·测试工具·自动化·pytest
XTY0018 天前
mac电脑pytest生成测试报告
pytest
程序员的世界你不懂18 天前
pytest-前后置及fixture运用
pytest