修补Pytest fixture中导入的函数



我在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)

然而,当我运行这个测试时,我得到了一个关于调用DataFrame:的类型错误

TypeError: 'DataFrame' object is not callable

我知道csv可以正确读取,因为我已经单独测试过了,所以我认为我实现补丁的方式有问题,但我似乎无法解决

这里,对monkeypatch.setattr的调用是用对mock_data调用替换对postgres_fetch.get_data_for_market的任何调用。

无法工作,因为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)

最新更新