【问题标题】:pytest fixtures: testing pandas dataframepytest 固定装置:测试熊猫数据框
【发布时间】: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


    【解决方案1】:

    由于test_data 未传递给test_fixture 方法,因此出现错误。例如,下面是您可以调整 Class 及其方法的两种方法。

    import unittest
    import pytest
    import pandas as pd
    
    class TestStrataFrame(unittest.TestCase):
        test_data=pd.DataFrame()
        def test_fixture(self):
            test_data=pd.DataFrame()
            assert isinstance(test_data,pd.DataFrame) is True
        def test_fixture_1(self):
            assert isinstance(TestStrataFrame.test_data,pd.DataFrame) is True
    

    并从终端运行:pytest test_sample.py

    【讨论】:

    • 这没有回答问题,因为它不使用fixture,它只是重新定义了类中的变量
    【解决方案2】:

    如果您在此处记下page,这是预期的行为。该页面明确指出:

    The following pytest features do not work, and probably never will due to different design philosophies:
    
     1. Fixtures (except for autouse fixtures, see below);
     2. Parametrization;
     3. Custom hooks;
    

    您可以将代码修改为以下内容。

    # conftest.py
    from pathlib import Path
    import pytest
    from pandas import read_csv
    
    CWD = Path(__file__).resolve()
    FIN = CWD.parent / "test.csv"
    
    @pytest.fixture(scope="class")
    def test_data(request):
        request.cls.test_data = read_csv(FIN)
    
    
    # test_file.py
    import unittest
    import pytest
    import pandas as pd
    
    @pytest.mark.usefixtures("test_data")
    class TestStrataFrame(unittest.TestCase):
        def test_fixture(self):
            assert hasattr(self, "test_data")
            assert isinstance(self.test_data, pd.DataFrame)
    

    ==>pytest tests/
    ============================= test session starts ==============================
    platform darwin -- Python 3.9.1, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
    rootdir: /Users/***/Desktop/scripts/stackoverflow
    collected 1 item                                                               
    
    tests/test_file.py .                                                     [100%]
    
    ============================== 1 passed in 0.03s ===============================
    

    您可以查看更多关于使用unittest 框架here 混合固定装置的信息。

    【讨论】:

    • 成功了!感谢您的回答和文档链接!
    猜你喜欢
    • 2018-09-20
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    相关资源
    最近更新 更多