From ff881aef536640d712fd2bc53fa1ff98e300adad Mon Sep 17 00:00:00 2001 From: Shai Berger Date: Sat, 18 May 2013 19:26:34 +0300 Subject: [PATCH] Fixed #13958 -- problem reporting exception from \r-line-ended file Thanks petrvanblokland for reporting and saz for the patch --- django/views/debug.py | 8 ++++---- tests/view_tests/tests/test_debug.py | 21 ++++++++++++++++++++- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/django/views/debug.py b/django/views/debug.py index 9b95b524d2b..10c07e8f784 100644 --- a/django/views/debug.py +++ b/django/views/debug.py @@ -347,7 +347,7 @@ class ExceptionReporter(object): if source is None: try: with open(filename, 'rb') as fp: - source = fp.readlines() + source = fp.read().splitlines() except (OSError, IOError): pass if source is None: @@ -370,9 +370,9 @@ class ExceptionReporter(object): lower_bound = max(0, lineno - context_lines) upper_bound = lineno + context_lines - pre_context = [line.strip('\n') for line in source[lower_bound:lineno]] - context_line = source[lineno].strip('\n') - post_context = [line.strip('\n') for line in source[lineno+1:upper_bound]] + pre_context = source[lower_bound:lineno] + context_line = source[lineno] + post_context = source[lineno+1:upper_bound] return lower_bound, pre_context, context_line, post_context diff --git a/tests/view_tests/tests/test_debug.py b/tests/view_tests/tests/test_debug.py index b44cd88abed..1022d05998f 100644 --- a/tests/view_tests/tests/test_debug.py +++ b/tests/view_tests/tests/test_debug.py @@ -6,6 +6,7 @@ from __future__ import absolute_import, unicode_literals import inspect import os import sys +import tempfile from django.core import mail from django.core.files.uploadedfile import SimpleUploadedFile @@ -13,7 +14,7 @@ from django.core.urlresolvers import reverse from django.test import TestCase, RequestFactory from django.test.utils import (override_settings, setup_test_template_loader, restore_template_loaders) -from django.utils.encoding import force_text +from django.utils.encoding import force_text, force_bytes from django.views.debug import ExceptionReporter from .. import BrokenException, except_args @@ -122,6 +123,24 @@ class ExceptionReporterTests(TestCase): self.assertIn('

Request information

', html) self.assertIn('

Request data not supplied

', html) + def test_eol_support(self): + """Test that the ExceptionReporter supports Unix, Windows and Macintosh EOL markers""" + LINES = list(u'print %d' % i for i in range(1,6)) + reporter = ExceptionReporter(None, None, None, None) + + for newline in ['\n','\r\n','\r']: + fd,filename = tempfile.mkstemp(text = False) + os.write(fd, force_bytes(newline.join(LINES)+newline)) + os.close(fd) + + try: + self.assertEqual( + reporter._get_lines_from_file(filename, 3, 2), + (1, LINES[1:3], LINES[3], LINES[4:]) + ) + finally: + os.unlink(filename) + def test_no_exception(self): "An exception report can be generated for just a request" request = self.rf.get('/test_view/')