Search code examples
pythonunit-testingpython-mock

how to mock internal calls (xlwt)?


I have a test case like this:

@mock.patch('xlwt.Workbook.Workbook.save')
    def test_Generic_send_test_email_address(self, workspace_mock):
        workspace_mock.return_value = None
        oi = OptinInvitesGeneric()
        oi.compute(...)
        self.assert ...

The actual method does some processing and saves the result in an excel spreadsheet.

class OptinInvitesGeneric(OptinBase):
    def compute(...):
      ...
      wb = excel_tool.write_xls(...)
      wb.save('{0}.xls'.format(category))

It seems my mock patch doesn't take over the workbook.save(). What am I missing please?


Solution

  • I don't know why you're trying to patch xlwt.Workbook.Workbook, but these two work for me:

    @patch.object(xlwt.Workbook, 'save', return_value=None)
    def test_patch_object(mock):
        wb = xlwt.Workbook()
        assert wb.save() == None
    
    @patch('xlwt.Workbook.save', return_value=None)
    def test_patch(mock):
        wb = xlwt.Workbook()
        assert wb.save() == None