Skip to content

Instantly share code, notes, and snippets.

@hjwp
Created January 19, 2014 18:33
Show Gist options
  • Save hjwp/8508956 to your computer and use it in GitHub Desktop.
Save hjwp/8508956 to your computer and use it in GitHub Desktop.
test to get django's logging set up
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