Fixed #25684 -- Made runserver use logging for request/response output.

Thanks andreif for the contributing to the patch.
This commit is contained in:
Flavio Curella 2015-11-06 10:19:41 -06:00 committed by Tim Graham
parent 3792e291e6
commit 0bc5cd6280
6 changed files with 180 additions and 48 deletions

View file

@ -1,10 +1,11 @@
import logging
from io import BytesIO
from django.core.handlers.wsgi import WSGIRequest
from django.core.servers.basehttp import WSGIRequestHandler
from django.test import SimpleTestCase
from django.test.client import RequestFactory
from django.test.utils import captured_stderr
from django.test.utils import captured_stderr, patch_logger
class Stub(object):
@ -15,13 +16,39 @@ class Stub(object):
class WSGIRequestHandlerTestCase(SimpleTestCase):
def test_log_message(self):
request = WSGIRequest(RequestFactory().get('/').environ)
request.makefile = lambda *args, **kwargs: BytesIO()
handler = WSGIRequestHandler(request, '192.168.0.2', None)
# Silence the django.server logger by replacing its StreamHandler with
# NullHandler.
logger = logging.getLogger('django.server')
original_handlers = logger.handlers
logger.handlers = [logging.NullHandler()]
try:
request = WSGIRequest(RequestFactory().get('/').environ)
request.makefile = lambda *args, **kwargs: BytesIO()
handler = WSGIRequestHandler(request, '192.168.0.2', None)
level_status_codes = {
'info': [200, 301, 304],
'warning': [400, 403, 404],
'error': [500, 503],
}
with captured_stderr() as stderr:
handler.log_message('GET %s %s', 'A', 'B')
self.assertIn('] GET A B', stderr.getvalue())
def _log_level_code(level, status_code):
with patch_logger('django.server', level) as messages:
handler.log_message('GET %s %s', 'A', str(status_code))
return messages
for level, status_codes in level_status_codes.items():
for status_code in status_codes:
# The correct level gets the message.
messages = _log_level_code(level, status_code)
self.assertIn('GET A %d' % status_code, messages[0])
# Incorrect levels shouldn't have any messages.
for wrong_level in level_status_codes.keys():
if wrong_level != level:
messages = _log_level_code(wrong_level, status_code)
self.assertEqual(len(messages), 0)
finally:
logger.handlers = original_handlers
def test_https(self):
request = WSGIRequest(RequestFactory().get('/').environ)
@ -29,13 +56,13 @@ class WSGIRequestHandlerTestCase(SimpleTestCase):
handler = WSGIRequestHandler(request, '192.168.0.2', None)
with captured_stderr() as stderr:
with patch_logger('django.server', 'error') as messages:
handler.log_message("GET %s %s", str('\x16\x03'), "4")
self.assertIn(
"You're accessing the development server over HTTPS, "
"but it only supports HTTP.",
stderr.getvalue()
)
self.assertIn(
"You're accessing the development server over HTTPS, "
"but it only supports HTTP.",
messages[0]
)
def test_strips_underscore_headers(self):
"""WSGIRequestHandler ignores headers containing underscores.