Created
January 19, 2014 18:33
-
-
Save hjwp/8508956 to your computer and use it in GitHub Desktop.
test to get django's logging set up
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import sys | |
from unittest.mock import patch # reqs. python 3. change to from mock if p2. | |
from django.conf.urls import url | |
from django.http import HttpResponse | |
from django.test import TestCase | |
from .urls import urlpatterns | |
## test assumes a bare django project created called "myproj" | |
## django-admin.py startproject myproj | |
## then this file saved as myproj/myproj/test_logging.py | |
## then run python3 manage.py test | |
def do_logging(request): | |
# a simple view to test logging | |
# that we monkeypatch into the project urlpatterns | |
logging.debug('debug logged') | |
logging.info('info logged') | |
logging.warning('warning logged') | |
logging.critical('critical logged') | |
return HttpResponse('done') | |
urls_with_logging_test = urlpatterns + [url(r'^testlogging/$', do_logging)] | |
class LoggingTest(TestCase): | |
@patch('myproj.urls.urlpatterns', urls_with_logging_test) | |
@patch('sys.stderr') | |
def test_log_to_stderr(self, mock_stderr): | |
response = self.client.get('/testlogging/') | |
self.assertEqual(response.content.decode(), 'done') | |
written = ''.join(c[0][0] for c in mock_stderr.write.call_args_list) | |
print(written) | |
self.assertIn('critical logged', written) | |
self.assertIn('warning logged', written) | |
self.assertIn('info logged', written) | |
self.assertIn('debug logged', written) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment