简体   繁体   English

如何在Django Rest Framework单元测试中模拟日志记录?

[英]How to mock logging in Django Rest Framework unittest?

I have a unit test that tests whether an unauthorized user can GET a certain url. 我有一个单元测试,测试未经授权的用户是否可以GET某个URL。 I want to use unittest.mock to mock the logging in the request. 我想使用unittest.mock模拟请求中的日志记录。 How can I point the decorator to use the correct logger ? 如何指示装饰器使用正确的记录器? My test looks like: 我的测试看起来像:

@patch(what goes here???)
def test_response_list_not_authenticated(self, mock_logging):
    url = django.core.urlresolvers.reverse("project-api:response-list", args=[6])
    response = self.client.get(url, format="json")
    self.assertEqual(response.status_code, rest_framework.status.HTTP_401_UNAUTHORIZED)
    self.assertEqual(mock_logging.error.called, True)

You just put the path to your logging object, let's say for example you have the following in "myapp.views" file 您只需将路径放置到您的logging对象,例如,您在"myapp.views"文件中具有以下内容

import logging

logger = logging.getLogger(__name__)

Then in your test you do: 然后在您的测试中,您将执行以下操作:

@patch('myapp.views.logger')
def test_response_list_not_authenticated(self, mock_logger):
     ...
     # asserts about logger
     self.assertEqual(mock_logger.error.called, True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM