You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pytest中conftest.py全局变量失效问题求助及优化方案咨询

问题:conftest.py中全局变量无法在测试用例中访问

原本可正常运行的测试项目,现在conftest.py中加载的数据无法在目录下测试用例中使用,报错NameError: name 'test_data' is not defined。

现有代码

conftest.py

def pytest_configure(config):
   global test_data
   test_data = pd.read_excel("file.xlsx", index_col=None, sheet_name='Sheet1')

test_temp1.py

from conftest import *
def input_data():
    print(test_data)

报错信息

E   NameError: name 'test_data' is not defined

问题原因

  • pytest_configure是pytest的钩子函数,执行时机在pytest初始化配置阶段,此时用global声明的变量不会被导入到测试模块的命名空间中。
  • 直接from conftest import *无法导入钩子函数内部定义的全局变量,因为conftest模块加载时,pytest_configure还未执行,变量未完成初始化。
  • 即使在函数外声明变量,函数内的赋值因作用域限制,无法让测试模块感知到变量更新。

解决方案

方法1:使用pytest fixture(推荐)

fixture是pytest共享数据/资源的标准方案,比全局变量更可控、灵活。

修改conftest.py:

import pandas as pd
import pytest

@pytest.fixture(scope="session")  # session级别:整个测试会话仅加载一次
def test_data():
    return pd.read_excel("file.xlsx", index_col=None, sheet_name='Sheet1')

测试用例test_temp1.py中使用:

def input_data(test_data):  # 直接将fixture作为参数传入
    print(test_data)

方法2:将变量挂载到pytest config对象

利用pytest_configure钩子把数据挂载到config对象,后续通过pytest的config获取:

conftest.py修改为:

import pandas as pd

def pytest_configure(config):
    config.test_data = pd.read_excel("file.xlsx", index_col=None, sheet_name='Sheet1')

测试用例中获取方式1:

import pytest

def input_data():
    test_data = pytest.config.test_data
    print(test_data)

测试用例中获取方式2(通过request fixture):

def input_data(request):
    test_data = request.config.test_data
    print(test_data)

方法3:模块级全局变量(不推荐)

如果必须使用全局变量,需在conftest.py模块级别声明变量,再在钩子函数中更新:

conftest.py:

import pandas as pd

test_data = None  # 模块级别声明变量

def pytest_configure(config):
    global test_data
    test_data = pd.read_excel("file.xlsx", index_col=None, sheet_name='Sheet1')

测试用例中导入:

from conftest import test_data

def input_data():
    print(test_data)

注意:该方式依赖pytest钩子的执行顺序,可靠性不如fixture,复杂项目不建议使用。

内容的提问来源于stack exchange,提问作者RajeshS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:25:22