在Pytest夹具中修补导入的函数

2024-06-11 08:55:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我在pytest中正确修补导入的函数时遇到问题。我想修补的函数是一个设计用于执行大型SQL获取的函数,因此为了提高速度,我想用读取CSV文件来代替它。以下是我目前拥有的代码:

from data import postgres_fetch
import pytest

@pytest.fixture
def data_patch_market(monkeypatch):
    test_data_path = os.path.join(os.path.dirname(__file__), 'test_data')
    if os.path.exists(test_data_path):
        mock_data_path = os.path.join(test_data_path, 'test_data_market.csv')
        mock_data = pd.read_csv(mock_data_path)
        monkeypatch.setattr(postgres_fetch, 'get_data_for_market', mock_data)


def test_mase(data_patch_market):
    data = postgres_fetch.get_data_for_market(market_name=market,
                                              market_level=market_level,
                                              backtest_log_ids=log_ids,
                                              connection=conn)

    test_result= build_features.MASE(data)

但是,当我运行此测试时,我收到一个关于调用数据帧的类型错误:

TypeError: 'DataFrame' object is not callable

我知道csv可以正确读取,因为我已经单独测试过了,所以我假设我如何实现补丁装置有问题,但我似乎无法解决它


Tags: csvpath函数testimportdatapytestos
1条回答
网友
1楼 · 发布于 2024-06-11 08:55:24

在这里,您对monkeypatch.setattr的调用是将对postgres_fetch.get_data_for_market的任何调用替换为对mock_data调用

这个不能工作,因为mock_data不是一个函数,而是一个DataFrame对象

相反,在对monkeypatch.setattr的调用中,需要传入一个函数,该函数返回模拟数据(即DataFrame对象)

因此,类似这样的方法应该有效:

@pytest.fixture
def data_patch_market(monkeypatch):
    test_data_path = os.path.join(os.path.dirname(__file__), 'test_data')
    if os.path.exists(test_data_path):
        mock_data_path = os.path.join(test_data_path, 'test_data_market.csv')
        mock_data = pd.read_csv(mock_data_path)

        # The lines below are new - here, we define a function that will return the data we have mocked
        def return_mocked(*args, **kwargs):
            return mock_data
        monkeypatch.setattr(postgres_fetch, 'get_data_for_market', return_mocked)

相关问题 更多 >