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博客

相关推荐
XYiFfang6 天前
【Pytest】解决Pytest中Teardown钩子的TypeError:实例方法与类方法的调用差异
python·pytest
Kingairy8 天前
Pytest 插件:pytest_runtest_protocol
python·pytest
AIZHINAN8 天前
Pytest 插件介绍和开发
测试工具·pytest·插件开发
灰阳阳10 天前
替身演员的艺术:pytest-mock 从入门到飙戏
自动化测试·python·pytest·unit testing·pytest-mock
年年测试13 天前
Playwright与PyTest结合指南
pytest
focksorCr14 天前
pytest 并发执行用例(基于受限的测试资源)
python·pytest
律品18 天前
pytest的前置与后置
开发语言·python·pytest
测试老哥20 天前
pytest+requests+allure自动化测试接入Jenkins学习
自动化测试·软件测试·学习·测试工具·职场和发展·jenkins·pytest
丿罗小黑20 天前
Pytest项目_day20(log日志)
pytest