【问题标题】:Patching imported functions in a Pytest fixture在 Pytest 夹具中修补导入的函数
【发布时间】:2021-03-19 17:02:36
【问题描述】:

我在正确修补 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 可以正确读取,因为我已经单独测试过了,所以我认为我实现补丁固定装置的方式有问题,但我似乎无法解决

【问题讨论】:

    标签: python pytest monkeypatching


    【解决方案1】:

    在这里,您对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)
    

    【讨论】:

    • 啊,太好了,谢谢!我之前只使用了unittest.mock 装饰器,它直接指定了返回值,所以我的印象是setattr 以类似的方式工作,但这很有意义
    猜你喜欢
    • 1970-01-01
    • 2022-09-23
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多