我有一个工作测试项目,在这个项目中,我在conftest.py中加载了数据,并且能够在目录中的所有测试中使用这些数据。因为某种原因,它停止工作了。
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)Error:
E NameError: name 'test_data' is not defined我尝试在pytest_configure()之外声明变量,但是在pytest_configure中独立化的值仅在函数中有作用域。不确定最近是否有任何可能导致这种情况的更新。对于更清洁的方法有什么想法或建议吗?
发布于 2022-11-02 19:33:53
也许变化来自于这个弃用。您可以在pytest命名空间中定义某种全局变量。
## conftest.py
def pytest_configure(config):
pytest.test_data = pd.read_excel("file.xlsx", index_col=None, sheet_name='Sheet1')
## test file
from pytest import test_data
def test_input_data():
print(test_data)备注:固定装置的使用
如果您可以执行一些重构,那么处理在Pytest中加载的数据的方法称为夹具。因此,您可以将测试数据定义为一个夹具,并在测试中使用(请求)。
import pytest
@pytest.fixture
def test_data():
return pd.read_excel("file.xlsx", index_col=None, sheet_name='Sheet1')
def test_input_data(test_data):
print(test_data)您甚至可以根据您的需要选择夹具的范围来执行此数据加载,请参阅夹具范围。
https://stackoverflow.com/questions/74294063
复制相似问题