模拟方法 pandas.read_excel 不适用于 @patch Python [英] Mocking method pandas.read_excel does not work with @patch Python

查看:31
本文介绍了模拟方法 pandas.read_excel 不适用于 @patch Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Python 为一个项目编写单元测试,最近遇到了装饰器 @patch 的问题.我有以下方法需要测试

I'm writing unit tests with Python for a project and recently encountered a problem with the decorator @patch. I have the following method which I need to test

def _read_from_disk(self, excel_kwargs):
        """
        Read excel file from disk and apply excel_kwargs.

        Args:
            excel_kwargs: Parameters for pandas.read_excel.

        Returns:
            DataFrame or dict of DataFrames.
        """
        return pd.read_excel(self.location, **excel_kwargs)

我的测试方法结构是

 @patch("program.data.excel.BaseExcelReader._read_from_disk.pd.read_excel")
    def test___read_from_disk(self, mock_df):
        mock_df.return_value = pd.DataFrame({"test_id": [1, 2, 3, 4, 5]})
        return_df = self.test_reader._read_from_disk(self.excel_kwargs_svd)
        pd.testing.assert_frame_equal(return_df, pd.DataFrame({"test_id": [1, 2, 3, 4, 5]}))

这给了我以下错误:

ModuleNotFoundError: 没有名为program.data.excel.BaseExcelReader"的模块;'program.data.excel' 不是包

ModuleNotFoundError: No module named 'program.data.excel.BaseExcelReader'; 'program.data.excel' is not a package

请注意,测试方法只是一个示例.问题的目的是找到一种使用@patch 模拟pandas.read_excel 的方法.谢谢

Please note that the test method is only an example. The purpose of the question is to find a way to mock pandas.read_excel with @patch. Thanks

推荐答案

可以直接对pandas.read_excel"进行打补丁而不是program.data.excel.BaseExcelReader._read_from_disk.pd.read_excel"

You can directly patch the "pandas.read_excel" instead of "program.data.excel.BaseExcelReader._read_from_disk.pd.read_excel"

代码:

@patch("pandas.read_excel")
def test___read_from_disk(self, mock_df):
    mock_df.return_value = pd.DataFrame({"test_id": [1, 2, 3, 4, 5]})
    return_df = self.test_reader._read_from_disk(self.excel_kwargs_svd)
    pd.testing.assert_frame_equal(return_df, pd.DataFrame({"test_id": [1, 2, 3, 4, 5]}))

这篇关于模拟方法 pandas.read_excel 不适用于 @patch Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆