gpt4 book ai didi

python-2.7 - 断言已使用特定字符串调用了日志记录

转载 作者:行者123 更新时间:2023-12-03 21:16:48 25 4
gpt4 key购买 nike

我正在尝试使用unittest测试我制作的SimpleXMLRPCServer的某些功能。现在,我与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)

最佳答案

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

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

最后,使用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')

关于python-2.7 - 断言已使用特定字符串调用了日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31728497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com