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
...
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.
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.
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.
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')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With