簡體   English   中英

修補 Pytest 夾具中的導入功能

[英]Patching imported functions in a Pytest fixture

我在正確修補 pytest 中的導入 function 時遇到問題。 The function I want to patch is a function designed to do a large SQL fetch, so for speed I would like to replace this with reading a CSV file. 這是我目前擁有的代碼:

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 可以正確讀取,因為我已經單獨測試過,所以我認為我實現補丁夾具的方式有問題,但我似乎無法解決

在這里,您對mock_data的調用正在用對monkeypatch.setattr調用替換postgres_fetch.get_data_for_market的任何調用。

這是行不通的,因為mock_data不是 function - 它是DataFrame object。

相反,在調用monkeypatch.setattr時,您需要傳入返回模擬數據的function (即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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM