1
0
mirror of https://github.com/django/django.git synced 2025-06-03 10:39:12 +00:00

Merge branch 'master' into schema-alteration

This commit is contained in:
Andrew Godwin 2012-09-07 15:43:28 -04:00
commit 828d691f62
59 changed files with 416 additions and 417 deletions

View File

@ -1,8 +1,9 @@
from django.conf import settings from django.conf import settings
from django.contrib.auth.models import (Group, User, SiteProfileNotAvailable,
UserManager)
from django.test import TestCase from django.test import TestCase
from django.test.utils import override_settings from django.test.utils import override_settings
from django.contrib.auth.models import (Group, User, from django.utils import six
SiteProfileNotAvailable, UserManager)
@override_settings(USE_TZ=False, AUTH_PROFILE_MODULE='') @override_settings(USE_TZ=False, AUTH_PROFILE_MODULE='')
@ -13,19 +14,19 @@ class ProfileTestCase(TestCase):
# calling get_profile without AUTH_PROFILE_MODULE set # calling get_profile without AUTH_PROFILE_MODULE set
del settings.AUTH_PROFILE_MODULE del settings.AUTH_PROFILE_MODULE
with self.assertRaisesRegexp(SiteProfileNotAvailable, with six.assertRaisesRegex(self, SiteProfileNotAvailable,
"You need to set AUTH_PROFILE_MODULE in your project"): "You need to set AUTH_PROFILE_MODULE in your project"):
user.get_profile() user.get_profile()
# Bad syntax in AUTH_PROFILE_MODULE: # Bad syntax in AUTH_PROFILE_MODULE:
settings.AUTH_PROFILE_MODULE = 'foobar' settings.AUTH_PROFILE_MODULE = 'foobar'
with self.assertRaisesRegexp(SiteProfileNotAvailable, with six.assertRaisesRegex(self, SiteProfileNotAvailable,
"app_label and model_name should be separated by a dot"): "app_label and model_name should be separated by a dot"):
user.get_profile() user.get_profile()
# module that doesn't exist # module that doesn't exist
settings.AUTH_PROFILE_MODULE = 'foo.bar' settings.AUTH_PROFILE_MODULE = 'foo.bar'
with self.assertRaisesRegexp(SiteProfileNotAvailable, with six.assertRaisesRegex(self, SiteProfileNotAvailable,
"Unable to load the profile model"): "Unable to load the profile model"):
user.get_profile() user.get_profile()

View File

@ -4,6 +4,7 @@ HR-specific Form helpers
""" """
from __future__ import absolute_import, unicode_literals from __future__ import absolute_import, unicode_literals
import datetime
import re import re
from django.contrib.localflavor.hr.hr_choices import ( from django.contrib.localflavor.hr.hr_choices import (
@ -91,17 +92,16 @@ class HRJMBGField(Field):
dd = int(matches.group('dd')) dd = int(matches.group('dd'))
mm = int(matches.group('mm')) mm = int(matches.group('mm'))
yyy = int(matches.group('yyy')) yyy = int(matches.group('yyy'))
import datetime
try: try:
datetime.date(yyy,mm,dd) datetime.date(yyy, mm, dd)
except: except ValueError:
raise ValidationError(self.error_messages['date']) raise ValidationError(self.error_messages['date'])
# Validate checksum. # Validate checksum.
k = matches.group('k') k = matches.group('k')
checksum = 0 checksum = 0
for i,j in zip(range(7,1,-1),range(6)): for i, j in zip(range(7, 1, -1), range(6)):
checksum+=i*(int(value[j])+int(value[13-i])) checksum += i * (int(value[j]) + int(value[13 - i]))
m = 11 - checksum % 11 m = 11 - checksum % 11
if m == 10: if m == 10:
raise ValidationError(self.error_messages['invalid']) raise ValidationError(self.error_messages['invalid'])

View File

@ -4,6 +4,8 @@ Romanian specific form helpers.
""" """
from __future__ import absolute_import, unicode_literals from __future__ import absolute_import, unicode_literals
import datetime
from django.contrib.localflavor.ro.ro_counties import COUNTIES_CHOICES from django.contrib.localflavor.ro.ro_counties import COUNTIES_CHOICES
from django.core.validators import EMPTY_VALUES from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError, Field, RegexField, Select from django.forms import ValidationError, Field, RegexField, Select
@ -69,10 +71,9 @@ class ROCNPField(RegexField):
if value in EMPTY_VALUES: if value in EMPTY_VALUES:
return '' return ''
# check birthdate digits # check birthdate digits
import datetime
try: try:
datetime.date(int(value[1:3]),int(value[3:5]),int(value[5:7])) datetime.date(int(value[1:3]), int(value[3:5]), int(value[5:7]))
except: except ValueError:
raise ValidationError(self.error_messages['invalid']) raise ValidationError(self.error_messages['invalid'])
# checksum # checksum
key = '279146358279' key = '279146358279'
@ -118,7 +119,7 @@ class ROCountyField(Field):
# search for county name # search for county name
normalized_CC = [] normalized_CC = []
for entry in COUNTIES_CHOICES: for entry in COUNTIES_CHOICES:
normalized_CC.append((entry[0],entry[1].upper())) normalized_CC.append((entry[0], entry[1].upper()))
for entry in normalized_CC: for entry in normalized_CC:
if entry[1] == value: if entry[1] == value:
return entry[0] return entry[0]
@ -153,8 +154,8 @@ class ROIBANField(RegexField):
value = super(ROIBANField, self).clean(value) value = super(ROIBANField, self).clean(value)
if value in EMPTY_VALUES: if value in EMPTY_VALUES:
return '' return ''
value = value.replace('-','') value = value.replace('-', '')
value = value.replace(' ','') value = value.replace(' ', '')
value = value.upper() value = value.upper()
if value[0:2] != 'RO': if value[0:2] != 'RO':
raise ValidationError(self.error_messages['invalid']) raise ValidationError(self.error_messages['invalid'])
@ -185,10 +186,10 @@ class ROPhoneNumberField(RegexField):
value = super(ROPhoneNumberField, self).clean(value) value = super(ROPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES: if value in EMPTY_VALUES:
return '' return ''
value = value.replace('-','') value = value.replace('-', '')
value = value.replace('(','') value = value.replace('(', '')
value = value.replace(')','') value = value.replace(')', '')
value = value.replace(' ','') value = value.replace(' ', '')
if len(value) != 10: if len(value) != 10:
raise ValidationError(self.error_messages['invalid']) raise ValidationError(self.error_messages['invalid'])
return value return value
@ -202,4 +203,3 @@ class ROPostalCodeField(RegexField):
def __init__(self, max_length=6, min_length=6, *args, **kwargs): def __init__(self, max_length=6, min_length=6, *args, **kwargs):
super(ROPostalCodeField, self).__init__(r'^[0-9][0-8][0-9]{4}$', super(ROPostalCodeField, self).__init__(r'^[0-9][0-8][0-9]{4}$',
max_length, min_length, *args, **kwargs) max_length, min_length, *args, **kwargs)

View File

@ -141,7 +141,7 @@ class CacheClass(BaseMemcachedCache):
) )
try: try:
import memcache import memcache
except: except ImportError:
raise InvalidCacheBackendError( raise InvalidCacheBackendError(
"Memcached cache backend requires either the 'memcache' or 'cmemcache' library" "Memcached cache backend requires either the 'memcache' or 'cmemcache' library"
) )

View File

@ -21,7 +21,7 @@ class EmailBackend(BaseEmailBackend):
stream_created = self.open() stream_created = self.open()
for message in email_messages: for message in email_messages:
self.stream.write('%s\n' % message.message().as_string()) self.stream.write('%s\n' % message.message().as_string())
self.stream.write('-'*79) self.stream.write('-' * 79)
self.stream.write('\n') self.stream.write('\n')
self.stream.flush() # flush after each message self.stream.flush() # flush after each message
if stream_created: if stream_created:

View File

@ -1,8 +1,10 @@
import hashlib
import sys import sys
import time import time
from django.conf import settings from django.conf import settings
from django.db.utils import load_backend from django.db.utils import load_backend
from django.utils.encoding import force_bytes
from django.utils.six.moves import input from django.utils.six.moves import input
# The prefix to put on the default database name when creating # The prefix to put on the default database name when creating
@ -29,7 +31,10 @@ class BaseDatabaseCreation(object):
Generates a 32-bit digest of a set of arguments that can be used to Generates a 32-bit digest of a set of arguments that can be used to
shorten identifying names. shorten identifying names.
""" """
return '%x' % (abs(hash(args)) % 4294967296) # 2**32 h = hashlib.md5()
for arg in args:
h.update(force_bytes(arg))
return h.hexdigest()[:8]
def sql_create_model(self, model, style, known_models=set()): def sql_create_model(self, model, style, known_models=set()):
""" """

View File

@ -419,7 +419,4 @@ def _sqlite_format_dtdelta(dt, conn, days, secs, usecs):
return str(dt) return str(dt)
def _sqlite_regexp(re_pattern, re_string): def _sqlite_regexp(re_pattern, re_string):
try: return bool(re.search(re_pattern, re_string))
return bool(re.search(re_pattern, re_string))
except:
return False

View File

@ -4,7 +4,8 @@ from django.core.exceptions import FieldError
from django.db import transaction from django.db import transaction
from django.db.backends.util import truncate_name from django.db.backends.util import truncate_name
from django.db.models.query_utils import select_related_descend from django.db.models.query_utils import select_related_descend
from django.db.models.sql.constants import * from django.db.models.sql.constants import (SINGLE, MULTI, ORDER_DIR,
LOOKUP_SEP, GET_ITERATOR_CHUNK_SIZE)
from django.db.models.sql.datastructures import EmptyResultSet from django.db.models.sql.datastructures import EmptyResultSet
from django.db.models.sql.expressions import SQLEvaluator from django.db.models.sql.expressions import SQLEvaluator
from django.db.models.sql.query import get_order_dir, Query from django.db.models.sql.query import get_order_dir, Query
@ -811,7 +812,7 @@ class SQLCompiler(object):
raise EmptyResultSet raise EmptyResultSet
except EmptyResultSet: except EmptyResultSet:
if result_type == MULTI: if result_type == MULTI:
return empty_iter() return iter([])
else: else:
return return
@ -1088,13 +1089,6 @@ class SQLDateCompiler(SQLCompiler):
yield date yield date
def empty_iter():
"""
Returns an iterator containing no results.
"""
yield next(iter([]))
def order_modified_iter(cursor, trim, sentinel): def order_modified_iter(cursor, trim, sentinel):
""" """
Yields blocks of rows from a cursor. We use this iterator in the special Yields blocks of rows from a cursor. We use this iterator in the special

View File

@ -17,9 +17,9 @@ from django.db import connections, DEFAULT_DB_ALIAS
from django.db.models import signals from django.db.models import signals
from django.db.models.expressions import ExpressionNode from django.db.models.expressions import ExpressionNode
from django.db.models.fields import FieldDoesNotExist from django.db.models.fields import FieldDoesNotExist
from django.db.models.query_utils import InvalidQuery
from django.db.models.sql import aggregates as base_aggregates_module from django.db.models.sql import aggregates as base_aggregates_module
from django.db.models.sql.constants import * from django.db.models.sql.constants import (QUERY_TERMS, LOOKUP_SEP, ORDER_DIR,
SINGLE, ORDER_PATTERN, JoinInfo)
from django.db.models.sql.datastructures import EmptyResultSet, Empty, MultiJoin from django.db.models.sql.datastructures import EmptyResultSet, Empty, MultiJoin
from django.db.models.sql.expressions import SQLEvaluator from django.db.models.sql.expressions import SQLEvaluator
from django.db.models.sql.where import (WhereNode, Constraint, EverythingNode, from django.db.models.sql.where import (WhereNode, Constraint, EverythingNode,
@ -28,6 +28,7 @@ from django.core.exceptions import FieldError
__all__ = ['Query', 'RawQuery'] __all__ = ['Query', 'RawQuery']
class RawQuery(object): class RawQuery(object):
""" """
A single raw SQL query A single raw SQL query

View File

@ -71,7 +71,8 @@ class BaseFormSet(object):
return True return True
__nonzero__ = __bool__ # Python 2 __nonzero__ = __bool__ # Python 2
def _management_form(self): @property
def management_form(self):
"""Returns the ManagementForm instance for this FormSet.""" """Returns the ManagementForm instance for this FormSet."""
if self.is_bound: if self.is_bound:
form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix) form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix)
@ -84,7 +85,6 @@ class BaseFormSet(object):
MAX_NUM_FORM_COUNT: self.max_num MAX_NUM_FORM_COUNT: self.max_num
}) })
return form return form
management_form = property(_management_form)
def total_form_count(self): def total_form_count(self):
"""Returns the total number of forms in this FormSet.""" """Returns the total number of forms in this FormSet."""
@ -140,17 +140,18 @@ class BaseFormSet(object):
self.add_fields(form, i) self.add_fields(form, i)
return form return form
def _get_initial_forms(self): @property
def initial_forms(self):
"""Return a list of all the initial forms in this formset.""" """Return a list of all the initial forms in this formset."""
return self.forms[:self.initial_form_count()] return self.forms[:self.initial_form_count()]
initial_forms = property(_get_initial_forms)
def _get_extra_forms(self): @property
def extra_forms(self):
"""Return a list of all the extra forms in this formset.""" """Return a list of all the extra forms in this formset."""
return self.forms[self.initial_form_count():] return self.forms[self.initial_form_count():]
extra_forms = property(_get_extra_forms)
def _get_empty_form(self, **kwargs): @property
def empty_form(self, **kwargs):
defaults = { defaults = {
'auto_id': self.auto_id, 'auto_id': self.auto_id,
'prefix': self.add_prefix('__prefix__'), 'prefix': self.add_prefix('__prefix__'),
@ -160,19 +161,19 @@ class BaseFormSet(object):
form = self.form(**defaults) form = self.form(**defaults)
self.add_fields(form, None) self.add_fields(form, None)
return form return form
empty_form = property(_get_empty_form)
# Maybe this should just go away? # Maybe this should just go away?
def _get_cleaned_data(self): @property
def cleaned_data(self):
""" """
Returns a list of form.cleaned_data dicts for every form in self.forms. Returns a list of form.cleaned_data dicts for every form in self.forms.
""" """
if not self.is_valid(): if not self.is_valid():
raise AttributeError("'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__) raise AttributeError("'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__)
return [form.cleaned_data for form in self.forms] return [form.cleaned_data for form in self.forms]
cleaned_data = property(_get_cleaned_data)
def _get_deleted_forms(self): @property
def deleted_forms(self):
""" """
Returns a list of forms that have been marked for deletion. Raises an Returns a list of forms that have been marked for deletion. Raises an
AttributeError if deletion is not allowed. AttributeError if deletion is not allowed.
@ -191,9 +192,9 @@ class BaseFormSet(object):
if self._should_delete_form(form): if self._should_delete_form(form):
self._deleted_form_indexes.append(i) self._deleted_form_indexes.append(i)
return [self.forms[i] for i in self._deleted_form_indexes] return [self.forms[i] for i in self._deleted_form_indexes]
deleted_forms = property(_get_deleted_forms)
def _get_ordered_forms(self): @property
def ordered_forms(self):
""" """
Returns a list of form in the order specified by the incoming data. Returns a list of form in the order specified by the incoming data.
Raises an AttributeError if ordering is not allowed. Raises an AttributeError if ordering is not allowed.
@ -228,7 +229,6 @@ class BaseFormSet(object):
# Return a list of form.cleaned_data dicts in the order specified by # Return a list of form.cleaned_data dicts in the order specified by
# the form data. # the form data.
return [self.forms[i[0]] for i in self._ordering] return [self.forms[i[0]] for i in self._ordering]
ordered_forms = property(_get_ordered_forms)
@classmethod @classmethod
def get_default_prefix(cls): def get_default_prefix(cls):
@ -244,14 +244,14 @@ class BaseFormSet(object):
return self._non_form_errors return self._non_form_errors
return self.error_class() return self.error_class()
def _get_errors(self): @property
def errors(self):
""" """
Returns a list of form.errors for every form in self.forms. Returns a list of form.errors for every form in self.forms.
""" """
if self._errors is None: if self._errors is None:
self.full_clean() self.full_clean()
return self._errors return self._errors
errors = property(_get_errors)
def _should_delete_form(self, form): def _should_delete_form(self, form):
""" """
@ -332,14 +332,14 @@ class BaseFormSet(object):
""" """
return self.forms and self.forms[0].is_multipart() return self.forms and self.forms[0].is_multipart()
def _get_media(self): @property
def media(self):
# All the forms on a FormSet are the same, so you only need to # All the forms on a FormSet are the same, so you only need to
# interrogate the first form for media. # interrogate the first form for media.
if self.forms: if self.forms:
return self.forms[0].media return self.forms[0].media
else: else:
return Media() return Media()
media = property(_get_media)
def as_table(self): def as_table(self):
"Returns this formset rendered as HTML <tr>s -- excluding the <table></table>." "Returns this formset rendered as HTML <tr>s -- excluding the <table></table>."

View File

@ -507,11 +507,7 @@ class CheckboxInput(Widget):
def render(self, name, value, attrs=None): def render(self, name, value, attrs=None):
final_attrs = self.build_attrs(attrs, type='checkbox', name=name) final_attrs = self.build_attrs(attrs, type='checkbox', name=name)
try: if self.check_test(value):
result = self.check_test(value)
except: # Silently catch exceptions
result = False
if result:
final_attrs['checked'] = 'checked' final_attrs['checked'] = 'checked'
if not (value is True or value is False or value is None or value == ''): if not (value is True or value is False or value is None or value == ''):
# Only add the 'value' attribute if a value is non-empty. # Only add the 'value' attribute if a value is non-empty.
@ -525,7 +521,7 @@ class CheckboxInput(Widget):
return False return False
value = data.get(name) value = data.get(name)
# Translate true and false strings to boolean values. # Translate true and false strings to boolean values.
values = {'true': True, 'false': False} values = {'true': True, 'false': False}
if isinstance(value, six.string_types): if isinstance(value, six.string_types):
value = values.get(value.lower(), value) value = values.get(value.lower(), value)
return value return value

View File

@ -68,11 +68,10 @@ class MultiPartParser(object):
if not boundary or not cgi.valid_boundary(boundary): if not boundary or not cgi.valid_boundary(boundary):
raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary) raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary)
# Content-Length should contain the length of the body we are about # Content-Length should contain the length of the body we are about
# to receive. # to receive.
try: try:
content_length = int(META.get('HTTP_CONTENT_LENGTH', META.get('CONTENT_LENGTH',0))) content_length = int(META.get('HTTP_CONTENT_LENGTH', META.get('CONTENT_LENGTH', 0)))
except (ValueError, TypeError): except (ValueError, TypeError):
content_length = 0 content_length = 0
@ -178,7 +177,7 @@ class MultiPartParser(object):
content_type = meta_data.get('content-type', ('',))[0].strip() content_type = meta_data.get('content-type', ('',))[0].strip()
try: try:
charset = meta_data.get('content-type', (0,{}))[1].get('charset', None) charset = meta_data.get('content-type', (0, {}))[1].get('charset', None)
except: except:
charset = None charset = None

View File

@ -358,7 +358,7 @@ class SimpleTestCase(ut2.TestCase):
args: Extra args. args: Extra args.
kwargs: Extra kwargs. kwargs: Extra kwargs.
""" """
return self.assertRaisesRegexp(expected_exception, return six.assertRaisesRegex(self, expected_exception,
re.escape(expected_message), callable_obj, *args, **kwargs) re.escape(expected_message), callable_obj, *args, **kwargs)
def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None, def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None,

View File

@ -370,13 +370,20 @@ def with_metaclass(meta, base=object):
if PY3: if PY3:
_iterlists = "lists" _iterlists = "lists"
_assertRaisesRegex = "assertRaisesRegex"
else: else:
_iterlists = "iterlists" _iterlists = "iterlists"
_assertRaisesRegex = "assertRaisesRegexp"
def iterlists(d): def iterlists(d):
"""Return an iterator over the values of a MultiValueDict.""" """Return an iterator over the values of a MultiValueDict."""
return getattr(d, _iterlists)() return getattr(d, _iterlists)()
def assertRaisesRegex(self, *args, **kwargs):
return getattr(self, _assertRaisesRegex)(*args, **kwargs)
add_move(MovedModule("_dummy_thread", "dummy_thread")) add_move(MovedModule("_dummy_thread", "dummy_thread"))
add_move(MovedModule("_thread", "thread")) add_move(MovedModule("_thread", "thread"))

View File

@ -517,7 +517,7 @@ URLconf by removing the leading "polls/" from each line, and removing the
lines registering the admin site. Your ``polls/urls.py`` file should now look like lines registering the admin site. Your ``polls/urls.py`` file should now look like
this:: this::
from django.conf.urls import patterns, include, url from django.conf.urls import patterns, url
urlpatterns = patterns('polls.views', urlpatterns = patterns('polls.views',
url(r'^$', 'index'), url(r'^$', 'index'),

View File

@ -80,7 +80,7 @@ geospatial libraries:
Program Description Required Supported Versions Program Description Required Supported Versions
======================== ==================================== ================================ ========================== ======================== ==================================== ================================ ==========================
:ref:`GEOS <ref-geos>` Geometry Engine Open Source Yes 3.3, 3.2, 3.1, 3.0 :ref:`GEOS <ref-geos>` Geometry Engine Open Source Yes 3.3, 3.2, 3.1, 3.0
`PROJ.4`_ Cartographic Projections library Yes (PostgreSQL and SQLite only) 4.7, 4.6, 4.5, 4.4 `PROJ.4`_ Cartographic Projections library Yes (PostgreSQL and SQLite only) 4.8, 4.7, 4.6, 4.5, 4.4
:ref:`GDAL <ref-gdal>` Geospatial Data Abstraction Library No (but, required for SQLite) 1.9, 1.8, 1.7, 1.6, 1.5 :ref:`GDAL <ref-gdal>` Geospatial Data Abstraction Library No (but, required for SQLite) 1.9, 1.8, 1.7, 1.6, 1.5
:ref:`GeoIP <ref-geoip>` IP-based geolocation library No 1.4 :ref:`GeoIP <ref-geoip>` IP-based geolocation library No 1.4
`PostGIS`__ Spatial extensions for PostgreSQL Yes (PostgreSQL only) 1.5, 1.4, 1.3 `PostGIS`__ Spatial extensions for PostgreSQL Yes (PostgreSQL only) 1.5, 1.4, 1.3
@ -140,16 +140,16 @@ internal geometry representation used by GeoDjango (it's behind the "lazy"
geometries). Specifically, the C API library is called (e.g., ``libgeos_c.so``) geometries). Specifically, the C API library is called (e.g., ``libgeos_c.so``)
directly from Python using ctypes. directly from Python using ctypes.
First, download GEOS 3.3.0 from the refractions Web site and untar the source First, download GEOS 3.3.5 from the refractions Web site and untar the source
archive:: archive::
$ wget http://download.osgeo.org/geos/geos-3.3.0.tar.bz2 $ wget http://download.osgeo.org/geos/geos-3.3.5.tar.bz2
$ tar xjf geos-3.3.0.tar.bz2 $ tar xjf geos-3.3.5.tar.bz2
Next, change into the directory where GEOS was unpacked, run the configure Next, change into the directory where GEOS was unpacked, run the configure
script, compile, and install:: script, compile, and install::
$ cd geos-3.3.0 $ cd geos-3.3.5
$ ./configure $ ./configure
$ make $ make
$ sudo make install $ sudo make install
@ -203,15 +203,15 @@ reference systems.
First, download the PROJ.4 source code and datum shifting files [#]_:: First, download the PROJ.4 source code and datum shifting files [#]_::
$ wget http://download.osgeo.org/proj/proj-4.7.0.tar.gz $ wget http://download.osgeo.org/proj/proj-4.8.0.tar.gz
$ wget http://download.osgeo.org/proj/proj-datumgrid-1.5.zip $ wget http://download.osgeo.org/proj/proj-datumgrid-1.5.tar.gz
Next, untar the source code archive, and extract the datum shifting files in the Next, untar the source code archive, and extract the datum shifting files in the
``nad`` subdirectory. This must be done *prior* to configuration:: ``nad`` subdirectory. This must be done *prior* to configuration::
$ tar xzf proj-4.7.0.tar.gz $ tar xzf proj-4.8.0.tar.gz
$ cd proj-4.7.0/nad $ cd proj-4.8.0/nad
$ unzip ../../proj-datumgrid-1.5.zip $ tar xzf ../../proj-datumgrid-1.5.tar.gz
$ cd .. $ cd ..
Finally, configure, make and install PROJ.4:: Finally, configure, make and install PROJ.4::
@ -239,9 +239,9 @@ installed prior to building PostGIS.
First download the source archive, and extract:: First download the source archive, and extract::
$ wget http://postgis.refractions.net/download/postgis-1.5.2.tar.gz $ wget http://postgis.refractions.net/download/postgis-1.5.5.tar.gz
$ tar xzf postgis-1.5.2.tar.gz $ tar xzf postgis-1.5.5.tar.gz
$ cd postgis-1.5.2 $ cd postgis-1.5.5
Next, configure, make and install PostGIS:: Next, configure, make and install PostGIS::

View File

@ -70,9 +70,8 @@ overridden:
formfield-specific piece of validation and, possibly, formfield-specific piece of validation and, possibly,
cleaning/normalizing the data. cleaning/normalizing the data.
Just like the general field ``clean()`` method, above, this method This method should return the cleaned value obtained from cleaned_data,
should return the cleaned data, regardless of whether it changed regardless of whether it changed anything or not.
anything or not.
* The Form subclass's ``clean()`` method. This method can perform * The Form subclass's ``clean()`` method. This method can perform
any validation that requires access to multiple fields from the form at any validation that requires access to multiple fields from the form at

View File

@ -310,6 +310,10 @@ commonly used groups of widgets:
A callable that takes the value of the CheckBoxInput and returns A callable that takes the value of the CheckBoxInput and returns
``True`` if the checkbox should be checked for that value. ``True`` if the checkbox should be checked for that value.
.. versionchanged:: 1.5
Exceptions from ``check_test`` used to be silenced by its caller,
this is no longer the case, they will propagate upwards.
``Select`` ``Select``
~~~~~~~~~~ ~~~~~~~~~~

View File

@ -83,9 +83,10 @@ Django quotes column and table names behind the scenes.
.. attribute:: Options.get_latest_by .. attribute:: Options.get_latest_by
The name of a :class:`DateField` or :class:`DateTimeField` in the model. The name of an orderable field in the model, typically a :class:`DateField`,
This specifies the default field to use in your model :class:`Manager`'s :class:`DateTimeField`, or :class:`IntegerField`. This specifies the default
:class:`~QuerySet.latest` method. field to use in your model :class:`Manager`'s :class:`~QuerySet.latest`
method.
Example:: Example::

View File

@ -2064,7 +2064,7 @@ Note this is only available in MySQL and requires direct manipulation of the
database to add the full-text index. By default Django uses BOOLEAN MODE for database to add the full-text index. By default Django uses BOOLEAN MODE for
full text searches. See the `MySQL documentation`_ for additional details. full text searches. See the `MySQL documentation`_ for additional details.
.. _MySQL documentation: http://dev.mysql.com/doc/refman/5.1/en/fulltext-boolean.html> .. _MySQL documentation: http://dev.mysql.com/doc/refman/5.1/en/fulltext-boolean.html
.. fieldlookup:: regex .. fieldlookup:: regex
@ -2236,4 +2236,3 @@ Variance
extension. extension.
.. _SQLite documentation: http://www.sqlite.org/contrib .. _SQLite documentation: http://www.sqlite.org/contrib

View File

@ -587,7 +587,7 @@ gettext domain):
ones listed later. ones listed later.
* The ``locale`` subdirectory of the directory containing the settings, that * The ``locale`` subdirectory of the directory containing the settings, that
usually coincides with and is know as the *project directory* is being usually coincides with and is known as the *project directory* is being
deprecated in this release as a source of translations. (the precedence of deprecated in this release as a source of translations. (the precedence of
these translations is intermediate between applications and :setting:`LOCALE_PATHS` these translations is intermediate between applications and :setting:`LOCALE_PATHS`
translations). See the `corresponding deprecated features section`_ translations). See the `corresponding deprecated features section`_

View File

@ -235,14 +235,14 @@ refinements together. For example::
... ).exclude( ... ).exclude(
... pub_date__gte=datetime.now() ... pub_date__gte=datetime.now()
... ).filter( ... ).filter(
... pub_date__gte=datetime(2005, 1, 1) ... pub_date__gte=datetime(2005, 1, 30)
... ) ... )
This takes the initial :class:`~django.db.models.query.QuerySet` of all entries This takes the initial :class:`~django.db.models.query.QuerySet` of all entries
in the database, adds a filter, then an exclusion, then another filter. The in the database, adds a filter, then an exclusion, then another filter. The
final result is a :class:`~django.db.models.query.QuerySet` containing all final result is a :class:`~django.db.models.query.QuerySet` containing all
entries with a headline that starts with "What", that were published between entries with a headline that starts with "What", that were published between
January 1, 2005, and the current day. January 30, 2005, and the current day.
.. _filtered-querysets-are-unique: .. _filtered-querysets-are-unique:

View File

@ -25,10 +25,11 @@ free to chose another strategy for your own code, especially if you don't need
to stay compatible with Python 2. But authors of pluggable applications are to stay compatible with Python 2. But authors of pluggable applications are
encouraged to use the same porting strategy as Django itself. encouraged to use the same porting strategy as Django itself.
Writing compatible code is much easier if you target Python ≥ 2.6. You will Writing compatible code is much easier if you target Python ≥ 2.6. Django 1.5
most likely take advantage of the compatibility functions introduced in Django introduces compatibility tools such as :mod:`django.utils.six`. For
1.5, like :mod:`django.utils.six`, so your application will also require convenience, forwards-compatible aliases were introduced in Django 1.4.2. If
Django ≥ 1.5. your application takes advantage of these tools, it will require Django ≥
1.4.2.
Obviously, writing compatible source code adds some overhead, and that can Obviously, writing compatible source code adds some overhead, and that can
cause frustration. Django's developers have found that attempting to write cause frustration. Django's developers have found that attempting to write
@ -102,6 +103,8 @@ Old name New name
For backwards compatibility, the old names still work on Python 2. Under For backwards compatibility, the old names still work on Python 2. Under
Python 3, ``smart_str`` is an alias for ``smart_text``. Python 3, ``smart_str`` is an alias for ``smart_text``.
For forwards compatibility, the new names work as of Django 1.4.2.
.. note:: .. note::
:mod:`django.utils.encoding` was deeply refactored in Django 1.5 to :mod:`django.utils.encoding` was deeply refactored in Django 1.5 to
@ -126,6 +129,8 @@ For backwards compatibility, the old names still work on Python 2. Under
Python 3, ``EscapeString`` and ``SafeString`` are aliases for ``EscapeText`` Python 3, ``EscapeString`` and ``SafeString`` are aliases for ``EscapeText``
and ``SafeText`` respectively. and ``SafeText`` respectively.
For forwards compatibility, the new names work as of Django 1.4.2.
:meth:`__str__` and :meth:`__unicode__` methods :meth:`__str__` and :meth:`__unicode__` methods
----------------------------------------------- -----------------------------------------------
@ -166,6 +171,8 @@ On Python 3, the decorator is a no-op. On Python 2, it defines appropriate
This technique is the best match for Django's porting philosophy. This technique is the best match for Django's porting philosophy.
For forwards compatibility, this decorator is available as of Django 1.4.2.
Finally, note that :meth:`__repr__` must return a :class:`str` on all versions Finally, note that :meth:`__repr__` must return a :class:`str` on all versions
of Python. of Python.
@ -317,7 +324,8 @@ Writing compatible code with six
six_ is the canonical compatibility library for supporting Python 2 and 3 in six_ is the canonical compatibility library for supporting Python 2 and 3 in
a single codebase. Read its documentation! a single codebase. Read its documentation!
:mod:`six` is bundled with Django: you can import it as :mod:`django.utils.six`. :mod`six` is bundled with Django as of version 1.4.2. You can import it as
:mod`django.utils.six`.
Here are the most common changes required to write compatible code. Here are the most common changes required to write compatible code.

View File

@ -76,9 +76,17 @@ POST to your Web site and have another logged in user unwittingly submit that
form. The malicious user would have to know the nonce, which is user specific form. The malicious user would have to know the nonce, which is user specific
(using a cookie). (using a cookie).
When deployed with :ref:`HTTPS <security-recommendation-ssl>`,
``CsrfViewMiddleware`` will check that the HTTP referer header is set to a
URL on the same origin (including subdomain and port). Because HTTPS
provides additional security, it is imperative to ensure connections use HTTPS
where it is available by forwarding insecure connection requests and using
HSTS for supported browsers.
Be very careful with marking views with the ``csrf_exempt`` decorator unless Be very careful with marking views with the ``csrf_exempt`` decorator unless
it is absolutely necessary. it is absolutely necessary.
SQL injection protection SQL injection protection
======================== ========================
@ -112,6 +120,8 @@ The middleware is strongly recommended for any site that does not need to have
its pages wrapped in a frame by third party sites, or only needs to allow that its pages wrapped in a frame by third party sites, or only needs to allow that
for a small section of the site. for a small section of the site.
.. _security-recommendation-ssl:
SSL/HTTPS SSL/HTTPS
========= =========
@ -147,7 +157,15 @@ server, there are some additional steps you may need:
any POST data being accepted over HTTP (which will be fine if you are any POST data being accepted over HTTP (which will be fine if you are
redirecting all HTTP traffic to HTTPS). redirecting all HTTP traffic to HTTPS).
.. _additional-security-topics: * Use HTTP Strict Transport Security (HSTS)
HSTS is an HTTP header that informs a browser that all future connections
to a particular site should always use HTTPS. Combined with redirecting
requests over HTTP to HTTPS, this will ensure that connections always enjoy
the added security of SSL provided one successful connection has occurred.
HSTS is usually configured on the web server.
.. _host-headers-virtual-hosting:
Host headers and virtual hosting Host headers and virtual hosting
================================ ================================
@ -158,15 +176,17 @@ Site Scripting attacks, they can be used for Cross-Site Request
Forgery and cache poisoning attacks in some circumstances. We Forgery and cache poisoning attacks in some circumstances. We
recommend you ensure your Web server is configured such that: recommend you ensure your Web server is configured such that:
* It always validates incoming HTTP ``Host`` headers against the expected * It always validates incoming HTTP ``Host`` headers against the expected
host name. host name.
* Disallows requests with no ``Host`` header. * Disallows requests with no ``Host`` header.
* Is *not* configured with a catch-all virtual host that forwards requests * Is *not* configured with a catch-all virtual host that forwards requests
to a Django application. to a Django application.
Additionally, as of 1.3.1, Django requires you to explicitly enable support for Additionally, as of 1.3.1, Django requires you to explicitly enable support for
the ``X-Forwarded-Host`` header if your configuration requires it. the ``X-Forwarded-Host`` header if your configuration requires it.
.. _additional-security-topics:
Additional security topics Additional security topics
========================== ==========================

View File

@ -5,7 +5,7 @@ from datetime import datetime
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
from django.db.models.fields import Field, FieldDoesNotExist from django.db.models.fields import Field, FieldDoesNotExist
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from django.utils.six import PY3 from django.utils import six
from django.utils.translation import ugettext_lazy from django.utils.translation import ugettext_lazy
from .models import Article from .models import Article
@ -82,7 +82,7 @@ class ModelTest(TestCase):
# Django raises an Article.DoesNotExist exception for get() if the # Django raises an Article.DoesNotExist exception for get() if the
# parameters don't match any object. # parameters don't match any object.
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ObjectDoesNotExist, ObjectDoesNotExist,
"Article matching query does not exist. Lookup parameters were " "Article matching query does not exist. Lookup parameters were "
"{'id__exact': 2000}", "{'id__exact': 2000}",
@ -91,14 +91,14 @@ class ModelTest(TestCase):
) )
# To avoid dict-ordering related errors check only one lookup # To avoid dict-ordering related errors check only one lookup
# in single assert. # in single assert.
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ObjectDoesNotExist, ObjectDoesNotExist,
".*'pub_date__year': 2005.*", ".*'pub_date__year': 2005.*",
Article.objects.get, Article.objects.get,
pub_date__year=2005, pub_date__year=2005,
pub_date__month=8, pub_date__month=8,
) )
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ObjectDoesNotExist, ObjectDoesNotExist,
".*'pub_date__month': 8.*", ".*'pub_date__month': 8.*",
Article.objects.get, Article.objects.get,
@ -106,7 +106,7 @@ class ModelTest(TestCase):
pub_date__month=8, pub_date__month=8,
) )
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ObjectDoesNotExist, ObjectDoesNotExist,
"Article matching query does not exist. Lookup parameters were " "Article matching query does not exist. Lookup parameters were "
"{'pub_date__week_day': 6}", "{'pub_date__week_day': 6}",
@ -168,7 +168,7 @@ class ModelTest(TestCase):
self.assertEqual(a4.headline, 'Fourth article') self.assertEqual(a4.headline, 'Fourth article')
# Don't use invalid keyword arguments. # Don't use invalid keyword arguments.
self.assertRaisesRegexp( six.assertRaisesRegex(self,
TypeError, TypeError,
"'foo' is an invalid keyword argument for this function", "'foo' is an invalid keyword argument for this function",
Article, Article,
@ -259,13 +259,13 @@ class ModelTest(TestCase):
"datetime.datetime(2005, 7, 28, 0, 0)"]) "datetime.datetime(2005, 7, 28, 0, 0)"])
# dates() requires valid arguments. # dates() requires valid arguments.
self.assertRaisesRegexp( six.assertRaisesRegex(self,
TypeError, TypeError,
"dates\(\) takes at least 3 arguments \(1 given\)", "dates\(\) takes at least 3 arguments \(1 given\)",
Article.objects.dates, Article.objects.dates,
) )
self.assertRaisesRegexp( six.assertRaisesRegex(self,
FieldDoesNotExist, FieldDoesNotExist,
"Article has no field named 'invalid_field'", "Article has no field named 'invalid_field'",
Article.objects.dates, Article.objects.dates,
@ -273,7 +273,7 @@ class ModelTest(TestCase):
"year", "year",
) )
self.assertRaisesRegexp( six.assertRaisesRegex(self,
AssertionError, AssertionError,
"'kind' must be one of 'year', 'month' or 'day'.", "'kind' must be one of 'year', 'month' or 'day'.",
Article.objects.dates, Article.objects.dates,
@ -281,7 +281,7 @@ class ModelTest(TestCase):
"bad_kind", "bad_kind",
) )
self.assertRaisesRegexp( six.assertRaisesRegex(self,
AssertionError, AssertionError,
"'order' must be either 'ASC' or 'DESC'.", "'order' must be either 'ASC' or 'DESC'.",
Article.objects.dates, Article.objects.dates,
@ -323,7 +323,7 @@ class ModelTest(TestCase):
"<Article: Third article>"]) "<Article: Third article>"])
# Slicing works with longs (Python 2 only -- Python 3 doesn't have longs). # Slicing works with longs (Python 2 only -- Python 3 doesn't have longs).
if not PY3: if not six.PY3:
self.assertEqual(Article.objects.all()[long(0)], a) self.assertEqual(Article.objects.all()[long(0)], a)
self.assertQuerysetEqual(Article.objects.all()[long(1):long(3)], self.assertQuerysetEqual(Article.objects.all()[long(1):long(3)],
["<Article: Second article>", "<Article: Third article>"]) ["<Article: Second article>", "<Article: Third article>"])
@ -369,14 +369,14 @@ class ModelTest(TestCase):
"<Article: Updated article 8>"]) "<Article: Updated article 8>"])
# Also, once you have sliced you can't filter, re-order or combine # Also, once you have sliced you can't filter, re-order or combine
self.assertRaisesRegexp( six.assertRaisesRegex(self,
AssertionError, AssertionError,
"Cannot filter a query once a slice has been taken.", "Cannot filter a query once a slice has been taken.",
Article.objects.all()[0:5].filter, Article.objects.all()[0:5].filter,
id=a.id, id=a.id,
) )
self.assertRaisesRegexp( six.assertRaisesRegex(self,
AssertionError, AssertionError,
"Cannot reorder a query once a slice has been taken.", "Cannot reorder a query once a slice has been taken.",
Article.objects.all()[0:5].order_by, Article.objects.all()[0:5].order_by,
@ -411,7 +411,7 @@ class ModelTest(TestCase):
# An Article instance doesn't have access to the "objects" attribute. # An Article instance doesn't have access to the "objects" attribute.
# That's only available on the class. # That's only available on the class.
self.assertRaisesRegexp( six.assertRaisesRegex(self,
AttributeError, AttributeError,
"Manager isn't accessible via Article instances", "Manager isn't accessible via Article instances",
getattr, getattr,

View File

@ -1,10 +1,10 @@
from __future__ import absolute_import from __future__ import absolute_import
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.db.models.loading import get_app from django.db.models.loading import get_app
from django.test import TestCase from django.test import TestCase
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils import six
from .models import Empty from .models import Empty
@ -14,12 +14,13 @@ class EmptyModelTests(TestCase):
m = Empty() m = Empty()
self.assertEqual(m.id, None) self.assertEqual(m.id, None)
m.save() m.save()
m2 = Empty.objects.create() Empty.objects.create()
self.assertEqual(len(Empty.objects.all()), 2) self.assertEqual(len(Empty.objects.all()), 2)
self.assertTrue(m.id is not None) self.assertTrue(m.id is not None)
existing = Empty(m.id) existing = Empty(m.id)
existing.save() existing.save()
class NoModelTests(TestCase): class NoModelTests(TestCase):
""" """
Test for #7198 to ensure that the proper error message is raised Test for #7198 to ensure that the proper error message is raised
@ -32,6 +33,6 @@ class NoModelTests(TestCase):
""" """
@override_settings(INSTALLED_APPS=("modeltests.empty.no_models",)) @override_settings(INSTALLED_APPS=("modeltests.empty.no_models",))
def test_no_models(self): def test_no_models(self):
with self.assertRaisesRegexp(ImproperlyConfigured, with six.assertRaisesRegex(self, ImproperlyConfigured,
'App with label no_models is missing a models.py module.'): 'App with label no_models is missing a models.py module.'):
get_app('no_models') get_app('no_models')

View File

@ -4,7 +4,7 @@ from django.contrib.sites.models import Site
from django.core import management from django.core import management
from django.db import connection, IntegrityError from django.db import connection, IntegrityError
from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature
from django.utils.six import StringIO from django.utils import six
from .models import Article, Book, Spy, Tag, Visa from .models import Article, Book, Spy, Tag, Visa
@ -21,16 +21,17 @@ class TestCaseFixtureLoadingTests(TestCase):
'<Article: Poker has no place on ESPN>', '<Article: Poker has no place on ESPN>',
]) ])
class FixtureLoadingTests(TestCase): class FixtureLoadingTests(TestCase):
def _dumpdata_assert(self, args, output, format='json', natural_keys=False, def _dumpdata_assert(self, args, output, format='json', natural_keys=False,
use_base_manager=False, exclude_list=[]): use_base_manager=False, exclude_list=[]):
new_io = StringIO() new_io = six.StringIO()
management.call_command('dumpdata', *args, **{'format':format, management.call_command('dumpdata', *args, **{'format': format,
'stdout':new_io, 'stdout': new_io,
'stderr':new_io, 'stderr': new_io,
'use_natural_keys':natural_keys, 'use_natural_keys': natural_keys,
'use_base_manager':use_base_manager, 'use_base_manager': use_base_manager,
'exclude': exclude_list}) 'exclude': exclude_list})
command_output = new_io.getvalue().strip() command_output = new_io.getvalue().strip()
self.assertEqual(command_output, output) self.assertEqual(command_output, output)
@ -42,8 +43,6 @@ class FixtureLoadingTests(TestCase):
]) ])
def test_loading_and_dumping(self): def test_loading_and_dumping(self):
new_io = StringIO()
Site.objects.all().delete() Site.objects.all().delete()
# Load fixture 1. Single JSON file, with two objects. # Load fixture 1. Single JSON file, with two objects.
management.call_command('loaddata', 'fixture1.json', verbosity=0, commit=False) management.call_command('loaddata', 'fixture1.json', verbosity=0, commit=False)
@ -184,12 +183,12 @@ class FixtureLoadingTests(TestCase):
exclude_list=['fixtures.Article', 'fixtures.Book', 'sites']) exclude_list=['fixtures.Article', 'fixtures.Book', 'sites'])
# Excluding a bogus app should throw an error # Excluding a bogus app should throw an error
with self.assertRaisesRegexp(management.CommandError, with six.assertRaisesRegex(self, management.CommandError,
"Unknown app in excludes: foo_app"): "Unknown app in excludes: foo_app"):
self._dumpdata_assert(['fixtures', 'sites'], '', exclude_list=['foo_app']) self._dumpdata_assert(['fixtures', 'sites'], '', exclude_list=['foo_app'])
# Excluding a bogus model should throw an error # Excluding a bogus model should throw an error
with self.assertRaisesRegexp(management.CommandError, with six.assertRaisesRegex(self, management.CommandError,
"Unknown model in excludes: fixtures.FooModel"): "Unknown model in excludes: fixtures.FooModel"):
self._dumpdata_assert(['fixtures', 'sites'], '', exclude_list=['fixtures.FooModel']) self._dumpdata_assert(['fixtures', 'sites'], '', exclude_list=['fixtures.FooModel'])
@ -199,7 +198,7 @@ class FixtureLoadingTests(TestCase):
self.assertQuerysetEqual(Spy.objects.all(), self.assertQuerysetEqual(Spy.objects.all(),
['<Spy: Paul>']) ['<Spy: Paul>'])
# Use the default manager # Use the default manager
self._dumpdata_assert(['fixtures.Spy'],'[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % spy1.pk) self._dumpdata_assert(['fixtures.Spy'], '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % spy1.pk)
# Dump using Django's base manager. Should return all objects, # Dump using Django's base manager. Should return all objects,
# even those normally filtered by the manager # even those normally filtered by the manager
self._dumpdata_assert(['fixtures.Spy'], '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": true}}, {"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % (spy2.pk, spy1.pk), use_base_manager=True) self._dumpdata_assert(['fixtures.Spy'], '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": true}}, {"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % (spy2.pk, spy1.pk), use_base_manager=True)
@ -227,7 +226,7 @@ class FixtureLoadingTests(TestCase):
def test_ambiguous_compressed_fixture(self): def test_ambiguous_compressed_fixture(self):
# The name "fixture5" is ambigous, so loading it will raise an error # The name "fixture5" is ambigous, so loading it will raise an error
with self.assertRaisesRegexp(management.CommandError, with six.assertRaisesRegex(self, management.CommandError,
"Multiple fixtures named 'fixture5'"): "Multiple fixtures named 'fixture5'"):
management.call_command('loaddata', 'fixture5', verbosity=0, commit=False) management.call_command('loaddata', 'fixture5', verbosity=0, commit=False)
@ -251,7 +250,7 @@ class FixtureLoadingTests(TestCase):
# is closed at the end of each test. # is closed at the end of each test.
if connection.vendor == 'mysql': if connection.vendor == 'mysql':
connection.cursor().execute("SET sql_mode = 'TRADITIONAL'") connection.cursor().execute("SET sql_mode = 'TRADITIONAL'")
with self.assertRaisesRegexp(IntegrityError, with six.assertRaisesRegex(self, IntegrityError,
"Could not load fixtures.Article\(pk=1\): .*$"): "Could not load fixtures.Article\(pk=1\): .*$"):
management.call_command('loaddata', 'invalid.json', verbosity=0, commit=False) management.call_command('loaddata', 'invalid.json', verbosity=0, commit=False)
@ -290,10 +289,11 @@ class FixtureLoadingTests(TestCase):
self._dumpdata_assert(['fixtures'], """<?xml version="1.0" encoding="utf-8"?> self._dumpdata_assert(['fixtures'], """<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0"><object pk="1" model="fixtures.category"><field type="CharField" name="title">News Stories</field><field type="TextField" name="description">Latest news stories</field></object><object pk="2" model="fixtures.article"><field type="CharField" name="headline">Poker has no place on ESPN</field><field type="DateTimeField" name="pub_date">2006-06-16T12:00:00</field></object><object pk="3" model="fixtures.article"><field type="CharField" name="headline">Time to reform copyright</field><field type="DateTimeField" name="pub_date">2006-06-16T13:00:00</field></object><object pk="1" model="fixtures.tag"><field type="CharField" name="name">copyright</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">law</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="1" model="fixtures.person"><field type="CharField" name="name">Django Reinhardt</field></object><object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane Grappelli</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">Prince</field></object><object pk="10" model="fixtures.book"><field type="CharField" name="name">Achieving self-awareness of Python programs</field><field to="fixtures.person" name="authors" rel="ManyToManyRel"></field></object></django-objects>""", format='xml', natural_keys=True) <django-objects version="1.0"><object pk="1" model="fixtures.category"><field type="CharField" name="title">News Stories</field><field type="TextField" name="description">Latest news stories</field></object><object pk="2" model="fixtures.article"><field type="CharField" name="headline">Poker has no place on ESPN</field><field type="DateTimeField" name="pub_date">2006-06-16T12:00:00</field></object><object pk="3" model="fixtures.article"><field type="CharField" name="headline">Time to reform copyright</field><field type="DateTimeField" name="pub_date">2006-06-16T13:00:00</field></object><object pk="1" model="fixtures.tag"><field type="CharField" name="name">copyright</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">law</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="1" model="fixtures.person"><field type="CharField" name="name">Django Reinhardt</field></object><object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane Grappelli</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">Prince</field></object><object pk="10" model="fixtures.book"><field type="CharField" name="name">Achieving self-awareness of Python programs</field><field to="fixtures.person" name="authors" rel="ManyToManyRel"></field></object></django-objects>""", format='xml', natural_keys=True)
class FixtureTransactionTests(TransactionTestCase): class FixtureTransactionTests(TransactionTestCase):
def _dumpdata_assert(self, args, output, format='json'): def _dumpdata_assert(self, args, output, format='json'):
new_io = StringIO() new_io = six.StringIO()
management.call_command('dumpdata', *args, **{'format':format, 'stdout':new_io}) management.call_command('dumpdata', *args, **{'format': format, 'stdout': new_io})
command_output = new_io.getvalue().strip() command_output = new_io.getvalue().strip()
self.assertEqual(command_output, output) self.assertEqual(command_output, output)
@ -308,7 +308,7 @@ class FixtureTransactionTests(TransactionTestCase):
# Try to load fixture 2 using format discovery; this will fail # Try to load fixture 2 using format discovery; this will fail
# because there are two fixture2's in the fixtures directory # because there are two fixture2's in the fixtures directory
with self.assertRaisesRegexp(management.CommandError, with six.assertRaisesRegex(self, management.CommandError,
"Multiple fixtures named 'fixture2'"): "Multiple fixtures named 'fixture2'"):
management.call_command('loaddata', 'fixture2', verbosity=0) management.call_command('loaddata', 'fixture2', verbosity=0)

View File

@ -1,6 +1,7 @@
from __future__ import absolute_import from __future__ import absolute_import
from django.test import TestCase from django.test import TestCase
from django.utils import six
from .models import Article, Publication from .models import Article, Publication
@ -52,7 +53,7 @@ class ManyToManyTests(TestCase):
]) ])
# Adding an object of the wrong type raises TypeError # Adding an object of the wrong type raises TypeError
with self.assertRaisesRegexp(TypeError, "'Publication' instance expected, got <Article.*"): with six.assertRaisesRegex(self, TypeError, "'Publication' instance expected, got <Article.*"):
a6.publications.add(a5) a6.publications.add(a5)
# Add a Publication directly via publications.add by using keyword arguments. # Add a Publication directly via publications.add by using keyword arguments.
p4 = a6.publications.create(title='Highlights for Adults') p4 = a6.publications.create(title='Highlights for Adults')

View File

@ -70,7 +70,7 @@ class ManyToOneTests(TestCase):
self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"]) self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"])
# Adding an object of the wrong type raises TypeError. # Adding an object of the wrong type raises TypeError.
with self.assertRaisesRegexp(TypeError, "'Article' instance expected, got <Reporter.*"): with six.assertRaisesRegex(self, TypeError, "'Article' instance expected, got <Reporter.*"):
self.r.article_set.add(self.r2) self.r.article_set.add(self.r2)
self.assertQuerysetEqual(self.r.article_set.all(), self.assertQuerysetEqual(self.r.article_set.all(),
[ [

View File

@ -2,7 +2,7 @@ from __future__ import absolute_import
from datetime import date from datetime import date
from django.db.models.sql.query import InvalidQuery from django.db.models.query_utils import InvalidQuery
from django.test import TestCase from django.test import TestCase
from .models import Author, Book, Coffee, Reviewer, FriendlyAuthor from .models import Author, Book, Coffee, Reviewer, FriendlyAuthor

View File

@ -1,7 +1,8 @@
from __future__ import absolute_import from __future__ import absolute_import
from django.test import TestCase
from django.db.models.signals import pre_save, post_save from django.db.models.signals import pre_save, post_save
from django.test import TestCase
from .models import Person, Employee, ProxyEmployee, Profile, Account from .models import Person, Employee, ProxyEmployee, Profile, Account

View File

@ -3,6 +3,7 @@ from __future__ import unicode_literals
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.db import models from django.db import models
from django.utils import six
from django.utils.unittest import TestCase from django.utils.unittest import TestCase
@ -18,7 +19,7 @@ class ValidationMessagesTest(TestCase):
self._test_validation_messages(f, 'fõo', self._test_validation_messages(f, 'fõo',
["'fõo' value must be an integer."]) ["'fõo' value must be an integer."])
# primary_key must be True. Refs #12467. # primary_key must be True. Refs #12467.
with self.assertRaisesRegexp(AssertionError, with six.assertRaisesRegex(self, AssertionError,
"AutoFields must have primary_key=True."): "AutoFields must have primary_key=True."):
models.AutoField(primary_key=False) models.AutoField(primary_key=False)

View File

@ -9,7 +9,7 @@ from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase, RequestFactory from django.test import TestCase, RequestFactory
from django.test.utils import override_settings from django.test.utils import override_settings, six
from django.utils.encoding import force_text from django.utils.encoding import force_text
from .models import Book, Department, Employee from .models import Book, Department, Employee
@ -18,6 +18,7 @@ from .models import Book, Department, Employee
def select_by(dictlist, key, value): def select_by(dictlist, key, value):
return [x for x in dictlist if x[key] == value][0] return [x for x in dictlist if x[key] == value][0]
class DecadeListFilter(SimpleListFilter): class DecadeListFilter(SimpleListFilter):
def lookups(self, request, model_admin): def lookups(self, request, model_admin):
@ -520,7 +521,7 @@ class ListFiltersTests(TestCase):
""" """
modeladmin = DecadeFilterBookAdminWithoutTitle(Book, site) modeladmin = DecadeFilterBookAdminWithoutTitle(Book, site)
request = self.request_factory.get('/', {}) request = self.request_factory.get('/', {})
self.assertRaisesRegexp(ImproperlyConfigured, six.assertRaisesRegex(self, ImproperlyConfigured,
"The list filter 'DecadeListFilterWithoutTitle' does not specify a 'title'.", "The list filter 'DecadeListFilterWithoutTitle' does not specify a 'title'.",
self.get_changelist, request, Book, modeladmin) self.get_changelist, request, Book, modeladmin)
@ -530,7 +531,7 @@ class ListFiltersTests(TestCase):
""" """
modeladmin = DecadeFilterBookAdminWithoutParameter(Book, site) modeladmin = DecadeFilterBookAdminWithoutParameter(Book, site)
request = self.request_factory.get('/', {}) request = self.request_factory.get('/', {})
self.assertRaisesRegexp(ImproperlyConfigured, six.assertRaisesRegex(self, ImproperlyConfigured,
"The list filter 'DecadeListFilterWithoutParameter' does not specify a 'parameter_name'.", "The list filter 'DecadeListFilterWithoutParameter' does not specify a 'parameter_name'.",
self.get_changelist, request, Book, modeladmin) self.get_changelist, request, Book, modeladmin)

View File

@ -1576,7 +1576,6 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
self.assertOutput(err, "Destination directory '%s' does not exist, please create it first." % testproject_dir) self.assertOutput(err, "Destination directory '%s' does not exist, please create it first." % testproject_dir)
self.assertFalse(os.path.exists(testproject_dir)) self.assertFalse(os.path.exists(testproject_dir))
def test_custom_project_template_with_non_ascii_templates(self): def test_custom_project_template_with_non_ascii_templates(self):
"Ticket 18091: Make sure the startproject management command is able to render templates with non-ASCII content" "Ticket 18091: Make sure the startproject management command is able to render templates with non-ASCII content"
template_path = os.path.join(test_dir, 'admin_scripts', 'custom_templates', 'project_template') template_path = os.path.join(test_dir, 'admin_scripts', 'custom_templates', 'project_template')
@ -1588,5 +1587,6 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
self.assertNoOutput(err) self.assertNoOutput(err)
self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.isdir(testproject_dir))
path = os.path.join(testproject_dir, 'ticket-18091-non-ascii-template.txt') path = os.path.join(testproject_dir, 'ticket-18091-non-ascii-template.txt')
self.assertEqual(codecs.open(path, 'r', 'utf-8').read(), with codecs.open(path, 'r', 'utf-8') as f:
'Some non-ASCII text for testing ticket #18091:\nüäö €\n') self.assertEqual(f.read(),
'Some non-ASCII text for testing ticket #18091:\nüäö €\n')

View File

@ -655,7 +655,7 @@ class ThreadTests(TestCase):
class BackendLoadingTests(TestCase): class BackendLoadingTests(TestCase):
def test_old_style_backends_raise_useful_exception(self): def test_old_style_backends_raise_useful_exception(self):
self.assertRaisesRegexp(ImproperlyConfigured, six.assertRaisesRegex(self, ImproperlyConfigured,
"Try using django.db.backends.sqlite3 instead", "Try using django.db.backends.sqlite3 instead",
load_backend, 'sqlite3') load_backend, 'sqlite3')

View File

@ -15,7 +15,7 @@ import warnings
from django.conf import settings from django.conf import settings
from django.core import management from django.core import management
from django.core.cache import get_cache, DEFAULT_CACHE_ALIAS from django.core.cache import get_cache
from django.core.cache.backends.base import (CacheKeyWarning, from django.core.cache.backends.base import (CacheKeyWarning,
InvalidCacheBackendError) InvalidCacheBackendError)
from django.db import router from django.db import router
@ -25,8 +25,7 @@ from django.middleware.cache import (FetchFromCacheMiddleware,
from django.template import Template from django.template import Template
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from django.test import TestCase, TransactionTestCase, RequestFactory from django.test import TestCase, TransactionTestCase, RequestFactory
from django.test.utils import (get_warnings_state, restore_warnings_state, from django.test.utils import override_settings, six
override_settings)
from django.utils import timezone, translation, unittest from django.utils import timezone, translation, unittest
from django.utils.cache import (patch_vary_headers, get_cache_key, from django.utils.cache import (patch_vary_headers, get_cache_key,
learn_cache_key, patch_cache_control, patch_response_headers) learn_cache_key, patch_cache_control, patch_response_headers)
@ -821,7 +820,7 @@ class DBCacheTests(BaseCacheTests, TransactionTestCase):
self.perform_cull_test(50, 18) self.perform_cull_test(50, 18)
def test_second_call_doesnt_crash(self): def test_second_call_doesnt_crash(self):
with self.assertRaisesRegexp(management.CommandError, with six.assertRaisesRegex(self, management.CommandError,
"Cache table 'test cache table' could not be created"): "Cache table 'test cache table' could not be created"):
management.call_command( management.call_command(
'createcachetable', 'createcachetable',

View File

@ -73,7 +73,7 @@ class GetStorageClassTests(SimpleTestCase):
get_storage_class raises an error if the requested module don't exist. get_storage_class raises an error if the requested module don't exist.
""" """
# Error message may or may not be the fully qualified path. # Error message may or may not be the fully qualified path.
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
('Error importing storage module django.core.files.non_existing_' ('Error importing storage module django.core.files.non_existing_'
'storage: "No module named .*non_existing_storage"'), 'storage: "No module named .*non_existing_storage"'),

View File

@ -100,7 +100,7 @@ class FileUploadTests(TestCase):
try: try:
os.unlink(file1.name) os.unlink(file1.name)
except: except OSError:
pass pass
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -384,15 +384,13 @@ class DirectoryCreationTests(unittest.TestCase):
"""The correct IOError is raised when the upload directory name exists but isn't a directory""" """The correct IOError is raised when the upload directory name exists but isn't a directory"""
# Create a file with the upload directory name # Create a file with the upload directory name
open(UPLOAD_TO, 'wb').close() open(UPLOAD_TO, 'wb').close()
try: with self.assertRaises(IOError) as exc_info:
self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', b'x')) self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', b'x'))
except IOError as err: # The test needs to be done on a specific string as IOError
# The test needs to be done on a specific string as IOError # is raised even without the patch (just not early enough)
# is raised even without the patch (just not early enough) self.assertEqual(exc_info.exception.args[0],
self.assertEqual(err.args[0], "%s exists and is not a directory." % UPLOAD_TO)
"%s exists and is not a directory." % UPLOAD_TO)
except:
self.fail("IOError not raised")
class MultiParserTests(unittest.TestCase): class MultiParserTests(unittest.TestCase):

View File

@ -13,6 +13,7 @@ from django.db.models import signals
from django.test import (TestCase, TransactionTestCase, skipIfDBFeature, from django.test import (TestCase, TransactionTestCase, skipIfDBFeature,
skipUnlessDBFeature) skipUnlessDBFeature)
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils import six
from django.utils.six import PY3, StringIO from django.utils.six import PY3, StringIO
from .models import (Animal, Stuff, Absolute, Parent, Child, Article, Widget, from .models import (Animal, Stuff, Absolute, Parent, Child, Article, Widget,
@ -20,18 +21,15 @@ from .models import (Animal, Stuff, Absolute, Parent, Child, Article, Widget,
ExternalDependency, Thingy) ExternalDependency, Thingy)
pre_save_checks = []
def animal_pre_save_check(signal, sender, instance, **kwargs):
"A signal that is used to check the type of data loaded from fixtures"
pre_save_checks.append(
(
'Count = %s (%s)' % (instance.count, type(instance.count)),
'Weight = %s (%s)' % (instance.weight, type(instance.weight)),
)
)
class TestFixtures(TestCase): class TestFixtures(TestCase):
def animal_pre_save_check(self, signal, sender, instance, **kwargs):
self.pre_save_checks.append(
(
'Count = %s (%s)' % (instance.count, type(instance.count)),
'Weight = %s (%s)' % (instance.weight, type(instance.weight)),
)
)
def test_duplicate_pk(self): def test_duplicate_pk(self):
""" """
This is a regression test for ticket #3790. This is a regression test for ticket #3790.
@ -110,13 +108,12 @@ class TestFixtures(TestCase):
) )
self.assertEqual(Absolute.load_count, 1) self.assertEqual(Absolute.load_count, 1)
def test_unknown_format(self): def test_unknown_format(self):
""" """
Test for ticket #4371 -- Loading data of an unknown format should fail Test for ticket #4371 -- Loading data of an unknown format should fail
Validate that error conditions are caught correctly Validate that error conditions are caught correctly
""" """
with self.assertRaisesRegexp(management.CommandError, with six.assertRaisesRegex(self, management.CommandError,
"Problem installing fixture 'bad_fixture1': " "Problem installing fixture 'bad_fixture1': "
"unkn is not a known serialization format."): "unkn is not a known serialization format."):
management.call_command( management.call_command(
@ -131,7 +128,7 @@ class TestFixtures(TestCase):
""" """
Test that failing serializer import raises the proper error Test that failing serializer import raises the proper error
""" """
with self.assertRaisesRegexp(ImportError, with six.assertRaisesRegex(self, ImportError,
"No module named unexistent.path"): "No module named unexistent.path"):
management.call_command( management.call_command(
'loaddata', 'loaddata',
@ -146,7 +143,7 @@ class TestFixtures(TestCase):
using explicit filename. using explicit filename.
Validate that error conditions are caught correctly Validate that error conditions are caught correctly
""" """
with self.assertRaisesRegexp(management.CommandError, with six.assertRaisesRegex(self, management.CommandError,
"No fixture data found for 'bad_fixture2'. \(File format may be invalid.\)"): "No fixture data found for 'bad_fixture2'. \(File format may be invalid.\)"):
management.call_command( management.call_command(
'loaddata', 'loaddata',
@ -161,7 +158,7 @@ class TestFixtures(TestCase):
without file extension. without file extension.
Validate that error conditions are caught correctly Validate that error conditions are caught correctly
""" """
with self.assertRaisesRegexp(management.CommandError, with six.assertRaisesRegex(self, management.CommandError,
"No fixture data found for 'bad_fixture2'. \(File format may be invalid.\)"): "No fixture data found for 'bad_fixture2'. \(File format may be invalid.\)"):
management.call_command( management.call_command(
'loaddata', 'loaddata',
@ -175,7 +172,7 @@ class TestFixtures(TestCase):
Test for ticket #4371 -- Loading a fixture file with no data returns an error. Test for ticket #4371 -- Loading a fixture file with no data returns an error.
Validate that error conditions are caught correctly Validate that error conditions are caught correctly
""" """
with self.assertRaisesRegexp(management.CommandError, with six.assertRaisesRegex(self, management.CommandError,
"No fixture data found for 'empty'. \(File format may be invalid.\)"): "No fixture data found for 'empty'. \(File format may be invalid.\)"):
management.call_command( management.call_command(
'loaddata', 'loaddata',
@ -188,7 +185,7 @@ class TestFixtures(TestCase):
""" """
(Regression for #9011 - error message is correct) (Regression for #9011 - error message is correct)
""" """
with self.assertRaisesRegexp(management.CommandError, with six.assertRaisesRegex(self, management.CommandError,
"^No fixture data found for 'bad_fixture2'. \(File format may be invalid.\)$"): "^No fixture data found for 'bad_fixture2'. \(File format may be invalid.\)$"):
management.call_command( management.call_command(
'loaddata', 'loaddata',
@ -245,9 +242,8 @@ class TestFixtures(TestCase):
Test for tickets #8298, #9942 - Field values should be coerced into the Test for tickets #8298, #9942 - Field values should be coerced into the
correct type by the deserializer, not as part of the database write. correct type by the deserializer, not as part of the database write.
""" """
global pre_save_checks self.pre_save_checks = []
pre_save_checks = [] signals.pre_save.connect(self.animal_pre_save_check)
signals.pre_save.connect(animal_pre_save_check)
try: try:
management.call_command( management.call_command(
'loaddata', 'loaddata',
@ -256,14 +252,14 @@ class TestFixtures(TestCase):
commit=False, commit=False,
) )
self.assertEqual( self.assertEqual(
pre_save_checks, self.pre_save_checks,
[ [
("Count = 42 (<%s 'int'>)" % ('class' if PY3 else 'type'), ("Count = 42 (<%s 'int'>)" % ('class' if PY3 else 'type'),
"Weight = 1.2 (<%s 'float'>)" % ('class' if PY3 else 'type')) "Weight = 1.2 (<%s 'float'>)" % ('class' if PY3 else 'type'))
] ]
) )
finally: finally:
signals.pre_save.disconnect(animal_pre_save_check) signals.pre_save.disconnect(self.animal_pre_save_check)
def test_dumpdata_uses_default_manager(self): def test_dumpdata_uses_default_manager(self):
""" """
@ -353,7 +349,7 @@ class TestFixtures(TestCase):
""" """
Regression for #3615 - Ensure data with nonexistent child key references raises error Regression for #3615 - Ensure data with nonexistent child key references raises error
""" """
with self.assertRaisesRegexp(IntegrityError, with six.assertRaisesRegex(self, IntegrityError,
"Problem installing fixture"): "Problem installing fixture"):
management.call_command( management.call_command(
'loaddata', 'loaddata',
@ -385,7 +381,7 @@ class TestFixtures(TestCase):
""" """
Regression for #7043 - Error is quickly reported when no fixtures is provided in the command line. Regression for #7043 - Error is quickly reported when no fixtures is provided in the command line.
""" """
with self.assertRaisesRegexp(management.CommandError, with six.assertRaisesRegex(self, management.CommandError,
"No database fixture specified. Please provide the path of " "No database fixture specified. Please provide the path of "
"at least one fixture in the command line."): "at least one fixture in the command line."):
management.call_command( management.call_command(

View File

@ -475,7 +475,7 @@ class FieldsTests(SimpleTestCase):
def test_regexfield_5(self): def test_regexfield_5(self):
f = RegexField('^\d+$', min_length=5, max_length=10) f = RegexField('^\d+$', min_length=5, max_length=10)
self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 5 characters (it has 3).'", f.clean, '123') self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 5 characters (it has 3).'", f.clean, '123')
self.assertRaisesRegexp(ValidationError, "'Ensure this value has at least 5 characters \(it has 3\)\.', u?'Enter a valid value\.'", f.clean, 'abc') six.assertRaisesRegex(self, ValidationError, "'Ensure this value has at least 5 characters \(it has 3\)\.', u?'Enter a valid value\.'", f.clean, 'abc')
self.assertEqual('12345', f.clean('12345')) self.assertEqual('12345', f.clean('12345'))
self.assertEqual('1234567890', f.clean('1234567890')) self.assertEqual('1234567890', f.clean('1234567890'))
self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", f.clean, '12345678901') self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", f.clean, '12345678901')
@ -1036,7 +1036,7 @@ class FieldsTests(SimpleTestCase):
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello')
self.assertRaisesRegexp(ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there']) six.assertRaisesRegex(self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there'])
self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there']) self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there'])
self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30']) self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30'])
@ -1049,7 +1049,7 @@ class FieldsTests(SimpleTestCase):
self.assertEqual(None, f.clean([''])) self.assertEqual(None, f.clean(['']))
self.assertEqual(None, f.clean(['', ''])) self.assertEqual(None, f.clean(['', '']))
self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello')
self.assertRaisesRegexp(ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there']) six.assertRaisesRegex(self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there'])
self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there']) self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there'])
self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30']) self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30'])
self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', '']) self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', ''])

View File

@ -216,13 +216,9 @@ class FormsWidgetTestCase(TestCase):
self.assertHTMLEqual(w.render('greeting', 'hello there'), '<input checked="checked" type="checkbox" name="greeting" value="hello there" />') self.assertHTMLEqual(w.render('greeting', 'hello there'), '<input checked="checked" type="checkbox" name="greeting" value="hello there" />')
self.assertHTMLEqual(w.render('greeting', 'hello & goodbye'), '<input checked="checked" type="checkbox" name="greeting" value="hello &amp; goodbye" />') self.assertHTMLEqual(w.render('greeting', 'hello & goodbye'), '<input checked="checked" type="checkbox" name="greeting" value="hello &amp; goodbye" />')
# A subtlety: If the 'check_test' argument cannot handle a value and raises any # Ticket #17888: calling check_test shouldn't swallow exceptions
# exception during its __call__, then the exception will be swallowed and the box with self.assertRaises(AttributeError):
# will not be checked. In this example, the 'check_test' assumes the value has a w.render('greeting', True)
# startswith() method, which fails for the values True, False and None.
self.assertHTMLEqual(w.render('greeting', True), '<input type="checkbox" name="greeting" />')
self.assertHTMLEqual(w.render('greeting', False), '<input type="checkbox" name="greeting" />')
self.assertHTMLEqual(w.render('greeting', None), '<input type="checkbox" name="greeting" />')
# The CheckboxInput widget will return False if the key is not found in the data # The CheckboxInput widget will return False if the key is not found in the data
# dictionary (because HTML form submission doesn't send any result for unchecked # dictionary (because HTML form submission doesn't send any result for unchecked

View File

@ -17,10 +17,8 @@ class HandlerTests(unittest.TestCase):
# Try running the handler, it will fail in load_middleware # Try running the handler, it will fail in load_middleware
handler = WSGIHandler() handler = WSGIHandler()
self.assertEqual(handler.initLock.locked(), False) self.assertEqual(handler.initLock.locked(), False)
try: with self.assertRaises(Exception):
handler(None, None) handler(None, None)
except:
pass
self.assertEqual(handler.initLock.locked(), False) self.assertEqual(handler.initLock.locked(), False)
# Reset settings # Reset settings
settings.MIDDLEWARE_CLASSES = old_middleware_classes settings.MIDDLEWARE_CLASSES = old_middleware_classes

View File

@ -3,11 +3,12 @@ import os
from django.core.management import call_command, CommandError from django.core.management import call_command, CommandError
from django.test import TestCase from django.test import TestCase
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils import translation from django.utils import translation, six
from django.utils.six import StringIO from django.utils.six import StringIO
test_dir = os.path.abspath(os.path.dirname(__file__)) test_dir = os.path.abspath(os.path.dirname(__file__))
class MessageCompilationTests(TestCase): class MessageCompilationTests(TestCase):
def setUp(self): def setUp(self):
@ -19,12 +20,12 @@ class MessageCompilationTests(TestCase):
class PoFileTests(MessageCompilationTests): class PoFileTests(MessageCompilationTests):
LOCALE='es_AR' LOCALE = 'es_AR'
MO_FILE='locale/%s/LC_MESSAGES/django.mo' % LOCALE MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' % LOCALE
def test_bom_rejection(self): def test_bom_rejection(self):
os.chdir(test_dir) os.chdir(test_dir)
with self.assertRaisesRegexp(CommandError, with six.assertRaisesRegex(self, CommandError,
"file has a BOM \(Byte Order Mark\)"): "file has a BOM \(Byte Order Mark\)"):
call_command('compilemessages', locale=self.LOCALE, stderr=StringIO()) call_command('compilemessages', locale=self.LOCALE, stderr=StringIO())
self.assertFalse(os.path.exists(self.MO_FILE)) self.assertFalse(os.path.exists(self.MO_FILE))

View File

@ -123,7 +123,7 @@ class InlineFormsetFactoryTest(TestCase):
Child has two ForeignKeys to Parent, so if we don't specify which one Child has two ForeignKeys to Parent, so if we don't specify which one
to use for the inline formset, we should get an exception. to use for the inline formset, we should get an exception.
""" """
self.assertRaisesRegexp(Exception, six.assertRaisesRegex(self, Exception,
"<class 'regressiontests.inline_formsets.models.Child'> has more than 1 ForeignKey to <class 'regressiontests.inline_formsets.models.Parent'>", "<class 'regressiontests.inline_formsets.models.Child'> has more than 1 ForeignKey to <class 'regressiontests.inline_formsets.models.Parent'>",
inlineformset_factory, Parent, Child inlineformset_factory, Parent, Child
) )
@ -143,7 +143,7 @@ class InlineFormsetFactoryTest(TestCase):
If the field specified in fk_name is not a ForeignKey, we should get an If the field specified in fk_name is not a ForeignKey, we should get an
exception. exception.
""" """
self.assertRaisesRegexp(Exception, six.assertRaisesRegex(self, Exception,
"<class 'regressiontests.inline_formsets.models.Child'> has no field named 'test'", "<class 'regressiontests.inline_formsets.models.Child'> has no field named 'test'",
inlineformset_factory, Parent, Child, fk_name='test' inlineformset_factory, Parent, Child, fk_name='test'
) )

View File

@ -2,29 +2,31 @@
from django.contrib.localflavor.tr import forms as trforms from django.contrib.localflavor.tr import forms as trforms
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.utils import six
from django.utils.unittest import TestCase from django.utils.unittest import TestCase
class TRLocalFlavorTests(TestCase): class TRLocalFlavorTests(TestCase):
def test_TRPostalCodeField(self): def test_TRPostalCodeField(self):
f = trforms.TRPostalCodeField() f = trforms.TRPostalCodeField()
self.assertEqual(f.clean("06531"), "06531") self.assertEqual(f.clean("06531"), "06531")
self.assertEqual(f.clean("12345"), "12345") self.assertEqual(f.clean("12345"), "12345")
self.assertRaisesRegexp(ValidationError, six.assertRaisesRegex(self, ValidationError,
"Enter a postal code in the format XXXXX.", "Enter a postal code in the format XXXXX.",
f.clean, "a1234") f.clean, "a1234")
self.assertRaisesRegexp(ValidationError, six.assertRaisesRegex(self, ValidationError,
"Enter a postal code in the format XXXXX.", "Enter a postal code in the format XXXXX.",
f.clean, "1234") f.clean, "1234")
self.assertRaisesRegexp(ValidationError, six.assertRaisesRegex(self, ValidationError,
"Enter a postal code in the format XXXXX.", "Enter a postal code in the format XXXXX.",
f.clean, "82123") f.clean, "82123")
self.assertRaisesRegexp(ValidationError, six.assertRaisesRegex(self, ValidationError,
"Enter a postal code in the format XXXXX.", "Enter a postal code in the format XXXXX.",
f.clean, "00123") f.clean, "00123")
self.assertRaisesRegexp(ValidationError, six.assertRaisesRegex(self, ValidationError,
"Enter a postal code in the format XXXXX.", "Enter a postal code in the format XXXXX.",
f.clean, "123456") f.clean, "123456")
self.assertRaisesRegexp(ValidationError, six.assertRaisesRegex(self, ValidationError,
"Enter a postal code in the format XXXXX.", "Enter a postal code in the format XXXXX.",
f.clean, "12 34") f.clean, "12 34")
self.assertRaises(ValidationError, f.clean, None) self.assertRaises(ValidationError, f.clean, None)
@ -40,34 +42,34 @@ class TRLocalFlavorTests(TestCase):
self.assertEqual(f.clean("+90 312 455 4567"), "3124554567") self.assertEqual(f.clean("+90 312 455 4567"), "3124554567")
self.assertEqual(f.clean("+90 312 455 45 67"), "3124554567") self.assertEqual(f.clean("+90 312 455 45 67"), "3124554567")
self.assertEqual(f.clean("+90 (312) 4554567"), "3124554567") self.assertEqual(f.clean("+90 (312) 4554567"), "3124554567")
self.assertRaisesRegexp(ValidationError, six.assertRaisesRegex(self, ValidationError,
'Phone numbers must be in 0XXX XXX XXXX format.', 'Phone numbers must be in 0XXX XXX XXXX format.',
f.clean, "1234 233 1234") f.clean, "1234 233 1234")
self.assertRaisesRegexp(ValidationError, six.assertRaisesRegex(self, ValidationError,
'Phone numbers must be in 0XXX XXX XXXX format.', 'Phone numbers must be in 0XXX XXX XXXX format.',
f.clean, "0312 233 12345") f.clean, "0312 233 12345")
self.assertRaisesRegexp(ValidationError, six.assertRaisesRegex(self, ValidationError,
'Phone numbers must be in 0XXX XXX XXXX format.', 'Phone numbers must be in 0XXX XXX XXXX format.',
f.clean, "0312 233 123") f.clean, "0312 233 123")
self.assertRaisesRegexp(ValidationError, six.assertRaisesRegex(self, ValidationError,
'Phone numbers must be in 0XXX XXX XXXX format.', 'Phone numbers must be in 0XXX XXX XXXX format.',
f.clean, "0312 233 xxxx") f.clean, "0312 233 xxxx")
def test_TRIdentificationNumberField(self): def test_TRIdentificationNumberField(self):
f = trforms.TRIdentificationNumberField() f = trforms.TRIdentificationNumberField()
self.assertEqual(f.clean("10000000146"), "10000000146") self.assertEqual(f.clean("10000000146"), "10000000146")
self.assertRaisesRegexp(ValidationError, six.assertRaisesRegex(self, ValidationError,
'Enter a valid Turkish Identification number.', 'Enter a valid Turkish Identification number.',
f.clean, "10000000136") f.clean, "10000000136")
self.assertRaisesRegexp(ValidationError, six.assertRaisesRegex(self, ValidationError,
'Enter a valid Turkish Identification number.', 'Enter a valid Turkish Identification number.',
f.clean, "10000000147") f.clean, "10000000147")
self.assertRaisesRegexp(ValidationError, six.assertRaisesRegex(self, ValidationError,
'Turkish Identification number must be 11 digits.', 'Turkish Identification number must be 11 digits.',
f.clean, "123456789") f.clean, "123456789")
self.assertRaisesRegexp(ValidationError, six.assertRaisesRegex(self, ValidationError,
'Enter a valid Turkish Identification number.', 'Enter a valid Turkish Identification number.',
f.clean, "1000000014x") f.clean, "1000000014x")
self.assertRaisesRegexp(ValidationError, six.assertRaisesRegex(self, ValidationError,
'Enter a valid Turkish Identification number.', 'Enter a valid Turkish Identification number.',
f.clean, "x0000000146") f.clean, "x0000000146")

View File

@ -2,6 +2,7 @@ from __future__ import absolute_import
from django.core.exceptions import FieldError from django.core.exceptions import FieldError
from django.test import TestCase from django.test import TestCase
from django.utils import six
from .models import (SelfRefer, Tag, TagCollection, Entry, SelfReferChild, from .models import (SelfRefer, Tag, TagCollection, Entry, SelfReferChild,
SelfReferChildSibling, Worksheet) SelfReferChildSibling, Worksheet)
@ -35,7 +36,7 @@ class M2MRegressionTests(TestCase):
# The secret internal related names for self-referential many-to-many # The secret internal related names for self-referential many-to-many
# fields shouldn't appear in the list when an error is made. # fields shouldn't appear in the list when an error is made.
self.assertRaisesRegexp(FieldError, six.assertRaisesRegex(self, FieldError,
"Choices are: id, name, references, related, selfreferchild, selfreferchildsibling$", "Choices are: id, name, references, related, selfreferchild, selfreferchildsibling$",
lambda: SelfRefer.objects.filter(porcupine='fred') lambda: SelfRefer.objects.filter(porcupine='fred')
) )
@ -70,7 +71,7 @@ class M2MRegressionTests(TestCase):
t2 = Tag.objects.create(name='t2') t2 = Tag.objects.create(name='t2')
c1 = TagCollection.objects.create(name='c1') c1 = TagCollection.objects.create(name='c1')
c1.tags = [t1,t2] c1.tags = [t1, t2]
c1 = TagCollection.objects.get(name='c1') c1 = TagCollection.objects.get(name='c1')
self.assertQuerysetEqual(c1.tags.all(), ["<Tag: t1>", "<Tag: t2>"]) self.assertQuerysetEqual(c1.tags.all(), ["<Tag: t1>", "<Tag: t2>"])

View File

@ -2,8 +2,9 @@ from __future__ import absolute_import
from django.db import models from django.db import models
from django.test import TestCase from django.test import TestCase
from django.utils import six
from .models import First, Second, Third, Parent, Child, Category, Record, Relation from .models import First, Third, Parent, Child, Category, Record, Relation
class ManyToOneRegressionTests(TestCase): class ManyToOneRegressionTests(TestCase):
@ -59,7 +60,7 @@ class ManyToOneRegressionTests(TestCase):
self.assertRaises(ValueError, Child.objects.create, name='xyzzy', parent=None) self.assertRaises(ValueError, Child.objects.create, name='xyzzy', parent=None)
# Trying to assign to unbound attribute raises AttributeError # Trying to assign to unbound attribute raises AttributeError
self.assertRaisesRegexp(AttributeError, "must be accessed via instance", six.assertRaisesRegex(self, AttributeError, "must be accessed via instance",
Child.parent.__set__, None, p) Child.parent.__set__, None, p)
# Creation using keyword argument should cache the related object. # Creation using keyword argument should cache the related object.

View File

@ -16,7 +16,7 @@ from django.forms.models import BaseModelFormSet
from django.forms.widgets import Select from django.forms.widgets import Select
from django.test import TestCase from django.test import TestCase
from django.test.utils import str_prefix from django.test.utils import str_prefix
from django.utils import unittest from django.utils import unittest, six
from .models import Band, Concert, ValidationTestModel, ValidationTestInlineModel from .models import Band, Concert, ValidationTestModel, ValidationTestInlineModel
@ -506,7 +506,7 @@ class ValidationTests(unittest.TestCase):
site = AdminSite() site = AdminSite()
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.raw_id_fields' must be a list or tuple.", "'ValidationTestModelAdmin.raw_id_fields' must be a list or tuple.",
site.register, site.register,
@ -524,7 +524,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
raw_id_fields = 10 raw_id_fields = 10
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.raw_id_fields' must be a list or tuple.", "'ValidationTestModelAdmin.raw_id_fields' must be a list or tuple.",
validate, validate,
@ -535,7 +535,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
raw_id_fields = ('non_existent_field',) raw_id_fields = ('non_existent_field',)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.raw_id_fields' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.", "'ValidationTestModelAdmin.raw_id_fields' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.",
validate, validate,
@ -546,7 +546,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
raw_id_fields = ('name',) raw_id_fields = ('name',)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.raw_id_fields\[0\]', 'name' must be either a ForeignKey or ManyToManyField.", "'ValidationTestModelAdmin.raw_id_fields\[0\]', 'name' must be either a ForeignKey or ManyToManyField.",
validate, validate,
@ -564,7 +564,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
fieldsets = 10 fieldsets = 10
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.fieldsets' must be a list or tuple.", "'ValidationTestModelAdmin.fieldsets' must be a list or tuple.",
validate, validate,
@ -575,7 +575,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
fieldsets = ({},) fieldsets = ({},)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.fieldsets\[0\]' must be a list or tuple.", "'ValidationTestModelAdmin.fieldsets\[0\]' must be a list or tuple.",
validate, validate,
@ -586,7 +586,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
fieldsets = ((),) fieldsets = ((),)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.fieldsets\[0\]' does not have exactly two elements.", "'ValidationTestModelAdmin.fieldsets\[0\]' does not have exactly two elements.",
validate, validate,
@ -597,7 +597,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
fieldsets = (("General", ()),) fieldsets = (("General", ()),)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.fieldsets\[0\]\[1\]' must be a dictionary.", "'ValidationTestModelAdmin.fieldsets\[0\]\[1\]' must be a dictionary.",
validate, validate,
@ -608,7 +608,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
fieldsets = (("General", {}),) fieldsets = (("General", {}),)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'fields' key is required in ValidationTestModelAdmin.fieldsets\[0\]\[1\] field options dict.", "'fields' key is required in ValidationTestModelAdmin.fieldsets\[0\]\[1\] field options dict.",
validate, validate,
@ -619,7 +619,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
fieldsets = (("General", {"fields": ("non_existent_field",)}),) fieldsets = (("General", {"fields": ("non_existent_field",)}),)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.fieldsets\[0\]\[1\]\['fields'\]' refers to field 'non_existent_field' that is missing from the form.", "'ValidationTestModelAdmin.fieldsets\[0\]\[1\]\['fields'\]' refers to field 'non_existent_field' that is missing from the form.",
validate, validate,
@ -636,7 +636,7 @@ class ValidationTests(unittest.TestCase):
fieldsets = (("General", {"fields": ("name",)}),) fieldsets = (("General", {"fields": ("name",)}),)
fields = ["name",] fields = ["name",]
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"Both fieldsets and fields are specified in ValidationTestModelAdmin.", "Both fieldsets and fields are specified in ValidationTestModelAdmin.",
validate, validate,
@ -647,7 +647,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
fieldsets = [(None, {'fields': ['name', 'name']})] fieldsets = [(None, {'fields': ['name', 'name']})]
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"There are duplicate field\(s\) in ValidationTestModelAdmin.fieldsets", "There are duplicate field\(s\) in ValidationTestModelAdmin.fieldsets",
validate, validate,
@ -658,7 +658,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
fields = ["name", "name"] fields = ["name", "name"]
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"There are duplicate field\(s\) in ValidationTestModelAdmin.fields", "There are duplicate field\(s\) in ValidationTestModelAdmin.fields",
validate, validate,
@ -674,7 +674,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
form = FakeForm form = FakeForm
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"ValidationTestModelAdmin.form does not inherit from BaseModelForm.", "ValidationTestModelAdmin.form does not inherit from BaseModelForm.",
validate, validate,
@ -692,7 +692,7 @@ class ValidationTests(unittest.TestCase):
}), }),
) )
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'BandAdmin.fieldsets\[0\]\[1\]\['fields'\]' refers to field 'non_existent_field' that is missing from the form.", "'BandAdmin.fieldsets\[0\]\[1\]\['fields'\]' refers to field 'non_existent_field' that is missing from the form.",
validate, validate,
@ -722,7 +722,7 @@ class ValidationTests(unittest.TestCase):
}), }),
) )
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'BandAdmin.fieldsets\[0]\[1\]\['fields'\]' refers to field 'non_existent_field' that is missing from the form.", "'BandAdmin.fieldsets\[0]\[1\]\['fields'\]' refers to field 'non_existent_field' that is missing from the form.",
validate, validate,
@ -752,7 +752,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
filter_vertical = 10 filter_vertical = 10
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.filter_vertical' must be a list or tuple.", "'ValidationTestModelAdmin.filter_vertical' must be a list or tuple.",
validate, validate,
@ -763,7 +763,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
filter_vertical = ("non_existent_field",) filter_vertical = ("non_existent_field",)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.filter_vertical' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.", "'ValidationTestModelAdmin.filter_vertical' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.",
validate, validate,
@ -774,7 +774,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
filter_vertical = ("name",) filter_vertical = ("name",)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.filter_vertical\[0\]' must be a ManyToManyField.", "'ValidationTestModelAdmin.filter_vertical\[0\]' must be a ManyToManyField.",
validate, validate,
@ -792,7 +792,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
filter_horizontal = 10 filter_horizontal = 10
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.filter_horizontal' must be a list or tuple.", "'ValidationTestModelAdmin.filter_horizontal' must be a list or tuple.",
validate, validate,
@ -803,7 +803,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
filter_horizontal = ("non_existent_field",) filter_horizontal = ("non_existent_field",)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.filter_horizontal' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.", "'ValidationTestModelAdmin.filter_horizontal' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.",
validate, validate,
@ -814,7 +814,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
filter_horizontal = ("name",) filter_horizontal = ("name",)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.filter_horizontal\[0\]' must be a ManyToManyField.", "'ValidationTestModelAdmin.filter_horizontal\[0\]' must be a ManyToManyField.",
validate, validate,
@ -832,7 +832,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
radio_fields = () radio_fields = ()
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.radio_fields' must be a dictionary.", "'ValidationTestModelAdmin.radio_fields' must be a dictionary.",
validate, validate,
@ -843,7 +843,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
radio_fields = {"non_existent_field": None} radio_fields = {"non_existent_field": None}
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.radio_fields' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.", "'ValidationTestModelAdmin.radio_fields' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.",
validate, validate,
@ -854,7 +854,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
radio_fields = {"name": None} radio_fields = {"name": None}
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.radio_fields\['name'\]' is neither an instance of ForeignKey nor does have choices set.", "'ValidationTestModelAdmin.radio_fields\['name'\]' is neither an instance of ForeignKey nor does have choices set.",
validate, validate,
@ -865,7 +865,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
radio_fields = {"state": None} radio_fields = {"state": None}
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.radio_fields\['state'\]' is neither admin.HORIZONTAL nor admin.VERTICAL.", "'ValidationTestModelAdmin.radio_fields\['state'\]' is neither admin.HORIZONTAL nor admin.VERTICAL.",
validate, validate,
@ -883,7 +883,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
prepopulated_fields = () prepopulated_fields = ()
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.prepopulated_fields' must be a dictionary.", "'ValidationTestModelAdmin.prepopulated_fields' must be a dictionary.",
validate, validate,
@ -894,7 +894,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
prepopulated_fields = {"non_existent_field": None} prepopulated_fields = {"non_existent_field": None}
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.prepopulated_fields' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.", "'ValidationTestModelAdmin.prepopulated_fields' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.",
validate, validate,
@ -905,7 +905,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
prepopulated_fields = {"slug": ("non_existent_field",)} prepopulated_fields = {"slug": ("non_existent_field",)}
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.prepopulated_fields\['slug'\]\[0\]' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.", "'ValidationTestModelAdmin.prepopulated_fields\['slug'\]\[0\]' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.",
validate, validate,
@ -916,7 +916,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
prepopulated_fields = {"users": ("name",)} prepopulated_fields = {"users": ("name",)}
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.prepopulated_fields\['users'\]' is either a DateTimeField, ForeignKey or ManyToManyField. This isn't allowed.", "'ValidationTestModelAdmin.prepopulated_fields\['users'\]' is either a DateTimeField, ForeignKey or ManyToManyField. This isn't allowed.",
validate, validate,
@ -934,7 +934,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
list_display = 10 list_display = 10
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.list_display' must be a list or tuple.", "'ValidationTestModelAdmin.list_display' must be a list or tuple.",
validate, validate,
@ -945,7 +945,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
list_display = ('non_existent_field',) list_display = ('non_existent_field',)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
str_prefix("ValidationTestModelAdmin.list_display\[0\], %(_)s'non_existent_field' is not a callable or an attribute of 'ValidationTestModelAdmin' or found in the model 'ValidationTestModel'."), str_prefix("ValidationTestModelAdmin.list_display\[0\], %(_)s'non_existent_field' is not a callable or an attribute of 'ValidationTestModelAdmin' or found in the model 'ValidationTestModel'."),
validate, validate,
@ -956,7 +956,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
list_display = ('users',) list_display = ('users',)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.list_display\[0\]', 'users' is a ManyToManyField which is not supported.", "'ValidationTestModelAdmin.list_display\[0\]', 'users' is a ManyToManyField which is not supported.",
validate, validate,
@ -979,7 +979,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
list_display_links = 10 list_display_links = 10
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.list_display_links' must be a list or tuple.", "'ValidationTestModelAdmin.list_display_links' must be a list or tuple.",
validate, validate,
@ -990,7 +990,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
list_display_links = ('non_existent_field',) list_display_links = ('non_existent_field',)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.list_display_links\[0\]' refers to 'non_existent_field' which is not defined in 'list_display'.", "'ValidationTestModelAdmin.list_display_links\[0\]' refers to 'non_existent_field' which is not defined in 'list_display'.",
validate, validate,
@ -1001,7 +1001,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
list_display_links = ('name',) list_display_links = ('name',)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.list_display_links\[0\]' refers to 'name' which is not defined in 'list_display'.", "'ValidationTestModelAdmin.list_display_links\[0\]' refers to 'name' which is not defined in 'list_display'.",
validate, validate,
@ -1025,7 +1025,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
list_filter = 10 list_filter = 10
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.list_filter' must be a list or tuple.", "'ValidationTestModelAdmin.list_filter' must be a list or tuple.",
validate, validate,
@ -1036,7 +1036,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
list_filter = ('non_existent_field',) list_filter = ('non_existent_field',)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.list_filter\[0\]' refers to 'non_existent_field' which does not refer to a Field.", "'ValidationTestModelAdmin.list_filter\[0\]' refers to 'non_existent_field' which does not refer to a Field.",
validate, validate,
@ -1050,7 +1050,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
list_filter = (RandomClass,) list_filter = (RandomClass,)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.list_filter\[0\]' is 'RandomClass' which is not a descendant of ListFilter.", "'ValidationTestModelAdmin.list_filter\[0\]' is 'RandomClass' which is not a descendant of ListFilter.",
validate, validate,
@ -1061,7 +1061,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
list_filter = (('is_active', RandomClass),) list_filter = (('is_active', RandomClass),)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.list_filter\[0\]\[1\]' is 'RandomClass' which is not of type FieldListFilter.", "'ValidationTestModelAdmin.list_filter\[0\]\[1\]' is 'RandomClass' which is not of type FieldListFilter.",
validate, validate,
@ -1080,7 +1080,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
list_filter = (('is_active', AwesomeFilter),) list_filter = (('is_active', AwesomeFilter),)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.list_filter\[0\]\[1\]' is 'AwesomeFilter' which is not of type FieldListFilter.", "'ValidationTestModelAdmin.list_filter\[0\]\[1\]' is 'AwesomeFilter' which is not of type FieldListFilter.",
validate, validate,
@ -1091,7 +1091,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
list_filter = (BooleanFieldListFilter,) list_filter = (BooleanFieldListFilter,)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.list_filter\[0\]' is 'BooleanFieldListFilter' which is of type FieldListFilter but is not associated with a field name.", "'ValidationTestModelAdmin.list_filter\[0\]' is 'BooleanFieldListFilter' which is of type FieldListFilter but is not associated with a field name.",
validate, validate,
@ -1111,7 +1111,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
list_per_page = 'hello' list_per_page = 'hello'
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.list_per_page' should be a integer.", "'ValidationTestModelAdmin.list_per_page' should be a integer.",
validate, validate,
@ -1129,7 +1129,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
list_max_show_all = 'hello' list_max_show_all = 'hello'
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.list_max_show_all' should be an integer.", "'ValidationTestModelAdmin.list_max_show_all' should be an integer.",
validate, validate,
@ -1147,7 +1147,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
search_fields = 10 search_fields = 10
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.search_fields' must be a list or tuple.", "'ValidationTestModelAdmin.search_fields' must be a list or tuple.",
validate, validate,
@ -1160,7 +1160,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
date_hierarchy = 'non_existent_field' date_hierarchy = 'non_existent_field'
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.date_hierarchy' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.", "'ValidationTestModelAdmin.date_hierarchy' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.",
validate, validate,
@ -1171,7 +1171,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
date_hierarchy = 'name' date_hierarchy = 'name'
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.date_hierarchy is neither an instance of DateField nor DateTimeField.", "'ValidationTestModelAdmin.date_hierarchy is neither an instance of DateField nor DateTimeField.",
validate, validate,
@ -1189,7 +1189,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
ordering = 10 ordering = 10
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.ordering' must be a list or tuple.", "'ValidationTestModelAdmin.ordering' must be a list or tuple.",
validate, validate,
@ -1200,7 +1200,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
ordering = ('non_existent_field',) ordering = ('non_existent_field',)
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.ordering\[0\]' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.", "'ValidationTestModelAdmin.ordering\[0\]' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.",
validate, validate,
@ -1211,7 +1211,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
ordering = ('?', 'name') ordering = ('?', 'name')
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.ordering' has the random ordering marker '\?', but contains other fields as well. Please either remove '\?' or the other fields.", "'ValidationTestModelAdmin.ordering' has the random ordering marker '\?', but contains other fields as well. Please either remove '\?' or the other fields.",
validate, validate,
@ -1239,7 +1239,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
list_select_related = 1 list_select_related = 1
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.list_select_related' should be a boolean.", "'ValidationTestModelAdmin.list_select_related' should be a boolean.",
validate, validate,
@ -1257,7 +1257,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
save_as = 1 save_as = 1
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.save_as' should be a boolean.", "'ValidationTestModelAdmin.save_as' should be a boolean.",
validate, validate,
@ -1275,7 +1275,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
save_on_top = 1 save_on_top = 1
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.save_on_top' should be a boolean.", "'ValidationTestModelAdmin.save_on_top' should be a boolean.",
validate, validate,
@ -1293,7 +1293,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
inlines = 10 inlines = 10
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.inlines' must be a list or tuple.", "'ValidationTestModelAdmin.inlines' must be a list or tuple.",
validate, validate,
@ -1307,7 +1307,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
inlines = [ValidationTestInline] inlines = [ValidationTestInline]
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.inlines\[0\]' does not inherit from BaseModelAdmin.", "'ValidationTestModelAdmin.inlines\[0\]' does not inherit from BaseModelAdmin.",
validate, validate,
@ -1321,7 +1321,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
inlines = [ValidationTestInline] inlines = [ValidationTestInline]
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'model' is a required attribute of 'ValidationTestModelAdmin.inlines\[0\]'.", "'model' is a required attribute of 'ValidationTestModelAdmin.inlines\[0\]'.",
validate, validate,
@ -1338,7 +1338,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
inlines = [ValidationTestInline] inlines = [ValidationTestInline]
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestModelAdmin.inlines\[0\].model' does not inherit from models.Model.", "'ValidationTestModelAdmin.inlines\[0\].model' does not inherit from models.Model.",
validate, validate,
@ -1363,7 +1363,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
inlines = [ValidationTestInline] inlines = [ValidationTestInline]
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestInline.fields' must be a list or tuple.", "'ValidationTestInline.fields' must be a list or tuple.",
validate, validate,
@ -1378,7 +1378,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
inlines = [ValidationTestInline] inlines = [ValidationTestInline]
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestInline.fields' refers to field 'non_existent_field' that is missing from the form.", "'ValidationTestInline.fields' refers to field 'non_existent_field' that is missing from the form.",
validate, validate,
@ -1395,7 +1395,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
inlines = [ValidationTestInline] inlines = [ValidationTestInline]
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestInline.fk_name' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestInlineModel'.", "'ValidationTestInline.fk_name' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestInlineModel'.",
validate, validate,
@ -1421,7 +1421,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
inlines = [ValidationTestInline] inlines = [ValidationTestInline]
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestInline.extra' should be a integer.", "'ValidationTestInline.extra' should be a integer.",
validate, validate,
@ -1447,7 +1447,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
inlines = [ValidationTestInline] inlines = [ValidationTestInline]
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestInline.max_num' should be an integer or None \(default\).", "'ValidationTestInline.max_num' should be an integer or None \(default\).",
validate, validate,
@ -1476,7 +1476,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
inlines = [ValidationTestInline] inlines = [ValidationTestInline]
self.assertRaisesRegexp( six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
"'ValidationTestInline.formset' does not inherit from BaseModelFormSet.", "'ValidationTestInline.formset' does not inherit from BaseModelFormSet.",
validate, validate,

View File

@ -1677,10 +1677,7 @@ class CloneTests(TestCase):
list(n_list) list(n_list)
# Use the note queryset in a query, and evalute # Use the note queryset in a query, and evalute
# that query in a way that involves cloning. # that query in a way that involves cloning.
try: self.assertEqual(ExtraInfo.objects.filter(note__in=n_list)[0].info, 'good')
self.assertEqual(ExtraInfo.objects.filter(note__in=n_list)[0].info, 'good')
except:
self.fail('Query should be clonable')
class EmptyQuerySetTests(TestCase): class EmptyQuerySetTests(TestCase):

View File

@ -71,16 +71,18 @@ class SettingGetter(object):
def __init__(self): def __init__(self):
self.test = getattr(settings, 'TEST', 'undefined') self.test = getattr(settings, 'TEST', 'undefined')
testvalue = None
def signal_callback(sender, setting, value, **kwargs):
if setting == 'TEST':
global testvalue
testvalue = value
signals.setting_changed.connect(signal_callback)
class SettingsTests(TestCase): class SettingsTests(TestCase):
def setUp(self):
self.testvalue = None
signals.setting_changed.connect(self.signal_callback)
def tearDown(self):
signals.setting_changed.disconnect(self.signal_callback)
def signal_callback(self, sender, setting, value, **kwargs):
if setting == 'TEST':
self.testvalue = value
def test_override(self): def test_override(self):
settings.TEST = 'test' settings.TEST = 'test'
@ -128,12 +130,12 @@ class SettingsTests(TestCase):
def test_signal_callback_context_manager(self): def test_signal_callback_context_manager(self):
self.assertRaises(AttributeError, getattr, settings, 'TEST') self.assertRaises(AttributeError, getattr, settings, 'TEST')
with self.settings(TEST='override'): with self.settings(TEST='override'):
self.assertEqual(testvalue, 'override') self.assertEqual(self.testvalue, 'override')
self.assertEqual(testvalue, None) self.assertEqual(self.testvalue, None)
@override_settings(TEST='override') @override_settings(TEST='override')
def test_signal_callback_decorator(self): def test_signal_callback_decorator(self):
self.assertEqual(testvalue, 'override') self.assertEqual(self.testvalue, 'override')
# #
# Regression tests for #10130: deleting settings. # Regression tests for #10130: deleting settings.

View File

@ -6,31 +6,6 @@ from django.test import TestCase
from .models import Author, Book from .models import Author, Book
signal_output = []
def pre_save_test(signal, sender, instance, **kwargs):
signal_output.append('pre_save signal, %s' % instance)
if kwargs.get('raw'):
signal_output.append('Is raw')
def post_save_test(signal, sender, instance, **kwargs):
signal_output.append('post_save signal, %s' % instance)
if 'created' in kwargs:
if kwargs['created']:
signal_output.append('Is created')
else:
signal_output.append('Is updated')
if kwargs.get('raw'):
signal_output.append('Is raw')
def pre_delete_test(signal, sender, instance, **kwargs):
signal_output.append('pre_save signal, %s' % instance)
signal_output.append('instance.id is not None: %s' % (instance.id != None))
def post_delete_test(signal, sender, instance, **kwargs):
signal_output.append('post_delete signal, %s' % instance)
signal_output.append('instance.id is not None: %s' % (instance.id != None))
class SignalsRegressTests(TestCase): class SignalsRegressTests(TestCase):
""" """
Testing signals before/after saving and deleting. Testing signals before/after saving and deleting.
@ -38,12 +13,35 @@ class SignalsRegressTests(TestCase):
def get_signal_output(self, fn, *args, **kwargs): def get_signal_output(self, fn, *args, **kwargs):
# Flush any existing signal output # Flush any existing signal output
global signal_output self.signal_output = []
signal_output = []
fn(*args, **kwargs) fn(*args, **kwargs)
return signal_output return self.signal_output
def pre_save_test(self, signal, sender, instance, **kwargs):
self.signal_output.append('pre_save signal, %s' % instance)
if kwargs.get('raw'):
self.signal_output.append('Is raw')
def post_save_test(self, signal, sender, instance, **kwargs):
self.signal_output.append('post_save signal, %s' % instance)
if 'created' in kwargs:
if kwargs['created']:
self.signal_output.append('Is created')
else:
self.signal_output.append('Is updated')
if kwargs.get('raw'):
self.signal_output.append('Is raw')
def pre_delete_test(self, signal, sender, instance, **kwargs):
self.signal_output.append('pre_save signal, %s' % instance)
self.signal_output.append('instance.id is not None: %s' % (instance.id != None))
def post_delete_test(self, signal, sender, instance, **kwargs):
self.signal_output.append('post_delete signal, %s' % instance)
self.signal_output.append('instance.id is not None: %s' % (instance.id != None))
def setUp(self): def setUp(self):
self.signal_output = []
# Save up the number of connected signals so that we can check at the end # Save up the number of connected signals so that we can check at the end
# that all the signals we register get properly unregistered (#9989) # that all the signals we register get properly unregistered (#9989)
self.pre_signals = (len(models.signals.pre_save.receivers), self.pre_signals = (len(models.signals.pre_save.receivers),
@ -51,16 +49,16 @@ class SignalsRegressTests(TestCase):
len(models.signals.pre_delete.receivers), len(models.signals.pre_delete.receivers),
len(models.signals.post_delete.receivers)) len(models.signals.post_delete.receivers))
models.signals.pre_save.connect(pre_save_test) models.signals.pre_save.connect(self.pre_save_test)
models.signals.post_save.connect(post_save_test) models.signals.post_save.connect(self.post_save_test)
models.signals.pre_delete.connect(pre_delete_test) models.signals.pre_delete.connect(self.pre_delete_test)
models.signals.post_delete.connect(post_delete_test) models.signals.post_delete.connect(self.post_delete_test)
def tearDown(self): def tearDown(self):
models.signals.post_delete.disconnect(post_delete_test) models.signals.post_delete.disconnect(self.post_delete_test)
models.signals.pre_delete.disconnect(pre_delete_test) models.signals.pre_delete.disconnect(self.pre_delete_test)
models.signals.post_save.disconnect(post_save_test) models.signals.post_save.disconnect(self.post_save_test)
models.signals.pre_save.disconnect(pre_save_test) models.signals.pre_save.disconnect(self.pre_save_test)
# Check that all our signals got disconnected properly. # Check that all our signals got disconnected properly.
post_signals = (len(models.signals.pre_save.receivers), post_signals = (len(models.signals.pre_save.receivers),

View File

@ -617,7 +617,7 @@ class TestServeDisabled(TestServeStatic):
settings.DEBUG = False settings.DEBUG = False
def test_disabled_serving(self): def test_disabled_serving(self):
self.assertRaisesRegexp(ImproperlyConfigured, 'The staticfiles view ' six.assertRaisesRegex(self, ImproperlyConfigured, 'The staticfiles view '
'can only be used in debug mode ', self._response, 'test.txt') 'can only be used in debug mode ', self._response, 'test.txt')

View File

@ -1,6 +1,7 @@
from __future__ import absolute_import, unicode_literals from __future__ import absolute_import, unicode_literals
from django import template from django import template
from django.utils import six
from django.utils.unittest import TestCase from django.utils.unittest import TestCase
from .templatetags import custom from .templatetags import custom
@ -51,7 +52,7 @@ class CustomTagTests(TestCase):
t = template.Template('{% load custom %}{% simple_one_default one=99 two="hello" %}') t = template.Template('{% load custom %}{% simple_one_default one=99 two="hello" %}')
self.assertEqual(t.render(c), 'simple_one_default - Expected result: 99, hello') self.assertEqual(t.render(c), 'simple_one_default - Expected result: 99, hello')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'simple_one_default' received unexpected keyword argument 'three'", "'simple_one_default' received unexpected keyword argument 'three'",
template.Template, '{% load custom %}{% simple_one_default 99 two="hello" three="foo" %}') template.Template, '{% load custom %}{% simple_one_default 99 two="hello" three="foo" %}')
@ -70,22 +71,22 @@ class CustomTagTests(TestCase):
t = template.Template('{% load custom %}{% simple_only_unlimited_args 37 42 56 89 %}') t = template.Template('{% load custom %}{% simple_only_unlimited_args 37 42 56 89 %}')
self.assertEqual(t.render(c), 'simple_only_unlimited_args - Expected result: 37, 42, 56, 89') self.assertEqual(t.render(c), 'simple_only_unlimited_args - Expected result: 37, 42, 56, 89')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'simple_two_params' received too many positional arguments", "'simple_two_params' received too many positional arguments",
template.Template, '{% load custom %}{% simple_two_params 37 42 56 %}') template.Template, '{% load custom %}{% simple_two_params 37 42 56 %}')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'simple_one_default' received too many positional arguments", "'simple_one_default' received too many positional arguments",
template.Template, '{% load custom %}{% simple_one_default 37 42 56 %}') template.Template, '{% load custom %}{% simple_one_default 37 42 56 %}')
t = template.Template('{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}') t = template.Template('{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}')
self.assertEqual(t.render(c), 'simple_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4') self.assertEqual(t.render(c), 'simple_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'simple_unlimited_args_kwargs' received some positional argument\(s\) after some keyword argument\(s\)", "'simple_unlimited_args_kwargs' received some positional argument\(s\) after some keyword argument\(s\)",
template.Template, '{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 %}') template.Template, '{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 %}')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'simple_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'", "'simple_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'",
template.Template, '{% load custom %}{% simple_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}') template.Template, '{% load custom %}{% simple_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}')
@ -101,7 +102,7 @@ class CustomTagTests(TestCase):
def test_simple_tag_missing_context(self): def test_simple_tag_missing_context(self):
# The 'context' parameter must be present when takes_context is True # The 'context' parameter must be present when takes_context is True
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'simple_tag_without_context_parameter' is decorated with takes_context=True so it must have a first argument of 'context'", "'simple_tag_without_context_parameter' is decorated with takes_context=True so it must have a first argument of 'context'",
template.Template, '{% load custom %}{% simple_tag_without_context_parameter 123 %}') template.Template, '{% load custom %}{% simple_tag_without_context_parameter 123 %}')
@ -135,7 +136,7 @@ class CustomTagTests(TestCase):
t = template.Template('{% load custom %}{% inclusion_one_default one=99 two="hello" %}') t = template.Template('{% load custom %}{% inclusion_one_default one=99 two="hello" %}')
self.assertEqual(t.render(c), 'inclusion_one_default - Expected result: 99, hello\n') self.assertEqual(t.render(c), 'inclusion_one_default - Expected result: 99, hello\n')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'inclusion_one_default' received unexpected keyword argument 'three'", "'inclusion_one_default' received unexpected keyword argument 'three'",
template.Template, '{% load custom %}{% inclusion_one_default 99 two="hello" three="foo" %}') template.Template, '{% load custom %}{% inclusion_one_default 99 two="hello" three="foo" %}')
@ -154,36 +155,36 @@ class CustomTagTests(TestCase):
t = template.Template('{% load custom %}{% inclusion_only_unlimited_args 37 42 56 89 %}') t = template.Template('{% load custom %}{% inclusion_only_unlimited_args 37 42 56 89 %}')
self.assertEqual(t.render(c), 'inclusion_only_unlimited_args - Expected result: 37, 42, 56, 89\n') self.assertEqual(t.render(c), 'inclusion_only_unlimited_args - Expected result: 37, 42, 56, 89\n')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'inclusion_two_params' received too many positional arguments", "'inclusion_two_params' received too many positional arguments",
template.Template, '{% load custom %}{% inclusion_two_params 37 42 56 %}') template.Template, '{% load custom %}{% inclusion_two_params 37 42 56 %}')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'inclusion_one_default' received too many positional arguments", "'inclusion_one_default' received too many positional arguments",
template.Template, '{% load custom %}{% inclusion_one_default 37 42 56 %}') template.Template, '{% load custom %}{% inclusion_one_default 37 42 56 %}')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'inclusion_one_default' did not receive value\(s\) for the argument\(s\): 'one'", "'inclusion_one_default' did not receive value\(s\) for the argument\(s\): 'one'",
template.Template, '{% load custom %}{% inclusion_one_default %}') template.Template, '{% load custom %}{% inclusion_one_default %}')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'inclusion_unlimited_args' did not receive value\(s\) for the argument\(s\): 'one'", "'inclusion_unlimited_args' did not receive value\(s\) for the argument\(s\): 'one'",
template.Template, '{% load custom %}{% inclusion_unlimited_args %}') template.Template, '{% load custom %}{% inclusion_unlimited_args %}')
t = template.Template('{% load custom %}{% inclusion_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}') t = template.Template('{% load custom %}{% inclusion_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}')
self.assertEqual(t.render(c), 'inclusion_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4\n') self.assertEqual(t.render(c), 'inclusion_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4\n')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'inclusion_unlimited_args_kwargs' received some positional argument\(s\) after some keyword argument\(s\)", "'inclusion_unlimited_args_kwargs' received some positional argument\(s\) after some keyword argument\(s\)",
template.Template, '{% load custom %}{% inclusion_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 %}') template.Template, '{% load custom %}{% inclusion_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 %}')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'inclusion_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'", "'inclusion_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'",
template.Template, '{% load custom %}{% inclusion_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}') template.Template, '{% load custom %}{% inclusion_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}')
def test_include_tag_missing_context(self): def test_include_tag_missing_context(self):
# The 'context' parameter must be present when takes_context is True # The 'context' parameter must be present when takes_context is True
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'inclusion_tag_without_context_parameter' is decorated with takes_context=True so it must have a first argument of 'context'", "'inclusion_tag_without_context_parameter' is decorated with takes_context=True so it must have a first argument of 'context'",
template.Template, '{% load custom %}{% inclusion_tag_without_context_parameter 123 %}') template.Template, '{% load custom %}{% inclusion_tag_without_context_parameter 123 %}')
@ -296,7 +297,7 @@ class CustomTagTests(TestCase):
t = template.Template('{% load custom %}{% assignment_one_default one=99 two="hello" as var %}The result is: {{ var }}') t = template.Template('{% load custom %}{% assignment_one_default one=99 two="hello" as var %}The result is: {{ var }}')
self.assertEqual(t.render(c), 'The result is: assignment_one_default - Expected result: 99, hello') self.assertEqual(t.render(c), 'The result is: assignment_one_default - Expected result: 99, hello')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'assignment_one_default' received unexpected keyword argument 'three'", "'assignment_one_default' received unexpected keyword argument 'three'",
template.Template, '{% load custom %}{% assignment_one_default 99 two="hello" three="foo" as var %}') template.Template, '{% load custom %}{% assignment_one_default 99 two="hello" three="foo" as var %}')
@ -315,42 +316,42 @@ class CustomTagTests(TestCase):
t = template.Template('{% load custom %}{% assignment_only_unlimited_args 37 42 56 89 as var %}The result is: {{ var }}') t = template.Template('{% load custom %}{% assignment_only_unlimited_args 37 42 56 89 as var %}The result is: {{ var }}')
self.assertEqual(t.render(c), 'The result is: assignment_only_unlimited_args - Expected result: 37, 42, 56, 89') self.assertEqual(t.render(c), 'The result is: assignment_only_unlimited_args - Expected result: 37, 42, 56, 89')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'assignment_one_param' tag takes at least 2 arguments and the second last argument must be 'as'", "'assignment_one_param' tag takes at least 2 arguments and the second last argument must be 'as'",
template.Template, '{% load custom %}{% assignment_one_param 37 %}The result is: {{ var }}') template.Template, '{% load custom %}{% assignment_one_param 37 %}The result is: {{ var }}')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'assignment_one_param' tag takes at least 2 arguments and the second last argument must be 'as'", "'assignment_one_param' tag takes at least 2 arguments and the second last argument must be 'as'",
template.Template, '{% load custom %}{% assignment_one_param 37 as %}The result is: {{ var }}') template.Template, '{% load custom %}{% assignment_one_param 37 as %}The result is: {{ var }}')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'assignment_one_param' tag takes at least 2 arguments and the second last argument must be 'as'", "'assignment_one_param' tag takes at least 2 arguments and the second last argument must be 'as'",
template.Template, '{% load custom %}{% assignment_one_param 37 ass var %}The result is: {{ var }}') template.Template, '{% load custom %}{% assignment_one_param 37 ass var %}The result is: {{ var }}')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'assignment_two_params' received too many positional arguments", "'assignment_two_params' received too many positional arguments",
template.Template, '{% load custom %}{% assignment_two_params 37 42 56 as var %}The result is: {{ var }}') template.Template, '{% load custom %}{% assignment_two_params 37 42 56 as var %}The result is: {{ var }}')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'assignment_one_default' received too many positional arguments", "'assignment_one_default' received too many positional arguments",
template.Template, '{% load custom %}{% assignment_one_default 37 42 56 as var %}The result is: {{ var }}') template.Template, '{% load custom %}{% assignment_one_default 37 42 56 as var %}The result is: {{ var }}')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'assignment_one_default' did not receive value\(s\) for the argument\(s\): 'one'", "'assignment_one_default' did not receive value\(s\) for the argument\(s\): 'one'",
template.Template, '{% load custom %}{% assignment_one_default as var %}The result is: {{ var }}') template.Template, '{% load custom %}{% assignment_one_default as var %}The result is: {{ var }}')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'assignment_unlimited_args' did not receive value\(s\) for the argument\(s\): 'one'", "'assignment_unlimited_args' did not receive value\(s\) for the argument\(s\): 'one'",
template.Template, '{% load custom %}{% assignment_unlimited_args as var %}The result is: {{ var }}') template.Template, '{% load custom %}{% assignment_unlimited_args as var %}The result is: {{ var }}')
t = template.Template('{% load custom %}{% assignment_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 as var %}The result is: {{ var }}') t = template.Template('{% load custom %}{% assignment_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 as var %}The result is: {{ var }}')
self.assertEqual(t.render(c), 'The result is: assignment_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4') self.assertEqual(t.render(c), 'The result is: assignment_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'assignment_unlimited_args_kwargs' received some positional argument\(s\) after some keyword argument\(s\)", "'assignment_unlimited_args_kwargs' received some positional argument\(s\) after some keyword argument\(s\)",
template.Template, '{% load custom %}{% assignment_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 as var %}The result is: {{ var }}') template.Template, '{% load custom %}{% assignment_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 as var %}The result is: {{ var }}')
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'assignment_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'", "'assignment_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'",
template.Template, '{% load custom %}{% assignment_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" as var %}The result is: {{ var }}') template.Template, '{% load custom %}{% assignment_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" as var %}The result is: {{ var }}')
@ -371,6 +372,6 @@ class CustomTagTests(TestCase):
def test_assignment_tag_missing_context(self): def test_assignment_tag_missing_context(self):
# The 'context' parameter must be present when takes_context is True # The 'context' parameter must be present when takes_context is True
self.assertRaisesRegexp(template.TemplateSyntaxError, six.assertRaisesRegex(self, template.TemplateSyntaxError,
"'assignment_tag_without_context_parameter' is decorated with takes_context=True so it must have a first argument of 'context'", "'assignment_tag_without_context_parameter' is decorated with takes_context=True so it must have a first argument of 'context'",
template.Template, '{% load custom %}{% assignment_tag_without_context_parameter 123 as var %}') template.Template, '{% load custom %}{% assignment_tag_without_context_parameter 123 as var %}')

View File

@ -17,7 +17,7 @@ import os.path
from django.template import TemplateDoesNotExist, Context from django.template import TemplateDoesNotExist, Context
from django.template.loaders.eggs import Loader as EggLoader from django.template.loaders.eggs import Loader as EggLoader
from django.template import loader from django.template import loader
from django.utils import unittest from django.utils import unittest, six
from django.utils.six import StringIO from django.utils.six import StringIO
@ -30,7 +30,7 @@ class MockProvider(pkg_resources.NullProvider):
def _has(self, path): def _has(self, path):
return path in self.module._resources return path in self.module._resources
def _isdir(self,path): def _isdir(self, path):
return False return False
def get_resource_stream(self, manager, resource_name): def get_resource_stream(self, manager, resource_name):
@ -61,8 +61,8 @@ class EggLoaderTest(unittest.TestCase):
self.empty_egg = create_egg("egg_empty", {}) self.empty_egg = create_egg("egg_empty", {})
self.egg_1 = create_egg("egg_1", { self.egg_1 = create_egg("egg_1", {
os.path.normcase('templates/y.html') : StringIO("y"), os.path.normcase('templates/y.html'): StringIO("y"),
os.path.normcase('templates/x.txt') : StringIO("x"), os.path.normcase('templates/x.txt'): StringIO("x"),
}) })
self._old_installed_apps = settings.INSTALLED_APPS self._old_installed_apps = settings.INSTALLED_APPS
settings.INSTALLED_APPS = [] settings.INSTALLED_APPS = []
@ -144,12 +144,12 @@ class RenderToStringTest(unittest.TestCase):
self.assertEqual(context['obj'], 'before') self.assertEqual(context['obj'], 'before')
def test_empty_list(self): def test_empty_list(self):
self.assertRaisesRegexp(TemplateDoesNotExist, six.assertRaisesRegex(self, TemplateDoesNotExist,
'No template names provided$', 'No template names provided$',
loader.render_to_string, []) loader.render_to_string, [])
def test_select_templates_from_empty_list(self): def test_select_templates_from_empty_list(self):
self.assertRaisesRegexp(TemplateDoesNotExist, six.assertRaisesRegex(self, TemplateDoesNotExist,
'No template names provided$', 'No template names provided$',
loader.select_template, []) loader.select_template, [])

View File

@ -137,15 +137,15 @@ class AssertTemplateUsedContextManagerTests(TestCase):
pass pass
def test_error_message(self): def test_error_message(self):
with self.assertRaisesRegexp(AssertionError, r'^template_used/base\.html'): with six.assertRaisesRegex(self, AssertionError, r'^template_used/base\.html'):
with self.assertTemplateUsed('template_used/base.html'): with self.assertTemplateUsed('template_used/base.html'):
pass pass
with self.assertRaisesRegexp(AssertionError, r'^template_used/base\.html'): with six.assertRaisesRegex(self, AssertionError, r'^template_used/base\.html'):
with self.assertTemplateUsed(template_name='template_used/base.html'): with self.assertTemplateUsed(template_name='template_used/base.html'):
pass pass
with self.assertRaisesRegexp(AssertionError, r'^template_used/base\.html.*template_used/alternative\.html$'): with six.assertRaisesRegex(self, AssertionError, r'^template_used/base\.html.*template_used/alternative\.html$'):
with self.assertTemplateUsed('template_used/base.html'): with self.assertTemplateUsed('template_used/base.html'):
render_to_string('template_used/alternative.html') render_to_string('template_used/alternative.html')

View File

@ -1,7 +1,6 @@
from __future__ import absolute_import from __future__ import absolute_import
from django.core.exceptions import ImproperlyConfigured from django.db import connection, connections, transaction, DEFAULT_DB_ALIAS, DatabaseError
from django.db import connection, connections, transaction, DEFAULT_DB_ALIAS
from django.db.transaction import commit_on_success, commit_manually, TransactionManagementError from django.db.transaction import commit_on_success, commit_manually, TransactionManagementError
from django.test import TransactionTestCase, skipUnlessDBFeature from django.test import TransactionTestCase, skipUnlessDBFeature
from django.test.utils import override_settings from django.test.utils import override_settings
@ -151,21 +150,14 @@ class TestTransactionClosing(TransactionTestCase):
# Create a user # Create a user
create_system_user() create_system_user()
try: with self.assertRaises(DatabaseError):
# The second call to create_system_user should fail for violating a unique constraint # The second call to create_system_user should fail for violating
# (it's trying to re-create the same user) # a unique constraint (it's trying to re-create the same user)
create_system_user() create_system_user()
except:
pass
else:
raise ImproperlyConfigured('Unique constraint not enforced on django.contrib.auth.models.User')
try: # Try to read the database. If the last transaction was indeed closed,
# Try to read the database. If the last transaction was indeed closed, # this should cause no problems
# this should cause no problems User.objects.all()[0]
_ = User.objects.all()[0]
except:
self.fail("A transaction consisting of a failed operation was not closed.")
@override_settings(DEBUG=True) @override_settings(DEBUG=True)
def test_failing_query_transaction_closed_debug(self): def test_failing_query_transaction_closed_debug(self):

View File

@ -4,6 +4,7 @@ Unit tests for reverse URL lookups.
from __future__ import absolute_import, unicode_literals from __future__ import absolute_import, unicode_literals
from django.conf import settings from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
from django.core.urlresolvers import (reverse, resolve, get_callable, from django.core.urlresolvers import (reverse, resolve, get_callable,
get_resolver, NoReverseMatch, Resolver404, ResolverMatch, RegexURLResolver, get_resolver, NoReverseMatch, Resolver404, ResolverMatch, RegexURLResolver,
@ -11,10 +12,9 @@ from django.core.urlresolvers import (reverse, resolve, get_callable,
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect
from django.shortcuts import redirect from django.shortcuts import redirect
from django.test import TestCase from django.test import TestCase
from django.utils import unittest from django.utils import unittest, six
from django.contrib.auth.models import User
from . import urlconf_outer, urlconf_inner, middleware, views from . import urlconf_outer, middleware, views
resolve_test_data = ( resolve_test_data = (
@ -535,7 +535,7 @@ class ViewLoadingTests(TestCase):
def test_view_loading(self): def test_view_loading(self):
# A missing view (identified by an AttributeError) should raise # A missing view (identified by an AttributeError) should raise
# ViewDoesNotExist, ... # ViewDoesNotExist, ...
self.assertRaisesRegexp(ViewDoesNotExist, ".*View does not exist in.*", six.assertRaisesRegex(self, ViewDoesNotExist, ".*View does not exist in.*",
get_callable, get_callable,
'regressiontests.urlpatterns_reverse.views.i_should_not_exist') 'regressiontests.urlpatterns_reverse.views.i_should_not_exist')
# ... but if the AttributeError is caused by something else don't # ... but if the AttributeError is caused by something else don't

View File

@ -144,21 +144,3 @@ class TestUtilsCryptoPBKDF2(unittest.TestCase):
result = pbkdf2(**vector['args']) result = pbkdf2(**vector['args'])
self.assertEqual(binascii.hexlify(result).decode('ascii'), self.assertEqual(binascii.hexlify(result).decode('ascii'),
vector['result']) vector['result'])
def test_performance_scalability(self):
"""
Theory: If you run with 100 iterations, it should take 100
times as long as running with 1 iteration.
"""
# These values are chosen as a reasonable tradeoff between time
# to run the test suite and false positives caused by imprecise
# measurement.
n1, n2 = 200000, 800000
elapsed = lambda f: timeit.Timer(f,
'from django.utils.crypto import pbkdf2').timeit(number=1)
t1 = elapsed('pbkdf2("password", "salt", iterations=%d)' % n1)
t2 = elapsed('pbkdf2("password", "salt", iterations=%d)' % n2)
measured_scale_exponent = math.log(t2 / t1, n2 / n1)
# This should be less than 1. We allow up to 1.2 so that tests don't
# fail nondeterministically too often.
self.assertLess(measured_scale_exponent, 1.2)

View File

@ -6,8 +6,7 @@ from django.core.wsgi import get_wsgi_application
from django.test import TestCase from django.test import TestCase
from django.test.client import RequestFactory from django.test.client import RequestFactory
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils import six from django.utils import six, unittest
from django.utils import unittest
class WSGITest(TestCase): class WSGITest(TestCase):
@ -84,7 +83,7 @@ class GetInternalWSGIApplicationTest(unittest.TestCase):
@override_settings(WSGI_APPLICATION="regressiontests.wsgi.noexist.app") @override_settings(WSGI_APPLICATION="regressiontests.wsgi.noexist.app")
def test_bad_module(self): def test_bad_module(self):
with self.assertRaisesRegexp( with six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
r"^WSGI application 'regressiontests.wsgi.noexist.app' could not be loaded; could not import module 'regressiontests.wsgi.noexist':"): r"^WSGI application 'regressiontests.wsgi.noexist.app' could not be loaded; could not import module 'regressiontests.wsgi.noexist':"):
@ -93,7 +92,7 @@ class GetInternalWSGIApplicationTest(unittest.TestCase):
@override_settings(WSGI_APPLICATION="regressiontests.wsgi.wsgi.noexist") @override_settings(WSGI_APPLICATION="regressiontests.wsgi.wsgi.noexist")
def test_bad_name(self): def test_bad_name(self):
with self.assertRaisesRegexp( with six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,
r"^WSGI application 'regressiontests.wsgi.wsgi.noexist' could not be loaded; can't find 'noexist' in module 'regressiontests.wsgi.wsgi':"): r"^WSGI application 'regressiontests.wsgi.wsgi.noexist' could not be loaded; can't find 'noexist' in module 'regressiontests.wsgi.wsgi':"):