【问题标题】:Mocking logging module to include debug, info, error, etc模拟日志模块以包括调试、信息、错误等
【发布时间】:2019-04-10 07:12:43
【问题描述】:

在不使用几个独特的模拟的情况下,我很难模拟日志模块以包含所有日志模块功能。这是一个复制我想在 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可以处理对象及其方法。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      • 2011-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多