断言已使用特定字符串调用日志记录

时间:2015-07-30 15:50:38

标签: python-2.7 unit-testing logging mocking python-unittest

我正在尝试使用unittest来测试我制作的SimpleXMLRPCServer的一些功能。 Togethere with Mock,我现在试图断言在达到if语句时已经记录了一条特定的消息,但是我无法让它工作。我已经尝试在StackOverflow或Googling上找到我在这里找到的各种答案,但仍然没有运气。我在测试用例中进行的调用如下:

def test_listen_for_tasks(self):
    el = {'release': 'default', 'component': None}
    for i in range(50):
        self.server._queue.put(el)
    ServerThread.listen_for_tasks(self.server, 'bla', 'blabla')
    with mock.patch('queue_server.logging') as mock_logging:
        mock_logging.warning.assert_called_with('There are currently {}'
                                                ' items in the queue'.format(
                                                 str(len(self.server._queue.queue))))

服务器中的功能如下:

def listen_for_tasks(self, release, component):
    item = {'release': release, 'component': component}
    for el in list(self._queue.queue):
        if self.is_request_duplicate(el, item):
            logger.debug('Already have a request'
                         ' for this component: {}'.format(item))
            return
    self._queue.put(item, False)
    if len(self._queue.queue) > 50:
        logger.warning('There are currently {}'
                       ' items in the queue'.format(
                        str(len(self._queue.queue))))

知道为什么这不起作用?我是Python的单元测试的新手,并声称记录器已经完成了某些事情似乎是人们可能遇到的最大问题,所以我可能已经搞砸了代码中非常简单的东西。任何形式的帮助将不胜感激!

编辑:为了完整性,这是测试输出和失败:

.No handlers could be found for logger "queue_server"
F


FAIL: test_listen_for_tasks (__main__.TestQueueServer)

Traceback (most recent call last):
  File "artifacts_generator/test_queue_server.py", line 46, in   test_listen_for_tasks
str(len(self.server._queue.queue))))
  File "/home/lugiorgi/Desktop/Code/publisher/env/local/lib/python2.7/site-packages/mock/mock.py", line 925, in assert_called_with
raise AssertionError('Expected call: %s\nNot called' % (expected,))
AssertionError: Expected call: warning('There are currently 51 items in the queue')
Not called

Ran 2 tests in 0.137s

FAILED (failures=1)

2 个答案:

答案 0 :(得分:14)

从python 3.4开始,你可以使用unittest.TestCase类方法assertLogs

import logging
import unittest


class LoggingTestCase(unittest.TestCase):
    def test_logging(self):
        with self.assertLogs(level='INFO') as log:
            logging.info('Log message')
            self.assertEqual(len(log.output), 1)
            self.assertEqual(len(log.records), 1)
            self.assertIn('Log message', log.output[0])

答案 1 :(得分:12)

您需要首先模拟对象,然后调用您要测试的函数。

模拟对象时,还需要提供正在模拟的对象的完整包和对象/函数名称,而不是变量名。

最后,使用patch的装饰器形式通常会更方便。

所以,例如:

logger = logging.getLogger(__name__)

def my_fancy_function():
    logger.warning('test')

@patch('logging.Logger.warning')
def test_my_fancy_function(mock):
    my_fancy_function()
    mock.assert_called_with('test')

# if you insist on using with:
def test_my_fancy_function_with_with():
    with patch('logging.Logger.warning') as mock:
        my_fancy_function()
        mock.assert_called_with('test')