简体   繁体   中英

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. I want to use unittest.mock to mock the logging in the request. 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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