Skip to content
Browse files

Merge https://github.com/django/django into t19210

  • Loading branch information...
2 parents cd06f4e + 0d3f16b commit 3aacf5ff95a03f33547a120e1e74b9c1784396ba @hirokiky committed Jan 2, 2013
View
2 django/conf/locale/lt/formats.py
@@ -9,7 +9,7 @@
# DATETIME_FORMAT =
# YEAR_MONTH_FORMAT =
# MONTH_DAY_FORMAT =
-SHORT_DATE_FORMAT = 'Y.m.d'
+SHORT_DATE_FORMAT = 'Y-m-d'
# SHORT_DATETIME_FORMAT =
# FIRST_DAY_OF_WEEK =
View
4 django/contrib/gis/geoip/libgeoip.py
@@ -19,8 +19,8 @@
# Getting the path to the GeoIP library.
if lib_name: lib_path = find_library(lib_name)
-if lib_path is None: raise GeoIPException('Could not find the GeoIP library (tried "%s"). '
- 'Try setting GEOIP_LIBRARY_PATH in your settings.' % lib_name)
+if lib_path is None: raise RuntimeError('Could not find the GeoIP library (tried "%s"). '
+ 'Try setting GEOIP_LIBRARY_PATH in your settings.' % lib_name)
lgeoip = CDLL(lib_path)
# Getting the C `free` for the platform.
View
13 django/core/files/images.py
@@ -3,9 +3,11 @@
Requires PIL, as you might imagine.
"""
+import zlib
from django.core.files import File
+
class ImageFile(File):
"""
A mixin for use alongside django.core.files.base.File, which provides
@@ -26,6 +28,7 @@ def _get_image_dimensions(self):
self._dimensions_cache = get_image_dimensions(self, close=close)
return self._dimensions_cache
+
def get_image_dimensions(file_or_path, close=False):
"""
Returns the (width, height) of an image, given an open file or a path. Set
@@ -55,7 +58,15 @@ def get_image_dimensions(file_or_path, close=False):
data = file.read(chunk_size)
if not data:
break
- p.feed(data)
+ try:
+ p.feed(data)
+ except zlib.error as e:
+ # ignore zlib complaining on truncated stream, just feed more
+ # data to parser (ticket #19457).
+ if e.args[0].startswith("Error -5"):
+ pass
+ else:
+ raise
if p.image:
return p.image.size
chunk_size = chunk_size*2
View
14 django/forms/formsets.py
@@ -157,14 +157,12 @@ def extra_forms(self):
return self.forms[self.initial_form_count():]
@property
- def empty_form(self, **kwargs):
- defaults = {
- 'auto_id': self.auto_id,
- 'prefix': self.add_prefix('__prefix__'),
- 'empty_permitted': True,
- }
- defaults.update(kwargs)
- form = self.form(**defaults)
+ def empty_form(self):
+ form = self.form(
+ auto_id=self.auto_id,
+ prefix=self.add_prefix('__prefix__'),
+ empty_permitted=True,
+ )
self.add_fields(form, None)
return form
View
15 django/test/client.py
@@ -16,7 +16,9 @@
from django.contrib.auth import authenticate, login
from django.core.handlers.base import BaseHandler
from django.core.handlers.wsgi import WSGIRequest
-from django.core.signals import got_request_exception
+from django.core.signals import (request_started, request_finished,
+ got_request_exception)
+from django.db import close_connection
from django.http import SimpleCookie, HttpRequest, QueryDict
from django.template import TemplateDoesNotExist
from django.test import signals
@@ -76,7 +78,9 @@ def closing_iterator_wrapper(iterable, close):
for item in iterable:
yield item
finally:
- close()
+ request_finished.disconnect(close_connection)
+ close() # will fire request_finished
+ request_finished.connect(close_connection)
class ClientHandler(BaseHandler):
@@ -91,14 +95,13 @@ def __init__(self, enforce_csrf_checks=True, *args, **kwargs):
def __call__(self, environ):
from django.conf import settings
- from django.core import signals
# Set up middleware if needed. We couldn't do this earlier, because
# settings weren't available.
if self._request_middleware is None:
self.load_middleware()
- signals.request_started.send(sender=self.__class__)
+ request_started.send(sender=self.__class__)
request = WSGIRequest(environ)
# sneaky little hack so that we can easily get round
# CsrfViewMiddleware. This makes life easier, and is probably
@@ -112,7 +115,9 @@ def __call__(self, environ):
response.streaming_content = closing_iterator_wrapper(
response.streaming_content, response.close)
else:
- response.close()
+ request_finished.disconnect(close_connection)
+ response.close() # will fire request_finished
+ request_finished.connect(close_connection)
return response
View
2 django/test/testcases.py
@@ -641,8 +641,6 @@ def assertContains(self, response, text, count=None, status_code=200,
else:
content = response.content
content = content.decode(response._charset)
- # Avoid ResourceWarning about unclosed files.
- response.close()
if html:
content = assert_and_parse_html(self, content, None,
"Response's content is not valid HTML:")
View
8 django/test/utils.py
@@ -4,8 +4,6 @@
from django.conf import settings, UserSettingsHolder
from django.core import mail
-from django.core.signals import request_finished
-from django.db import close_connection
from django.test.signals import template_rendered, setting_changed
from django.template import Template, loader, TemplateDoesNotExist
from django.template.loaders import cached
@@ -70,10 +68,8 @@ def setup_test_environment():
"""Perform any global pre-test setup. This involves:
- Installing the instrumented test renderer
- - Setting the email backend to the locmem email backend.
+ - Set the email backend to the locmem email backend.
- Setting the active locale to match the LANGUAGE_CODE setting.
- - Disconnecting the request_finished signal to avoid closing
- the database connection within tests.
"""
Template.original_render = Template._render
Template._render = instrumented_test_render
@@ -85,8 +81,6 @@ def setup_test_environment():
deactivate()
- request_finished.disconnect(close_connection)
-
def teardown_test_environment():
"""Perform any global post-test teardown. This involves:
View
26 django/utils/six.py
@@ -1,5 +1,24 @@
"""Utilities for writing code that runs on Python 2 and 3"""
+# Copyright (c) 2010-2012 Benjamin Peterson
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy of
+# this software and associated documentation files (the "Software"), to deal in
+# the Software without restriction, including without limitation the rights to
+# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+# the Software, and to permit persons to whom the Software is furnished to do so,
+# subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in all
+# copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
import operator
import sys
import types
@@ -26,7 +45,7 @@
text_type = unicode
binary_type = str
- if sys.platform == "java":
+ if sys.platform.startswith("java"):
# Jython always uses 32 bits.
MAXSIZE = int((1 << 31) - 1)
else:
@@ -133,6 +152,9 @@ class _MovedItems(types.ModuleType):
MovedModule("html_entities", "htmlentitydefs", "html.entities"),
MovedModule("html_parser", "HTMLParser", "html.parser"),
MovedModule("http_client", "httplib", "http.client"),
+ MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
+ MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
+ MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
@@ -164,7 +186,7 @@ class _MovedItems(types.ModuleType):
setattr(_MovedItems, attr.name, attr)
del attr
-moves = sys.modules["django.utils.six.moves"] = _MovedItems("moves")
+moves = sys.modules[__name__ + ".moves"] = _MovedItems("moves")
def add_move(move):
View
30 docs/ref/class-based-views/generic-editing.txt
@@ -97,11 +97,11 @@ CreateView
.. attribute:: template_name_suffix
- The CreateView page displayed to a GET request uses a
- ``template_name_suffix`` of ``'_form.html'``. For
- example, changing this attribute to ``'_create_form.html'`` for a view
- creating objects for the the example `Author` model would cause the the
- default `template_name` to be ``'myapp/author_create_form.html'``.
+ The ``CreateView`` page displayed to a ``GET`` request uses a
+ ``template_name_suffix`` of ``'_form'``. For
+ example, changing this attribute to ``'_create_form'`` for a view
+ creating objects for the example ``Author`` model would cause the
+ default ``template_name`` to be ``'myapp/author_create_form.html'``.
**Example views.py**::
@@ -139,11 +139,11 @@ UpdateView
.. attribute:: template_name_suffix
- The UpdateView page displayed to a GET request uses a
- ``template_name_suffix`` of ``'_form.html'``. For
- example, changing this attribute to ``'_update_form.html'`` for a view
- updating objects for the the example `Author` model would cause the the
- default `template_name` to be ``'myapp/author_update_form.html'``.
+ The ``UpdateView`` page displayed to a ``GET`` request uses a
+ ``template_name_suffix`` of ``'_form'``. For
+ example, changing this attribute to ``'_update_form'`` for a view
+ updating objects for the example ``Author`` model would cause the
+ default ``template_name`` to be ``'myapp/author_update_form.html'``.
**Example views.py**::
@@ -180,11 +180,11 @@ DeleteView
.. attribute:: template_name_suffix
- The DeleteView page displayed to a GET request uses a
- ``template_name_suffix`` of ``'_confirm_delete.html'``. For
- example, changing this attribute to ``'_check_delete.html'`` for a view
- deleting objects for the the example `Author` model would cause the the
- default `template_name` to be ``'myapp/author_check_delete.html'``.
+ The ``DeleteView`` page displayed to a ``GET`` request uses a
+ ``template_name_suffix`` of ``'_confirm_delete'``. For
+ example, changing this attribute to ``'_check_delete'`` for a view
+ deleting objects for the example ``Author`` model would cause the
+ default ``template_name`` to be ``'myapp/author_check_delete.html'``.
**Example views.py**::
View
2 docs/topics/logging.txt
@@ -576,7 +576,7 @@ with ``ERROR`` or ``CRITICAL`` level are sent to :class:`AdminEmailHandler`, as
long as the :setting:`DEBUG` setting is set to ``False``.
All messages reaching the ``django`` catch-all logger when :setting:`DEBUG` is
-`True` are sent ot the console. They are simply discarded (sent to
+`True` are sent to the console. They are simply discarded (sent to
``NullHandler``) when :setting:`DEBUG` is `False`.
.. versionchanged:: 1.5
View
164 scripts/manage_translations.py
@@ -0,0 +1,164 @@
+#!/usr/bin/env python
+#
+# This python file contains utility scripts to manage Django translations.
+# It has to be run inside the django git root directory.
+#
+# The following commands are available:
+#
+# * update_catalogs: check for new strings in core and contrib catalogs, and
+# output how much strings are new/changed.
+#
+# * lang_stats: output statistics for each catalog/language combination
+#
+# * fetch: fetch translations from transifex.com
+#
+# Each command support the --languages and --resources options to limit their
+# operation to the specified language or resource. For example, to get stats
+# for Spanish in contrib.admin, run:
+#
+# $ python scripts/manage_translations.py lang_stats --language=es --resources=admin
+
+import os
+from optparse import OptionParser
+from subprocess import call, Popen, PIPE
+
+from django.core.management import call_command
+
+
+HAVE_JS = ['admin']
+
+def _get_locale_dirs(include_core=True):
+ """
+ Return a tuple (contrib name, absolute path) for all locale directories,
+ optionally including the django core catalog.
+ """
+ contrib_dir = os.path.join(os.getcwd(), 'django', 'contrib')
+ dirs = []
+ for contrib_name in os.listdir(contrib_dir):
+ path = os.path.join(contrib_dir, contrib_name, 'locale')
+ if os.path.isdir(path):
+ dirs.append((contrib_name, path))
+ if contrib_name in HAVE_JS:
+ dirs.append(("%s-js" % contrib_name, path))
+ if include_core:
+ dirs.insert(0, ('core', os.path.join(os.getcwd(), 'django', 'conf', 'locale')))
+ return dirs
+
+def _tx_resource_for_name(name):
+ """ Return the Transifex resource name """
+ if name == 'core':
+ return "django.core"
+ else:
+ return "django.contrib-%s" % name
+
+def _check_diff(cat_name, base_path):
+ """
+ Output the approximate number of changed/added strings in the en catalog.
+ """
+ po_path = '%(path)s/en/LC_MESSAGES/django%(ext)s.po' % {
+ 'path': base_path, 'ext': 'js' if cat_name.endswith('-js') else ''}
+ p = Popen("git diff -U0 %s | egrep -v '^@@|^[-+]#|^..POT-Creation' | wc -l" % po_path,
+ stdout=PIPE, stderr=PIPE, shell=True)
+ output, errors = p.communicate()
+ num_changes = int(output.strip()) - 4
+ print("%d changed/added messages in '%s' catalog." % (num_changes, cat_name))
+
+
+def update_catalogs(resources=None, languages=None):
+ """
+ Update the en/LC_MESSAGES/django.po (main and contrib) files with
+ new/updated translatable strings.
+ """
+ contrib_dirs = _get_locale_dirs(include_core=False)
+
+ os.chdir(os.path.join(os.getcwd(), 'django'))
+ print("Updating main en catalog")
+ call_command('makemessages', locale='en')
+ _check_diff('core', os.path.join(os.getcwd(), 'conf', 'locale'))
+
+ # Contrib catalogs
+ for name, dir_ in contrib_dirs:
+ if resources and not name in resources:
+ continue
+ os.chdir(os.path.join(dir_, '..'))
+ print("Updating en catalog in %s" % dir_)
+ if name.endswith('-js'):
+ call_command('makemessages', locale='en', domain='djangojs')
+ else:
+ call_command('makemessages', locale='en')
+ _check_diff(name, dir_)
+
+
+def lang_stats(resources=None, languages=None):
+ """
+ Output language statistics of committed translation files for each
+ Django catalog.
+ If resources is provided, it should be a list of translation resource to
+ limit the output (e.g. ['core', 'gis']).
+ """
+ locale_dirs = _get_locale_dirs()
+
+ for name, dir_ in locale_dirs:
+ if resources and not name in resources:
+ continue
+ print("\nShowing translations stats for '%s':" % name)
+ langs = sorted([d for d in os.listdir(dir_) if not d.startswith('_')])
+ for lang in langs:
+ if languages and not lang in languages:
+ continue
+ # TODO: merge first with the latest en catalog
+ p = Popen("msgfmt -vc -o /dev/null %(path)s/%(lang)s/LC_MESSAGES/django%(ext)s.po" % {
+ 'path': dir_, 'lang': lang, 'ext': 'js' if name.endswith('-js') else ''},
+ stdout=PIPE, stderr=PIPE, shell=True)
+ output, errors = p.communicate()
+ if p.returncode == 0:
+ # msgfmt output stats on stderr
+ print("%s: %s" % (lang, errors.strip()))
+
+
+def fetch(resources=None, languages=None):
+ """
+ Fetch translations from Transifex, wrap long lines, generate mo files.
+ """
+ locale_dirs = _get_locale_dirs()
+
+ for name, dir_ in locale_dirs:
+ if resources and not name in resources:
+ continue
+
+ # Transifex pull
+ if languages is None:
+ call('tx pull -r %(res)s -a -f' % {'res': _tx_resource_for_name(name)}, shell=True)
+ languages = sorted([d for d in os.listdir(dir_) if not d.startswith('_')])
+ else:
+ for lang in languages:
+ call('tx pull -r %(res)s -f -l %(lang)s' % {
+ 'res': _tx_resource_for_name(name), 'lang': lang}, shell=True)
+
+ # msgcat to wrap lines and msgfmt for compilation of .mo file
+ for lang in languages:
+ po_path = '%(path)s/%(lang)s/LC_MESSAGES/django%(ext)s.po' % {
+ 'path': dir_, 'lang': lang, 'ext': 'js' if name.endswith('-js') else ''}
+ call('msgcat -o %s %s' % (po_path, po_path), shell=True)
+ mo_path = '%s.mo' % po_path[:-3]
+ call('msgfmt -o %s %s' % (mo_path, po_path), shell=True)
+
+
+if __name__ == "__main__":
+ RUNABLE_SCRIPTS = ('update_catalogs', 'lang_stats', 'fetch')
+
+ parser = OptionParser(usage="usage: %prog [options] cmd")
+ parser.add_option("-r", "--resources", action='append',
+ help="limit operation to the specified resources")
+ parser.add_option("-l", "--languages", action='append',
+ help="limit operation to the specified languages")
+ options, args = parser.parse_args()
+
+ if not args:
+ parser.print_usage()
+ exit(1)
+
+ if args[0] in RUNABLE_SCRIPTS:
+ eval(args[0])(options.resources, options.languages)
+ else:
+ print("Available commands are: %s" % ", ".join(RUNABLE_SCRIPTS))
View
BIN tests/regressiontests/file_storage/magic.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
15 tests/regressiontests/file_storage/tests.py
@@ -7,6 +7,7 @@
import sys
import tempfile
import time
+import zlib
from datetime import datetime, timedelta
from io import BytesIO
@@ -559,6 +560,20 @@ def test_multiple_calls(self):
self.assertEqual(image_pil.size, size_1)
self.assertEqual(size_1, size_2)
+ @unittest.skipUnless(Image, "PIL not installed")
+ def test_bug_19457(self):
+ """
+ Regression test for #19457
+ get_image_dimensions fails on some pngs, while Image.size is working good on them
+ """
+ img_path = os.path.join(os.path.dirname(upath(__file__)), "magic.png")
+ try:
+ size = get_image_dimensions(img_path)
+ except zlib.error:
+ self.fail("Exception raised from get_image_dimensions().")
+ self.assertEqual(size, Image.open(img_path).size)
+
+
class ContentFileTestCase(unittest.TestCase):
def setUp(self):
View
1 tests/regressiontests/handlers/tests.py
@@ -56,6 +56,5 @@ def test_request_signals(self):
def test_request_signals_streaming_response(self):
response = self.client.get('/streaming/')
self.assertEqual(self.signals, ['started'])
- # Avoid self.assertContains, because it explicitly calls response.close()
self.assertEqual(b''.join(response.streaming_content), b"streaming content")
self.assertEqual(self.signals, ['started', 'finished'])
View
363 tests/regressiontests/middleware/tests.py
@@ -20,17 +20,6 @@
class CommonMiddlewareTest(TestCase):
- def setUp(self):
- self.append_slash = settings.APPEND_SLASH
- self.prepend_www = settings.PREPEND_WWW
- self.ignorable_404_urls = settings.IGNORABLE_404_URLS
- self.send_broken_email_links = settings.SEND_BROKEN_LINK_EMAILS
-
- def tearDown(self):
- settings.APPEND_SLASH = self.append_slash
- settings.PREPEND_WWW = self.prepend_www
- settings.IGNORABLE_404_URLS = self.ignorable_404_urls
- settings.SEND_BROKEN_LINK_EMAILS = self.send_broken_email_links
def _get_request(self, path):
request = HttpRequest()
@@ -41,103 +30,92 @@ def _get_request(self, path):
request.path = request.path_info = "/middleware/%s" % path
return request
+ @override_settings(APPEND_SLASH=True)
def test_append_slash_have_slash(self):
"""
Tests that URLs with slashes go unmolested.
"""
- settings.APPEND_SLASH = True
request = self._get_request('slash/')
self.assertEqual(CommonMiddleware().process_request(request), None)
+ @override_settings(APPEND_SLASH=True)
def test_append_slash_slashless_resource(self):
"""
Tests that matches to explicit slashless URLs go unmolested.
"""
- settings.APPEND_SLASH = True
request = self._get_request('noslash')
self.assertEqual(CommonMiddleware().process_request(request), None)
+ @override_settings(APPEND_SLASH=True)
def test_append_slash_slashless_unknown(self):
"""
Tests that APPEND_SLASH doesn't redirect to unknown resources.
"""
- settings.APPEND_SLASH = True
request = self._get_request('unknown')
self.assertEqual(CommonMiddleware().process_request(request), None)
+ @override_settings(APPEND_SLASH=True)
def test_append_slash_redirect(self):
"""
Tests that APPEND_SLASH redirects slashless URLs to a valid pattern.
"""
- settings.APPEND_SLASH = True
request = self._get_request('slash')
r = CommonMiddleware().process_request(request)
self.assertEqual(r.status_code, 301)
self.assertEqual(r['Location'], 'http://testserver/middleware/slash/')
+ @override_settings(APPEND_SLASH=True, DEBUG=True)
def test_append_slash_no_redirect_on_POST_in_DEBUG(self):
"""
Tests that while in debug mode, an exception is raised with a warning
when a failed attempt is made to POST to an URL which would normally be
redirected to a slashed version.
"""
- settings.APPEND_SLASH = True
- settings.DEBUG = True
request = self._get_request('slash')
request.method = 'POST'
- self.assertRaises(
- RuntimeError,
- CommonMiddleware().process_request,
- request)
- try:
+ with six.assertRaisesRegex(self, RuntimeError, 'end in a slash'):
CommonMiddleware().process_request(request)
- except RuntimeError as e:
- self.assertTrue('end in a slash' in str(e))
- settings.DEBUG = False
+ @override_settings(APPEND_SLASH=False)
def test_append_slash_disabled(self):
"""
Tests disabling append slash functionality.
"""
- settings.APPEND_SLASH = False
request = self._get_request('slash')
self.assertEqual(CommonMiddleware().process_request(request), None)
+ @override_settings(APPEND_SLASH=True)
def test_append_slash_quoted(self):
"""
Tests that URLs which require quoting are redirected to their slash
version ok.
"""
- settings.APPEND_SLASH = True
request = self._get_request('needsquoting#')
r = CommonMiddleware().process_request(request)
self.assertEqual(r.status_code, 301)
self.assertEqual(
r['Location'],
'http://testserver/middleware/needsquoting%23/')
+ @override_settings(APPEND_SLASH=False, PREPEND_WWW=True)
def test_prepend_www(self):
- settings.PREPEND_WWW = True
- settings.APPEND_SLASH = False
request = self._get_request('path/')
r = CommonMiddleware().process_request(request)
self.assertEqual(r.status_code, 301)
self.assertEqual(
r['Location'],
'http://www.testserver/middleware/path/')
+ @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
def test_prepend_www_append_slash_have_slash(self):
- settings.PREPEND_WWW = True
- settings.APPEND_SLASH = True
request = self._get_request('slash/')
r = CommonMiddleware().process_request(request)
self.assertEqual(r.status_code, 301)
self.assertEqual(r['Location'],
'http://www.testserver/middleware/slash/')
+ @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
def test_prepend_www_append_slash_slashless(self):
- settings.PREPEND_WWW = True
- settings.APPEND_SLASH = True
request = self._get_request('slash')
r = CommonMiddleware().process_request(request)
self.assertEqual(r.status_code, 301)
@@ -148,146 +126,135 @@ def test_prepend_www_append_slash_slashless(self):
# The following tests examine expected behavior given a custom urlconf that
# overrides the default one through the request object.
+ @override_settings(APPEND_SLASH=True)
def test_append_slash_have_slash_custom_urlconf(self):
- """
- Tests that URLs with slashes go unmolested.
- """
- settings.APPEND_SLASH = True
- request = self._get_request('customurlconf/slash/')
- request.urlconf = 'regressiontests.middleware.extra_urls'
- self.assertEqual(CommonMiddleware().process_request(request), None)
+ """
+ Tests that URLs with slashes go unmolested.
+ """
+ request = self._get_request('customurlconf/slash/')
+ request.urlconf = 'regressiontests.middleware.extra_urls'
+ self.assertEqual(CommonMiddleware().process_request(request), None)
+ @override_settings(APPEND_SLASH=True)
def test_append_slash_slashless_resource_custom_urlconf(self):
- """
- Tests that matches to explicit slashless URLs go unmolested.
- """
- settings.APPEND_SLASH = True
- request = self._get_request('customurlconf/noslash')
- request.urlconf = 'regressiontests.middleware.extra_urls'
- self.assertEqual(CommonMiddleware().process_request(request), None)
+ """
+ Tests that matches to explicit slashless URLs go unmolested.
+ """
+ request = self._get_request('customurlconf/noslash')
+ request.urlconf = 'regressiontests.middleware.extra_urls'
+ self.assertEqual(CommonMiddleware().process_request(request), None)
+ @override_settings(APPEND_SLASH=True)
def test_append_slash_slashless_unknown_custom_urlconf(self):
- """
- Tests that APPEND_SLASH doesn't redirect to unknown resources.
- """
- settings.APPEND_SLASH = True
- request = self._get_request('customurlconf/unknown')
- request.urlconf = 'regressiontests.middleware.extra_urls'
- self.assertEqual(CommonMiddleware().process_request(request), None)
+ """
+ Tests that APPEND_SLASH doesn't redirect to unknown resources.
+ """
+ request = self._get_request('customurlconf/unknown')
+ request.urlconf = 'regressiontests.middleware.extra_urls'
+ self.assertEqual(CommonMiddleware().process_request(request), None)
+ @override_settings(APPEND_SLASH=True)
def test_append_slash_redirect_custom_urlconf(self):
- """
- Tests that APPEND_SLASH redirects slashless URLs to a valid pattern.
- """
- settings.APPEND_SLASH = True
- request = self._get_request('customurlconf/slash')
- request.urlconf = 'regressiontests.middleware.extra_urls'
- r = CommonMiddleware().process_request(request)
- self.assertFalse(r is None,
- "CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
- self.assertEqual(r.status_code, 301)
- self.assertEqual(r['Location'], 'http://testserver/middleware/customurlconf/slash/')
+ """
+ Tests that APPEND_SLASH redirects slashless URLs to a valid pattern.
+ """
+ request = self._get_request('customurlconf/slash')
+ request.urlconf = 'regressiontests.middleware.extra_urls'
+ r = CommonMiddleware().process_request(request)
+ self.assertFalse(r is None,
+ "CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
+ self.assertEqual(r.status_code, 301)
+ self.assertEqual(r['Location'], 'http://testserver/middleware/customurlconf/slash/')
+ @override_settings(APPEND_SLASH=True, DEBUG=True)
def test_append_slash_no_redirect_on_POST_in_DEBUG_custom_urlconf(self):
- """
- Tests that while in debug mode, an exception is raised with a warning
- when a failed attempt is made to POST to an URL which would normally be
- redirected to a slashed version.
- """
- settings.APPEND_SLASH = True
- settings.DEBUG = True
- request = self._get_request('customurlconf/slash')
- request.urlconf = 'regressiontests.middleware.extra_urls'
- request.method = 'POST'
- self.assertRaises(
- RuntimeError,
- CommonMiddleware().process_request,
- request)
- try:
- CommonMiddleware().process_request(request)
- except RuntimeError as e:
- self.assertTrue('end in a slash' in str(e))
- settings.DEBUG = False
+ """
+ Tests that while in debug mode, an exception is raised with a warning
+ when a failed attempt is made to POST to an URL which would normally be
+ redirected to a slashed version.
+ """
+ request = self._get_request('customurlconf/slash')
+ request.urlconf = 'regressiontests.middleware.extra_urls'
+ request.method = 'POST'
+ with six.assertRaisesRegex(self, RuntimeError, 'end in a slash'):
+ CommonMiddleware().process_request(request)
+ @override_settings(APPEND_SLASH=False)
def test_append_slash_disabled_custom_urlconf(self):
- """
- Tests disabling append slash functionality.
- """
- settings.APPEND_SLASH = False
- request = self._get_request('customurlconf/slash')
- request.urlconf = 'regressiontests.middleware.extra_urls'
- self.assertEqual(CommonMiddleware().process_request(request), None)
+ """
+ Tests disabling append slash functionality.
+ """
+ request = self._get_request('customurlconf/slash')
+ request.urlconf = 'regressiontests.middleware.extra_urls'
+ self.assertEqual(CommonMiddleware().process_request(request), None)
+ @override_settings(APPEND_SLASH=True)
def test_append_slash_quoted_custom_urlconf(self):
- """
- Tests that URLs which require quoting are redirected to their slash
- version ok.
- """
- settings.APPEND_SLASH = True
- request = self._get_request('customurlconf/needsquoting#')
- request.urlconf = 'regressiontests.middleware.extra_urls'
- r = CommonMiddleware().process_request(request)
- self.assertFalse(r is None,
- "CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
- self.assertEqual(r.status_code, 301)
- self.assertEqual(
- r['Location'],
- 'http://testserver/middleware/customurlconf/needsquoting%23/')
+ """
+ Tests that URLs which require quoting are redirected to their slash
+ version ok.
+ """
+ request = self._get_request('customurlconf/needsquoting#')
+ request.urlconf = 'regressiontests.middleware.extra_urls'
+ r = CommonMiddleware().process_request(request)
+ self.assertFalse(r is None,
+ "CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
+ self.assertEqual(r.status_code, 301)
+ self.assertEqual(
+ r['Location'],
+ 'http://testserver/middleware/customurlconf/needsquoting%23/')
+ @override_settings(APPEND_SLASH=False, PREPEND_WWW=True)
def test_prepend_www_custom_urlconf(self):
- settings.PREPEND_WWW = True
- settings.APPEND_SLASH = False
- request = self._get_request('customurlconf/path/')
- request.urlconf = 'regressiontests.middleware.extra_urls'
- r = CommonMiddleware().process_request(request)
- self.assertEqual(r.status_code, 301)
- self.assertEqual(
- r['Location'],
- 'http://www.testserver/middleware/customurlconf/path/')
+ request = self._get_request('customurlconf/path/')
+ request.urlconf = 'regressiontests.middleware.extra_urls'
+ r = CommonMiddleware().process_request(request)
+ self.assertEqual(r.status_code, 301)
+ self.assertEqual(
+ r['Location'],
+ 'http://www.testserver/middleware/customurlconf/path/')
+ @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
def test_prepend_www_append_slash_have_slash_custom_urlconf(self):
- settings.PREPEND_WWW = True
- settings.APPEND_SLASH = True
- request = self._get_request('customurlconf/slash/')
- request.urlconf = 'regressiontests.middleware.extra_urls'
- r = CommonMiddleware().process_request(request)
- self.assertEqual(r.status_code, 301)
- self.assertEqual(r['Location'],
- 'http://www.testserver/middleware/customurlconf/slash/')
+ request = self._get_request('customurlconf/slash/')
+ request.urlconf = 'regressiontests.middleware.extra_urls'
+ r = CommonMiddleware().process_request(request)
+ self.assertEqual(r.status_code, 301)
+ self.assertEqual(r['Location'],
+ 'http://www.testserver/middleware/customurlconf/slash/')
+ @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
def test_prepend_www_append_slash_slashless_custom_urlconf(self):
- settings.PREPEND_WWW = True
- settings.APPEND_SLASH = True
- request = self._get_request('customurlconf/slash')
- request.urlconf = 'regressiontests.middleware.extra_urls'
- r = CommonMiddleware().process_request(request)
- self.assertEqual(r.status_code, 301)
- self.assertEqual(r['Location'],
- 'http://www.testserver/middleware/customurlconf/slash/')
+ request = self._get_request('customurlconf/slash')
+ request.urlconf = 'regressiontests.middleware.extra_urls'
+ r = CommonMiddleware().process_request(request)
+ self.assertEqual(r.status_code, 301)
+ self.assertEqual(r['Location'],
+ 'http://www.testserver/middleware/customurlconf/slash/')
# Tests for the 404 error reporting via email
+ @override_settings(IGNORABLE_404_URLS=(re.compile(r'foo'),),
+ SEND_BROKEN_LINK_EMAILS = True)
def test_404_error_reporting(self):
- settings.IGNORABLE_404_URLS = (re.compile(r'foo'),)
- settings.SEND_BROKEN_LINK_EMAILS = True
request = self._get_request('regular_url/that/does/not/exist')
request.META['HTTP_REFERER'] = '/another/url/'
response = self.client.get(request.path)
CommonMiddleware().process_response(request, response)
self.assertEqual(len(mail.outbox), 1)
self.assertIn('Broken', mail.outbox[0].subject)
+ @override_settings(IGNORABLE_404_URLS=(re.compile(r'foo'),),
+ SEND_BROKEN_LINK_EMAILS = True)
def test_404_error_reporting_no_referer(self):
- settings.IGNORABLE_404_URLS = (re.compile(r'foo'),)
- settings.SEND_BROKEN_LINK_EMAILS = True
request = self._get_request('regular_url/that/does/not/exist')
response = self.client.get(request.path)
CommonMiddleware().process_response(request, response)
self.assertEqual(len(mail.outbox), 0)
+ @override_settings(IGNORABLE_404_URLS=(re.compile(r'foo'),),
+ SEND_BROKEN_LINK_EMAILS = True)
def test_404_error_reporting_ignored_url(self):
- settings.IGNORABLE_404_URLS = (re.compile(r'foo'),)
- settings.SEND_BROKEN_LINK_EMAILS = True
request = self._get_request('foo_url/that/does/not/exist/either')
request.META['HTTP_REFERER'] = '/another/url/'
response = self.client.get(request.path)
@@ -424,89 +391,85 @@ class XFrameOptionsMiddlewareTest(TestCase):
"""
Tests for the X-Frame-Options clickjacking prevention middleware.
"""
- def setUp(self):
- self.x_frame_options = settings.X_FRAME_OPTIONS
-
- def tearDown(self):
- settings.X_FRAME_OPTIONS = self.x_frame_options
def test_same_origin(self):
"""
Tests that the X_FRAME_OPTIONS setting can be set to SAMEORIGIN to
have the middleware use that value for the HTTP header.
"""
- settings.X_FRAME_OPTIONS = 'SAMEORIGIN'
- r = XFrameOptionsMiddleware().process_response(HttpRequest(),
- HttpResponse())
- self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
+ with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
+ r = XFrameOptionsMiddleware().process_response(HttpRequest(),
+ HttpResponse())
+ self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
- settings.X_FRAME_OPTIONS = 'sameorigin'
- r = XFrameOptionsMiddleware().process_response(HttpRequest(),
+ with override_settings(X_FRAME_OPTIONS='sameorigin'):
+ r = XFrameOptionsMiddleware().process_response(HttpRequest(),
HttpResponse())
- self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
+ self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
def test_deny(self):
"""
Tests that the X_FRAME_OPTIONS setting can be set to DENY to
have the middleware use that value for the HTTP header.
"""
- settings.X_FRAME_OPTIONS = 'DENY'
- r = XFrameOptionsMiddleware().process_response(HttpRequest(),
- HttpResponse())
- self.assertEqual(r['X-Frame-Options'], 'DENY')
+ with override_settings(X_FRAME_OPTIONS='DENY'):
+ r = XFrameOptionsMiddleware().process_response(HttpRequest(),
+ HttpResponse())
+ self.assertEqual(r['X-Frame-Options'], 'DENY')
- settings.X_FRAME_OPTIONS = 'deny'
- r = XFrameOptionsMiddleware().process_response(HttpRequest(),
- HttpResponse())
- self.assertEqual(r['X-Frame-Options'], 'DENY')
+ with override_settings(X_FRAME_OPTIONS='deny'):
+ r = XFrameOptionsMiddleware().process_response(HttpRequest(),
+ HttpResponse())
+ self.assertEqual(r['X-Frame-Options'], 'DENY')
def test_defaults_sameorigin(self):
"""
Tests that if the X_FRAME_OPTIONS setting is not set then it defaults
to SAMEORIGIN.
"""
- del settings.X_FRAME_OPTIONS
- r = XFrameOptionsMiddleware().process_response(HttpRequest(),
- HttpResponse())
- self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
+ with override_settings(X_FRAME_OPTIONS=None):
+ del settings.X_FRAME_OPTIONS # restored by override_settings
+ r = XFrameOptionsMiddleware().process_response(HttpRequest(),
+ HttpResponse())
+ self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
def test_dont_set_if_set(self):
"""
Tests that if the X-Frame-Options header is already set then the
middleware does not attempt to override it.
"""
- settings.X_FRAME_OPTIONS = 'DENY'
- response = HttpResponse()
- response['X-Frame-Options'] = 'SAMEORIGIN'
- r = XFrameOptionsMiddleware().process_response(HttpRequest(),
- response)
- self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
+ with override_settings(X_FRAME_OPTIONS='DENY'):
+ response = HttpResponse()
+ response['X-Frame-Options'] = 'SAMEORIGIN'
+ r = XFrameOptionsMiddleware().process_response(HttpRequest(),
+ response)
+ self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
- settings.X_FRAME_OPTIONS = 'SAMEORIGIN'
- response = HttpResponse()
- response['X-Frame-Options'] = 'DENY'
- r = XFrameOptionsMiddleware().process_response(HttpRequest(),
- response)
- self.assertEqual(r['X-Frame-Options'], 'DENY')
+ with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
+ response = HttpResponse()
+ response['X-Frame-Options'] = 'DENY'
+ r = XFrameOptionsMiddleware().process_response(HttpRequest(),
+ response)
+ self.assertEqual(r['X-Frame-Options'], 'DENY')
def test_response_exempt(self):
"""
Tests that if the response has a xframe_options_exempt attribute set
to False then it still sets the header, but if it's set to True then
it does not.
"""
- settings.X_FRAME_OPTIONS = 'SAMEORIGIN'
- response = HttpResponse()
- response.xframe_options_exempt = False
- r = XFrameOptionsMiddleware().process_response(HttpRequest(),
- response)
- self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
+ with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
+ response = HttpResponse()
+ response.xframe_options_exempt = False
+ r = XFrameOptionsMiddleware().process_response(HttpRequest(),
+ response)
+ self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
- response = HttpResponse()
- response.xframe_options_exempt = True
- r = XFrameOptionsMiddleware().process_response(HttpRequest(),
- response)
- self.assertEqual(r.get('X-Frame-Options', None), None)
+ response = HttpResponse()
+ response.xframe_options_exempt = True
+ r = XFrameOptionsMiddleware().process_response(HttpRequest(),
+ response)
+ self.assertEqual(r.get('X-Frame-Options', None), None)
def test_is_extendable(self):
"""
@@ -523,23 +486,23 @@ def get_xframe_options_value(self, request, response):
return 'SAMEORIGIN'
return 'DENY'
- settings.X_FRAME_OPTIONS = 'DENY'
- response = HttpResponse()
- response.sameorigin = True
- r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(),
- response)
- self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
-
- request = HttpRequest()
- request.sameorigin = True
- r = OtherXFrameOptionsMiddleware().process_response(request,
- HttpResponse())
- self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
-
- settings.X_FRAME_OPTIONS = 'SAMEORIGIN'
- r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(),
- HttpResponse())
- self.assertEqual(r['X-Frame-Options'], 'DENY')
+ with override_settings(X_FRAME_OPTIONS='DENY'):
+ response = HttpResponse()
+ response.sameorigin = True
+ r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(),
+ response)
+ self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
+
+ request = HttpRequest()
+ request.sameorigin = True
+ r = OtherXFrameOptionsMiddleware().process_response(request,
+ HttpResponse())
+ self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
+
+ with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
+ r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(),
+ HttpResponse())
+ self.assertEqual(r['X-Frame-Options'], 'DENY')
class GZipMiddlewareTest(TestCase):

0 comments on commit 3aacf5f

Please sign in to comment.
Something went wrong with that request. Please try again.