我怎样才能patch and mock getLogger
在这个被测模块 (MUT) 中:
# Start of the module under test
import logging
log = logging.getLogger('some_logger')
# ...
我想做的事:
mock_logging.getLogger.return_value = Mock()
但是我无法在导入 MUT 之前创建 mock_logging
,但是导入 MUT 已经调用了 getLogger
...
最佳答案
这可以通过首先导入和修补 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')
或者,在修补多个方法时很有用:
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')
关于python - 在导入模块之前模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7293653/