模拟日志记录模块,包括调试、信息、错误等



如果不使用几个唯一的mock,我很难将日志记录模块模拟为包含所有日志记录模块功能。下面是一个示例,它复制了我想要在test_init_with:中实现的目标

problem_logging.py:

# problem_logging.py
import logging
class Example:
def __init__(self):
logging.info("Example initialized.")
logging.debug("Debug Info")

test_problem_logging.py:

# test_problem_logging.py
from unittest import TestCase
from unittest.mock import patch
from problem_logging import Example
class TestExample(TestCase):
def setUp(self):
self.mock_logging = patch("problem_logging.logging", autospec=True)
self.mock_logging.start()
def tearDown(self):
self.mock_logging.stop()
def test_init(self): # Fails
ex = Example()
self.mock_logging.info.assert_called_once_with("Example initialized.")
self.mock_logging.debug.assert_called_once_with("Debug Info")
def test_init_with(self): # Passes
with patch('problem_logging.logging.info') as mock_info:
with patch('problem_logging.logging.debug') as mock_debug:
ex = Example()
mock_info.assert_called_once_with("Example initialized.")
mock_debug.assert_called_once_with("Debug Info")
if __name__ == "__main__":
TestExample()

问题:

Error
Traceback (most recent call last):
File "/usr/lib/python3.5/unittest/case.py", line 58, in testPartExecutor
yield
File "/usr/lib/python3.5/unittest/case.py", line 600, in run
testMethod()
File "/home/fred/unittest_logging/test_problem_logging.py", line 16, in test_init
self.mock_logging.info.assert_called_once_with("Example initialized.")
AttributeError: '_patch' object has no attribute 'info'

Ran 2 tests in 0.016s
FAILED (errors=1)

我希望能够在setUp((中设置mock,并在整个TestCase中使用它,以确保我可以访问所有不同的日志记录级别,而不需要额外的五层缩进,类似于MagicMock处理对象及其方法的方式。

我找到了解决问题的方法。_patch.start((方法返回进行断言所需的MagicMock对象。

# test_problem_logging.py
from unittest import TestCase
from unittest.mock import patch
from problem_logging import Example
class TestExample(TestCase):
def setUp(self):
self.mock_logging_module = patch("problem_logging.logging")
self.mock_logging = self.mock_logging_module.start()

def tearDown(self):
self.mock_logging_module.stop()
def test_init(self): # Fails
ex = Example()
self.mock_logging.info.assert_called_once_with("Example initialized.")
self.mock_logging.debug.assert_called_once_with("Debug Info")
if __name__ == "__main__":
TestExample()

最新更新