Crash before importing a module

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

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

I'd like to do:

mock_logging.getLogger.return_value = Mock()

However, I cannot create mock_loggingMUT before importing, but importing MUT already causes getLogger...

+5
source share
2 answers

To do this, you will need to import the module without first executing it, which, unfortunately, will not work for you unless you make some fancy hacks, such as changing the parsing tree for the module, but you probably do not want to do this either .

, - , - , , .

+2

, logging.getLogger, 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')
0

All Articles