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)
My test method structure is
@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]}))
Which give me the following error:
ModuleNotFoundError: No module named 'program.data.excel.BaseExcelReader';
'program.data.excel' is not a package
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.