【发布时间】:2021-12-29 12:32:10
【问题描述】:
我在package 目录中有一些脚本,在tests 目录中有一些测试,还有一个包含我想用于测试目的的数据框的 CSV 文件。
main_directory/
|
|- package/
| |- foo.py
| |- bar.py
|
|- tests/
|- conftest.py
|- test1.py
|- test.csv
我正在使用pytest,并且我已经定义了一个conftest.py,其中包含一个我想用于整个测试会话的夹具,它应该返回一个从 csv 文件导入的 pandas 测试数据框,如下所示:
#conftest.py
import pytest
from pandas import read_csv
path="test.csv"
@pytest.fixture(scope="session")
def test_data():
return read_csv(path)
我一直在尝试使用夹具返回 test_functions 的测试数据帧。
最初的测试函数有点复杂,在夹具返回的对象上调用 pandas groupby。我不断收到错误'TestStrataFrame' object has no attribute 'groupby',所以我将测试简化为下面的测试,由于我仍然遇到错误,我意识到我可能遗漏了一些东西。
我的测试如下:
#test1.py
import unittest
import pytest
class TestStrataFrame(unittest.TestCase):
def test_fixture(test_data):
assert isinstance(test_data,pd.DataFrame) is True
以上test_fixture返回:
=============================================== FAILURES ================================================
_____________________________________ TestStrataFrame.test_fixture ______________________________________
test_data = <tests.test_data.TestStrataFrame testMethod=test_fixture>
def test_fixture(test_data):
ciao=test_data
> assert isinstance(ciao,pd.DataFrame) is True
E AssertionError: assert False is True
E + where False = isinstance(<tests.test_data.TestStrataFrame testMethod=test_fixture>, <class 'pandas.core.frame.DataFrame'>)
E + where <class 'pandas.core.frame.DataFrame'> = pd.DataFrame
tests/test_data.py:23: AssertionError
=========================================== warnings summary ============================================
../../../../../opt/miniconda3/envs/geo/lib/python3.7/importlib/_bootstrap.py:219
/opt/miniconda3/envs/geo/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: numpy.ufunc size changed, may indicate binary incompatibility. Expected 192 from C header, got 216 from PyObject
return f(*args, **kwds)
-- Docs: https://docs.pytest.org/en/stable/warnings.html
======================================== short test summary info ========================================
FAILED tests/test_data.py::TestStrataFrame::test_fixture - AssertionError: assert False is True
================================ 1 failed, 4 passed, 1 warning in 12.82s ================================
我怎样才能正确地做到这一点?
PS:目前我不会关注RuntimeWarning。自从我开始尝试解决这个问题之后,我就得到了,但我很确定测试在我收到警告之前就失败了——所以它们可能是不相关的。我重新安装了环境,警告仍然存在,希望可以解决问题...
【问题讨论】:
标签: python pandas pytest python-unittest fixtures