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

时间:2018-11-06 20:34:39

标签: python-3.x unit-testing logging mocking patch

我很难在不使用多个唯一模拟的情况下模拟日志记录模块以包括所有日志记录模块功能。这是一个示例,该示例复制了我想在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()中设置模拟并在整个TestCase中使用它,以确保我可以访问所有不同的日志记录级别,而无需潜在的额外五层缩进,这类似于MagicMock的方式可以处理对象及其方法。

1 个答案:

答案 0 :(得分:0)

我找到了解决问题的方法。 _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()