Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking before importing a module

How can I patch and mock getLogger in this module under test (MUT):

# Start of the module under test
import logging
log = logging.getLogger('some_logger')
# ...

I would like to do:

mock_logging.getLogger.return_value = Mock()

However I can't create mock_logging before importing the MUT, but importing the MUT already calls getLogger...

like image 553
Jonathan Livni Avatar asked Sep 03 '11 14:09

Jonathan Livni


People also ask

How do you mock an import in jest?

To mock an imported function with Jest we use the jest. mock() function. jest. mock() is called with one required argument - the import path of the module we're mocking.

What is mocking in Python?

mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. unittest. mock provides a core Mock class removing the need to create a host of stubs throughout your test suite.

What is the difference between mock and MagicMock?

Mock vs. So what is the difference between them? MagicMock is a subclass of Mock . It contains all magic methods pre-created and ready to use (e.g. __str__ , __len__ , etc.). Therefore, you should use MagicMock when you need magic methods, and Mock if you don't need them.


2 Answers

This can be done by first importing and patching logging.getLogger and only then import your mut

import unittest
from unittest import mock

import logging
with mock.patch('logging.getLogger') as mock_method:
    import mut
mock_method.assert_called_once_with('some_logger')

Alternatively, useful when patching more than one method:

import unittest
from unittest import mock

import logging
mock_method = mock.patch('logging.getLogger').start()
import mut
mock_method.stop()
mock_method.assert_called_once_with('some_logger')
like image 122
Pelle Avatar answered Sep 21 '22 07:09

Pelle


This would require importing the module without executing it first, which unfortunately for you won't work unless you do some fancy hacks like modifying the parse tree for the module, but you probably don't want to do that either.

What you could do is to modify these import-time reference after the import and replace them manually by mock-objects or reexecute the statements after your mock-object is install, though I know, that this is of limited use.

like image 25
rumpel Avatar answered Sep 18 '22 07:09

rumpel