mirror of
https://github.com/django/django.git
synced 2024-12-22 17:16:24 +00:00
Refs #23968 -- Removed unnecessary lists, generators, and tuple calls.
This commit is contained in:
parent
edee5a8de6
commit
2c69824e5a
@ -300,7 +300,7 @@ class Apps:
|
|||||||
This method is safe in the sense that it doesn't trigger any imports.
|
This method is safe in the sense that it doesn't trigger any imports.
|
||||||
"""
|
"""
|
||||||
available = set(available)
|
available = set(available)
|
||||||
installed = set(app_config.name for app_config in self.get_app_configs())
|
installed = {app_config.name for app_config in self.get_app_configs()}
|
||||||
if not available.issubset(installed):
|
if not available.issubset(installed):
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"Available apps isn't a subset of installed apps, extra apps: %s"
|
"Available apps isn't a subset of installed apps, extra apps: %s"
|
||||||
|
@ -25,7 +25,7 @@ def add_preserved_filters(context, url, popup=False, to_field=None):
|
|||||||
|
|
||||||
parsed_url = list(urlparse(url))
|
parsed_url = list(urlparse(url))
|
||||||
parsed_qs = dict(parse_qsl(parsed_url[4]))
|
parsed_qs = dict(parse_qsl(parsed_url[4]))
|
||||||
merged_qs = dict()
|
merged_qs = {}
|
||||||
|
|
||||||
if opts and preserved_filters:
|
if opts and preserved_filters:
|
||||||
preserved_filters = dict(parse_qsl(preserved_filters))
|
preserved_filters = dict(parse_qsl(preserved_filters))
|
||||||
|
@ -54,7 +54,7 @@ class ModelBackend:
|
|||||||
else:
|
else:
|
||||||
perms = getattr(self, '_get_%s_permissions' % from_name)(user_obj)
|
perms = getattr(self, '_get_%s_permissions' % from_name)(user_obj)
|
||||||
perms = perms.values_list('content_type__app_label', 'codename').order_by()
|
perms = perms.values_list('content_type__app_label', 'codename').order_by()
|
||||||
setattr(user_obj, perm_cache_name, set("%s.%s" % (ct, name) for ct, name in perms))
|
setattr(user_obj, perm_cache_name, {"%s.%s" % (ct, name) for ct, name in perms})
|
||||||
return getattr(user_obj, perm_cache_name)
|
return getattr(user_obj, perm_cache_name)
|
||||||
|
|
||||||
def get_user_permissions(self, user_obj, obj=None):
|
def get_user_permissions(self, user_obj, obj=None):
|
||||||
|
@ -50,7 +50,7 @@ def create_permissions(app_config, verbosity=2, interactive=True, using=DEFAULT_
|
|||||||
|
|
||||||
# This will hold the permissions we're looking for as
|
# This will hold the permissions we're looking for as
|
||||||
# (content_type, (codename, name))
|
# (content_type, (codename, name))
|
||||||
searched_perms = list()
|
searched_perms = []
|
||||||
# The codenames and ctypes that should exist.
|
# The codenames and ctypes that should exist.
|
||||||
ctypes = set()
|
ctypes = set()
|
||||||
for klass in app_config.get_models():
|
for klass in app_config.get_models():
|
||||||
|
@ -529,7 +529,7 @@ def create_generic_related_manager(superclass, rel):
|
|||||||
|
|
||||||
query = {
|
query = {
|
||||||
'%s__pk' % self.content_type_field_name: self.content_type.id,
|
'%s__pk' % self.content_type_field_name: self.content_type.id,
|
||||||
'%s__in' % self.object_id_field_name: set(obj._get_pk_val() for obj in instances)
|
'%s__in' % self.object_id_field_name: {obj._get_pk_val() for obj in instances}
|
||||||
}
|
}
|
||||||
|
|
||||||
# We (possibly) need to convert object IDs to the type of the
|
# We (possibly) need to convert object IDs to the type of the
|
||||||
|
@ -72,7 +72,7 @@ def get_flatpages(parser, token):
|
|||||||
bits = token.split_contents()
|
bits = token.split_contents()
|
||||||
syntax_message = ("%(tag_name)s expects a syntax of %(tag_name)s "
|
syntax_message = ("%(tag_name)s expects a syntax of %(tag_name)s "
|
||||||
"['url_starts_with'] [for user] as context_name" %
|
"['url_starts_with'] [for user] as context_name" %
|
||||||
dict(tag_name=bits[0]))
|
{'tag_name': bits[0]})
|
||||||
# Must have at 3-6 bits in the tag
|
# Must have at 3-6 bits in the tag
|
||||||
if len(bits) >= 3 and len(bits) <= 6:
|
if len(bits) >= 3 and len(bits) <= 6:
|
||||||
|
|
||||||
|
2
django/core/cache/backends/memcached.py
vendored
2
django/core/cache/backends/memcached.py
vendored
@ -159,7 +159,7 @@ class MemcachedCache(BaseMemcachedCache):
|
|||||||
@property
|
@property
|
||||||
def _cache(self):
|
def _cache(self):
|
||||||
if getattr(self, '_client', None) is None:
|
if getattr(self, '_client', None) is None:
|
||||||
client_kwargs = dict(pickleProtocol=pickle.HIGHEST_PROTOCOL)
|
client_kwargs = {'pickleProtocol': pickle.HIGHEST_PROTOCOL}
|
||||||
client_kwargs.update(self._options)
|
client_kwargs.update(self._options)
|
||||||
self._client = self._lib.Client(self._servers, **client_kwargs)
|
self._client = self._lib.Client(self._servers, **client_kwargs)
|
||||||
return self._client
|
return self._client
|
||||||
|
@ -428,7 +428,7 @@ class BaseCommand:
|
|||||||
|
|
||||||
plan = executor.migration_plan(executor.loader.graph.leaf_nodes())
|
plan = executor.migration_plan(executor.loader.graph.leaf_nodes())
|
||||||
if plan:
|
if plan:
|
||||||
apps_waiting_migration = sorted(set(migration.app_label for migration, backwards in plan))
|
apps_waiting_migration = sorted({migration.app_label for migration, backwards in plan})
|
||||||
self.stdout.write(
|
self.stdout.write(
|
||||||
self.style.NOTICE(
|
self.style.NOTICE(
|
||||||
"\nYou have %(unpplied_migration_count)s unapplied migration(s). "
|
"\nYou have %(unpplied_migration_count)s unapplied migration(s). "
|
||||||
|
@ -235,7 +235,7 @@ class Command(BaseCommand):
|
|||||||
'.'.join(ext for ext in combo if ext)
|
'.'.join(ext for ext in combo if ext)
|
||||||
for combo in product(databases, ser_fmts, cmp_fmts)
|
for combo in product(databases, ser_fmts, cmp_fmts)
|
||||||
)
|
)
|
||||||
targets = set('.'.join((fixture_name, suffix)) for suffix in suffixes)
|
targets = {'.'.join((fixture_name, suffix)) for suffix in suffixes}
|
||||||
|
|
||||||
fixture_files = []
|
fixture_files = []
|
||||||
for fixture_dir in fixture_dirs:
|
for fixture_dir in fixture_dirs:
|
||||||
|
@ -78,7 +78,7 @@ class Command(BaseCommand):
|
|||||||
loader = MigrationLoader(None, ignore_no_migrations=True)
|
loader = MigrationLoader(None, ignore_no_migrations=True)
|
||||||
|
|
||||||
# Raise an error if any migrations are applied before their dependencies.
|
# Raise an error if any migrations are applied before their dependencies.
|
||||||
consistency_check_labels = set(config.label for config in apps.get_app_configs())
|
consistency_check_labels = {config.label for config in apps.get_app_configs()}
|
||||||
# Non-default databases are only checked if database routers used.
|
# Non-default databases are only checked if database routers used.
|
||||||
aliases_to_check = connections if settings.DATABASE_ROUTERS else [DEFAULT_DB_ALIAS]
|
aliases_to_check = connections if settings.DATABASE_ROUTERS else [DEFAULT_DB_ALIAS]
|
||||||
for alias in sorted(aliases_to_check):
|
for alias in sorted(aliases_to_check):
|
||||||
|
@ -143,7 +143,7 @@ class Command(BaseCommand):
|
|||||||
if target_app_labels_only:
|
if target_app_labels_only:
|
||||||
self.stdout.write(
|
self.stdout.write(
|
||||||
self.style.MIGRATE_LABEL(" Apply all migrations: ") +
|
self.style.MIGRATE_LABEL(" Apply all migrations: ") +
|
||||||
(", ".join(sorted(set(a for a, n in targets))) or "(none)")
|
(", ".join(sorted({a for a, n in targets})) or "(none)")
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
if targets[0][1] is None:
|
if targets[0][1] is None:
|
||||||
|
@ -324,8 +324,8 @@ class BaseDatabaseSchemaEditor:
|
|||||||
unique_togethers must be doubly-nested, not the single-nested
|
unique_togethers must be doubly-nested, not the single-nested
|
||||||
["foo", "bar"] format.
|
["foo", "bar"] format.
|
||||||
"""
|
"""
|
||||||
olds = set(tuple(fields) for fields in old_unique_together)
|
olds = {tuple(fields) for fields in old_unique_together}
|
||||||
news = set(tuple(fields) for fields in new_unique_together)
|
news = {tuple(fields) for fields in new_unique_together}
|
||||||
# Deleted uniques
|
# Deleted uniques
|
||||||
for fields in olds.difference(news):
|
for fields in olds.difference(news):
|
||||||
self._delete_composed_index(model, fields, {'unique': True}, self.sql_delete_unique)
|
self._delete_composed_index(model, fields, {'unique': True}, self.sql_delete_unique)
|
||||||
@ -340,8 +340,8 @@ class BaseDatabaseSchemaEditor:
|
|||||||
index_togethers must be doubly-nested, not the single-nested
|
index_togethers must be doubly-nested, not the single-nested
|
||||||
["foo", "bar"] format.
|
["foo", "bar"] format.
|
||||||
"""
|
"""
|
||||||
olds = set(tuple(fields) for fields in old_index_together)
|
olds = {tuple(fields) for fields in old_index_together}
|
||||||
news = set(tuple(fields) for fields in new_index_together)
|
news = {tuple(fields) for fields in new_index_together}
|
||||||
# Deleted indexes
|
# Deleted indexes
|
||||||
for fields in olds.difference(news):
|
for fields in olds.difference(news):
|
||||||
self._delete_composed_index(model, fields, {'index': True}, self.sql_delete_index)
|
self._delete_composed_index(model, fields, {'index': True}, self.sql_delete_index)
|
||||||
|
@ -169,7 +169,7 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
|
|||||||
'indexes': indexes,
|
'indexes': indexes,
|
||||||
'apps': apps,
|
'apps': apps,
|
||||||
}
|
}
|
||||||
meta = type("Meta", tuple(), meta_contents)
|
meta = type("Meta", (), meta_contents)
|
||||||
body['Meta'] = meta
|
body['Meta'] = meta
|
||||||
body['__module__'] = model.__module__
|
body['__module__'] = model.__module__
|
||||||
|
|
||||||
|
@ -1065,14 +1065,14 @@ class MigrationAutodetector:
|
|||||||
old_model_name = self.renamed_models.get((app_label, model_name), model_name)
|
old_model_name = self.renamed_models.get((app_label, model_name), model_name)
|
||||||
old_model_state = self.from_state.models[app_label, old_model_name]
|
old_model_state = self.from_state.models[app_label, old_model_name]
|
||||||
new_model_state = self.to_state.models[app_label, model_name]
|
new_model_state = self.to_state.models[app_label, model_name]
|
||||||
old_options = dict(
|
old_options = {
|
||||||
option for option in old_model_state.options.items()
|
key: value for key, value in old_model_state.options.items()
|
||||||
if option[0] in AlterModelOptions.ALTER_OPTION_KEYS
|
if key in AlterModelOptions.ALTER_OPTION_KEYS
|
||||||
)
|
}
|
||||||
new_options = dict(
|
new_options = {
|
||||||
option for option in new_model_state.options.items()
|
key: value for key, value in new_model_state.options.items()
|
||||||
if option[0] in AlterModelOptions.ALTER_OPTION_KEYS
|
if key in AlterModelOptions.ALTER_OPTION_KEYS
|
||||||
)
|
}
|
||||||
if old_options != new_options:
|
if old_options != new_options:
|
||||||
self.add_operation(
|
self.add_operation(
|
||||||
app_label,
|
app_label,
|
||||||
|
@ -496,7 +496,7 @@ class AlterUniqueTogether(FieldRelatedOptionOperation):
|
|||||||
|
|
||||||
def __init__(self, name, unique_together):
|
def __init__(self, name, unique_together):
|
||||||
unique_together = normalize_together(unique_together)
|
unique_together = normalize_together(unique_together)
|
||||||
self.unique_together = set(tuple(cons) for cons in unique_together)
|
self.unique_together = {tuple(cons) for cons in unique_together}
|
||||||
super().__init__(name)
|
super().__init__(name)
|
||||||
|
|
||||||
def deconstruct(self):
|
def deconstruct(self):
|
||||||
@ -550,7 +550,7 @@ class AlterIndexTogether(FieldRelatedOptionOperation):
|
|||||||
|
|
||||||
def __init__(self, name, index_together):
|
def __init__(self, name, index_together):
|
||||||
index_together = normalize_together(index_together)
|
index_together = normalize_together(index_together)
|
||||||
self.index_together = set(tuple(cons) for cons in index_together)
|
self.index_together = {tuple(cons) for cons in index_together}
|
||||||
super().__init__(name)
|
super().__init__(name)
|
||||||
|
|
||||||
def deconstruct(self):
|
def deconstruct(self):
|
||||||
|
@ -55,7 +55,7 @@ class MigrationRecorder:
|
|||||||
def applied_migrations(self):
|
def applied_migrations(self):
|
||||||
"""Return a set of (app, name) of applied migrations."""
|
"""Return a set of (app, name) of applied migrations."""
|
||||||
self.ensure_schema()
|
self.ensure_schema()
|
||||||
return set(tuple(x) for x in self.migration_qs.values_list("app", "name"))
|
return {tuple(x) for x in self.migration_qs.values_list("app", "name")}
|
||||||
|
|
||||||
def record_applied(self, app, name):
|
def record_applied(self, app, name):
|
||||||
"""Record that a migration was applied."""
|
"""Record that a migration was applied."""
|
||||||
|
@ -559,7 +559,7 @@ class ModelState:
|
|||||||
# First, make a Meta object
|
# First, make a Meta object
|
||||||
meta_contents = {'app_label': self.app_label, "apps": apps}
|
meta_contents = {'app_label': self.app_label, "apps": apps}
|
||||||
meta_contents.update(self.options)
|
meta_contents.update(self.options)
|
||||||
meta = type("Meta", tuple(), meta_contents)
|
meta = type("Meta", (), meta_contents)
|
||||||
# Then, work out our bases
|
# Then, work out our bases
|
||||||
try:
|
try:
|
||||||
bases = tuple(
|
bases = tuple(
|
||||||
|
@ -1294,7 +1294,7 @@ class Model(metaclass=ModelBase):
|
|||||||
@classmethod
|
@classmethod
|
||||||
def _check_id_field(cls):
|
def _check_id_field(cls):
|
||||||
"""Check if `id` field is a primary key."""
|
"""Check if `id` field is a primary key."""
|
||||||
fields = list(f for f in cls._meta.local_fields if f.name == 'id' and f != cls._meta.pk)
|
fields = [f for f in cls._meta.local_fields if f.name == 'id' and f != cls._meta.pk]
|
||||||
# fields is empty or consists of the invalid "id" field
|
# fields is empty or consists of the invalid "id" field
|
||||||
if fields and not fields[0].primary_key and cls._meta.pk.name == 'id':
|
if fields and not fields[0].primary_key and cls._meta.pk.name == 'id':
|
||||||
return [
|
return [
|
||||||
|
@ -122,7 +122,7 @@ class ForwardManyToOneDescriptor:
|
|||||||
# The check for len(...) == 1 is a special case that allows the query
|
# The check for len(...) == 1 is a special case that allows the query
|
||||||
# to be join-less and smaller. Refs #21760.
|
# to be join-less and smaller. Refs #21760.
|
||||||
if self.field.remote_field.is_hidden() or len(self.field.foreign_related_fields) == 1:
|
if self.field.remote_field.is_hidden() or len(self.field.foreign_related_fields) == 1:
|
||||||
query = {'%s__in' % related_field.name: set(instance_attr(inst)[0] for inst in instances)}
|
query = {'%s__in' % related_field.name: {instance_attr(inst)[0] for inst in instances}}
|
||||||
else:
|
else:
|
||||||
query = {'%s__in' % self.field.related_query_name(): instances}
|
query = {'%s__in' % self.field.related_query_name(): instances}
|
||||||
queryset = queryset.filter(**query)
|
queryset = queryset.filter(**query)
|
||||||
|
@ -20,7 +20,7 @@ from django.utils.translation import override
|
|||||||
|
|
||||||
PROXY_PARENTS = object()
|
PROXY_PARENTS = object()
|
||||||
|
|
||||||
EMPTY_RELATION_TREE = tuple()
|
EMPTY_RELATION_TREE = ()
|
||||||
|
|
||||||
IMMUTABLE_WARNING = (
|
IMMUTABLE_WARNING = (
|
||||||
"The return type of '%s' should never be mutated. If you want to manipulate this list "
|
"The return type of '%s' should never be mutated. If you want to manipulate this list "
|
||||||
|
@ -1251,8 +1251,7 @@ class Query:
|
|||||||
# (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if
|
# (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if
|
||||||
# rel_a doesn't produce any rows, then the whole condition must fail.
|
# rel_a doesn't produce any rows, then the whole condition must fail.
|
||||||
# So, demotion is OK.
|
# So, demotion is OK.
|
||||||
existing_inner = set(
|
existing_inner = {a for a in self.alias_map if self.alias_map[a].join_type == INNER}
|
||||||
(a for a in self.alias_map if self.alias_map[a].join_type == INNER))
|
|
||||||
clause, _ = self._add_q(q_object, self.used_aliases)
|
clause, _ = self._add_q(q_object, self.used_aliases)
|
||||||
if clause:
|
if clause:
|
||||||
self.where.add(clause, AND)
|
self.where.add(clause, AND)
|
||||||
@ -1437,8 +1436,8 @@ class Query:
|
|||||||
for pos, info in enumerate(reversed(path)):
|
for pos, info in enumerate(reversed(path)):
|
||||||
if len(joins) == 1 or not info.direct:
|
if len(joins) == 1 or not info.direct:
|
||||||
break
|
break
|
||||||
join_targets = set(t.column for t in info.join_field.foreign_related_fields)
|
join_targets = {t.column for t in info.join_field.foreign_related_fields}
|
||||||
cur_targets = set(t.column for t in targets)
|
cur_targets = {t.column for t in targets}
|
||||||
if not cur_targets.issubset(join_targets):
|
if not cur_targets.issubset(join_targets):
|
||||||
break
|
break
|
||||||
targets_dict = {r[1].column: r[0] for r in info.join_field.related_fields if r[1].column in cur_targets}
|
targets_dict = {r[1].column: r[0] for r in info.join_field.related_fields if r[1].column in cur_targets}
|
||||||
|
@ -47,10 +47,10 @@ class BoundField:
|
|||||||
id_ = self.field.widget.attrs.get('id') or self.auto_id
|
id_ = self.field.widget.attrs.get('id') or self.auto_id
|
||||||
attrs = {'id': id_} if id_ else {}
|
attrs = {'id': id_} if id_ else {}
|
||||||
attrs = self.build_widget_attrs(attrs)
|
attrs = self.build_widget_attrs(attrs)
|
||||||
return list(
|
return [
|
||||||
BoundWidget(self.field.widget, widget, self.form.renderer)
|
BoundWidget(self.field.widget, widget, self.form.renderer)
|
||||||
for widget in self.field.widget.subwidgets(self.html_name, self.value(), attrs=attrs)
|
for widget in self.field.widget.subwidgets(self.html_name, self.value(), attrs=attrs)
|
||||||
)
|
]
|
||||||
|
|
||||||
def __bool__(self):
|
def __bool__(self):
|
||||||
# BoundField evaluates to True even if it doesn't have subwidgets.
|
# BoundField evaluates to True even if it doesn't have subwidgets.
|
||||||
|
@ -873,8 +873,8 @@ class MultipleChoiceField(ChoiceField):
|
|||||||
data = []
|
data = []
|
||||||
if len(initial) != len(data):
|
if len(initial) != len(data):
|
||||||
return True
|
return True
|
||||||
initial_set = set(str(value) for value in initial)
|
initial_set = {str(value) for value in initial}
|
||||||
data_set = set(str(value) for value in data)
|
data_set = {str(value) for value in data}
|
||||||
return data_set != initial_set
|
return data_set != initial_set
|
||||||
|
|
||||||
|
|
||||||
|
@ -1289,7 +1289,7 @@ class ModelMultipleChoiceField(ModelChoiceField):
|
|||||||
params={'pk': pk},
|
params={'pk': pk},
|
||||||
)
|
)
|
||||||
qs = self.queryset.filter(**{'%s__in' % key: value})
|
qs = self.queryset.filter(**{'%s__in' % key: value})
|
||||||
pks = set(str(getattr(o, key)) for o in qs)
|
pks = {str(getattr(o, key)) for o in qs}
|
||||||
for val in value:
|
for val in value:
|
||||||
if str(val) not in pks:
|
if str(val) not in pks:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
@ -1313,8 +1313,8 @@ class ModelMultipleChoiceField(ModelChoiceField):
|
|||||||
data = []
|
data = []
|
||||||
if len(initial) != len(data):
|
if len(initial) != len(data):
|
||||||
return True
|
return True
|
||||||
initial_set = set(str(value) for value in self.prepare_value(initial))
|
initial_set = {str(value) for value in self.prepare_value(initial)}
|
||||||
data_set = set(str(value) for value in data)
|
data_set = {str(value) for value in data}
|
||||||
return data_set != initial_set
|
return data_set != initial_set
|
||||||
|
|
||||||
|
|
||||||
|
@ -287,7 +287,7 @@ def patch_vary_headers(response, newheaders):
|
|||||||
else:
|
else:
|
||||||
vary_headers = []
|
vary_headers = []
|
||||||
# Use .lower() here so we treat headers as case-insensitive.
|
# Use .lower() here so we treat headers as case-insensitive.
|
||||||
existing_headers = set(header.lower() for header in vary_headers)
|
existing_headers = {header.lower() for header in vary_headers}
|
||||||
additional_headers = [newheader for newheader in newheaders
|
additional_headers = [newheader for newheader in newheaders
|
||||||
if newheader.lower() not in existing_headers]
|
if newheader.lower() not in existing_headers]
|
||||||
response['Vary'] = ', '.join(vary_headers + additional_headers)
|
response['Vary'] = ', '.join(vary_headers + additional_headers)
|
||||||
@ -300,7 +300,7 @@ def has_vary_header(response, header_query):
|
|||||||
if not response.has_header('Vary'):
|
if not response.has_header('Vary'):
|
||||||
return False
|
return False
|
||||||
vary_headers = cc_delim_re.split(response['Vary'])
|
vary_headers = cc_delim_re.split(response['Vary'])
|
||||||
existing_headers = set(header.lower() for header in vary_headers)
|
existing_headers = {header.lower() for header in vary_headers}
|
||||||
return header_query.lower() in existing_headers
|
return header_query.lower() in existing_headers
|
||||||
|
|
||||||
|
|
||||||
|
@ -230,7 +230,7 @@ class JavaScriptCatalog(View):
|
|||||||
return self.render_to_response(context)
|
return self.render_to_response(context)
|
||||||
|
|
||||||
def get_paths(self, packages):
|
def get_paths(self, packages):
|
||||||
allowable_packages = dict((app_config.name, app_config) for app_config in apps.get_app_configs())
|
allowable_packages = {app_config.name: app_config for app_config in apps.get_app_configs()}
|
||||||
app_configs = [allowable_packages[p] for p in packages if p in allowable_packages]
|
app_configs = [allowable_packages[p] for p in packages if p in allowable_packages]
|
||||||
# paths of requested packages
|
# paths of requested packages
|
||||||
return [os.path.join(app.path, 'locale') for app in app_configs]
|
return [os.path.join(app.path, 'locale') for app in app_configs]
|
||||||
|
@ -250,8 +250,7 @@ class DjangoHTMLTranslator(HTMLTranslator):
|
|||||||
self.first_param = 1
|
self.first_param = 1
|
||||||
self.optional_param_level = 0
|
self.optional_param_level = 0
|
||||||
self.param_separator = node.child_text_separator
|
self.param_separator = node.child_text_separator
|
||||||
self.required_params_left = sum([isinstance(c, addnodes.desc_parameter)
|
self.required_params_left = sum(isinstance(c, addnodes.desc_parameter) for c in node.children)
|
||||||
for c in node.children])
|
|
||||||
|
|
||||||
def depart_desc_parameterlist(self, node):
|
def depart_desc_parameterlist(self, node):
|
||||||
self.body.append(')')
|
self.body.append(')')
|
||||||
|
@ -114,7 +114,7 @@ def lang_stats(resources=None, languages=None):
|
|||||||
|
|
||||||
for name, dir_ in locale_dirs:
|
for name, dir_ in locale_dirs:
|
||||||
print("\nShowing translations stats for '%s':" % name)
|
print("\nShowing translations stats for '%s':" % name)
|
||||||
langs = sorted([d for d in os.listdir(dir_) if not d.startswith('_')])
|
langs = sorted(d for d in os.listdir(dir_) if not d.startswith('_'))
|
||||||
for lang in langs:
|
for lang in langs:
|
||||||
if languages and lang not in languages:
|
if languages and lang not in languages:
|
||||||
continue
|
continue
|
||||||
@ -142,7 +142,7 @@ def fetch(resources=None, languages=None):
|
|||||||
# Transifex pull
|
# Transifex pull
|
||||||
if languages is None:
|
if languages is None:
|
||||||
call('tx pull -r %(res)s -a -f --minimum-perc=5' % {'res': _tx_resource_for_name(name)}, shell=True)
|
call('tx pull -r %(res)s -a -f --minimum-perc=5' % {'res': _tx_resource_for_name(name)}, shell=True)
|
||||||
target_langs = sorted([d for d in os.listdir(dir_) if not d.startswith('_') and d != 'en'])
|
target_langs = sorted(d for d in os.listdir(dir_) if not d.startswith('_') and d != 'en')
|
||||||
else:
|
else:
|
||||||
for lang in languages:
|
for lang in languages:
|
||||||
call('tx pull -r %(res)s -f -l %(lang)s' % {
|
call('tx pull -r %(res)s -f -l %(lang)s' % {
|
||||||
|
@ -8,7 +8,7 @@ urlpatterns = [
|
|||||||
url(r'^test_admin/admin/secure-view2/$', views.secure_view2, name='secure_view2'),
|
url(r'^test_admin/admin/secure-view2/$', views.secure_view2, name='secure_view2'),
|
||||||
url(r'^test_admin/admin/', admin.site.urls),
|
url(r'^test_admin/admin/', admin.site.urls),
|
||||||
url(r'^test_admin/admin2/', customadmin.site.urls),
|
url(r'^test_admin/admin2/', customadmin.site.urls),
|
||||||
url(r'^test_admin/admin3/', (admin.site.get_urls(), 'admin', 'admin3'), dict(form_url='pony')),
|
url(r'^test_admin/admin3/', (admin.site.get_urls(), 'admin', 'admin3'), {'form_url': 'pony'}),
|
||||||
url(r'^test_admin/admin4/', customadmin.simple_site.urls),
|
url(r'^test_admin/admin4/', customadmin.simple_site.urls),
|
||||||
url(r'^test_admin/admin5/', admin.site2.urls),
|
url(r'^test_admin/admin5/', admin.site2.urls),
|
||||||
url(r'^test_admin/admin7/', admin.site7.urls),
|
url(r'^test_admin/admin7/', admin.site7.urls),
|
||||||
|
@ -564,14 +564,14 @@ class ManyToManyRawIdWidgetTest(TestCase):
|
|||||||
w.render('test', [m1.pk, m2.pk], attrs={}), (
|
w.render('test', [m1.pk, m2.pk], attrs={}), (
|
||||||
'<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField" />'
|
'<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField" />'
|
||||||
'<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
|
'<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
|
||||||
) % dict(m1pk=m1.pk, m2pk=m2.pk)
|
) % {'m1pk': m1.pk, 'm2pk': m2.pk}
|
||||||
)
|
)
|
||||||
|
|
||||||
self.assertHTMLEqual(
|
self.assertHTMLEqual(
|
||||||
w.render('test', [m1.pk]), (
|
w.render('test', [m1.pk]), (
|
||||||
'<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField">'
|
'<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField">'
|
||||||
'<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
|
'<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
|
||||||
) % dict(m1pk=m1.pk)
|
) % {'m1pk': m1.pk}
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_m2m_related_model_not_in_admin(self):
|
def test_m2m_related_model_not_in_admin(self):
|
||||||
|
@ -1114,7 +1114,7 @@ class AggregateTestCase(TestCase):
|
|||||||
# test completely changing how the output is rendered
|
# test completely changing how the output is rendered
|
||||||
def lower_case_function_override(self, compiler, connection):
|
def lower_case_function_override(self, compiler, connection):
|
||||||
sql, params = compiler.compile(self.source_expressions[0])
|
sql, params = compiler.compile(self.source_expressions[0])
|
||||||
substitutions = dict(function=self.function.lower(), expressions=sql)
|
substitutions = {'function': self.function.lower(), 'expressions': sql}
|
||||||
substitutions.update(self.extra)
|
substitutions.update(self.extra)
|
||||||
return self.template % substitutions, params
|
return self.template % substitutions, params
|
||||||
setattr(MySum, 'as_' + connection.vendor, lower_case_function_override)
|
setattr(MySum, 'as_' + connection.vendor, lower_case_function_override)
|
||||||
@ -1141,7 +1141,7 @@ class AggregateTestCase(TestCase):
|
|||||||
|
|
||||||
# test overriding all parts of the template
|
# test overriding all parts of the template
|
||||||
def be_evil(self, compiler, connection):
|
def be_evil(self, compiler, connection):
|
||||||
substitutions = dict(function='MAX', expressions='2')
|
substitutions = {'function': 'MAX', 'expressions': '2'}
|
||||||
substitutions.update(self.extra)
|
substitutions.update(self.extra)
|
||||||
return self.template % substitutions, ()
|
return self.template % substitutions, ()
|
||||||
setattr(MySum, 'as_' + connection.vendor, be_evil)
|
setattr(MySum, 'as_' + connection.vendor, be_evil)
|
||||||
|
@ -197,7 +197,7 @@ class NonAggregateAnnotationTestCase(TestCase):
|
|||||||
name_lower=Lower('last_name'),
|
name_lower=Lower('last_name'),
|
||||||
).distinct('name_lower')
|
).distinct('name_lower')
|
||||||
|
|
||||||
self.assertEqual(set(p.last_name for p in people), {'Stark', 'Roosevelt'})
|
self.assertEqual({p.last_name for p in people}, {'Stark', 'Roosevelt'})
|
||||||
self.assertEqual(len(people), 2)
|
self.assertEqual(len(people), 2)
|
||||||
|
|
||||||
people2 = Employee.objects.annotate(
|
people2 = Employee.objects.annotate(
|
||||||
|
@ -194,7 +194,7 @@ class AppsTests(SimpleTestCase):
|
|||||||
'app_label': "apps",
|
'app_label': "apps",
|
||||||
'apps': new_apps,
|
'apps': new_apps,
|
||||||
}
|
}
|
||||||
meta = type("Meta", tuple(), meta_contents)
|
meta = type("Meta", (), meta_contents)
|
||||||
body['Meta'] = meta
|
body['Meta'] = meta
|
||||||
body['__module__'] = TotallyNormal.__module__
|
body['__module__'] = TotallyNormal.__module__
|
||||||
temp_model = type("SouthPonies", (models.Model,), body)
|
temp_model = type("SouthPonies", (models.Model,), body)
|
||||||
@ -215,7 +215,7 @@ class AppsTests(SimpleTestCase):
|
|||||||
}
|
}
|
||||||
|
|
||||||
body = {}
|
body = {}
|
||||||
body['Meta'] = type("Meta", tuple(), meta_contents)
|
body['Meta'] = type("Meta", (), meta_contents)
|
||||||
body['__module__'] = TotallyNormal.__module__
|
body['__module__'] = TotallyNormal.__module__
|
||||||
type("SouthPonies", (models.Model,), body)
|
type("SouthPonies", (models.Model,), body)
|
||||||
|
|
||||||
@ -223,7 +223,7 @@ class AppsTests(SimpleTestCase):
|
|||||||
# was reloaded and issue a warning. This use-case is
|
# was reloaded and issue a warning. This use-case is
|
||||||
# useful for REPL. Refs #23621.
|
# useful for REPL. Refs #23621.
|
||||||
body = {}
|
body = {}
|
||||||
body['Meta'] = type("Meta", tuple(), meta_contents)
|
body['Meta'] = type("Meta", (), meta_contents)
|
||||||
body['__module__'] = TotallyNormal.__module__
|
body['__module__'] = TotallyNormal.__module__
|
||||||
msg = (
|
msg = (
|
||||||
"Model 'apps.southponies' was already registered. "
|
"Model 'apps.southponies' was already registered. "
|
||||||
@ -236,7 +236,7 @@ class AppsTests(SimpleTestCase):
|
|||||||
# If it doesn't appear to be a reloaded module then we expect
|
# If it doesn't appear to be a reloaded module then we expect
|
||||||
# a RuntimeError.
|
# a RuntimeError.
|
||||||
body = {}
|
body = {}
|
||||||
body['Meta'] = type("Meta", tuple(), meta_contents)
|
body['Meta'] = type("Meta", (), meta_contents)
|
||||||
body['__module__'] = TotallyNormal.__module__ + '.whatever'
|
body['__module__'] = TotallyNormal.__module__ + '.whatever'
|
||||||
with self.assertRaisesMessage(RuntimeError, "Conflicting 'southponies' models in application 'apps':"):
|
with self.assertRaisesMessage(RuntimeError, "Conflicting 'southponies' models in application 'apps':"):
|
||||||
type("SouthPonies", (models.Model,), body)
|
type("SouthPonies", (models.Model,), body)
|
||||||
|
@ -75,7 +75,7 @@ urlpatterns = auth_urlpatterns + [
|
|||||||
url(r'^password_reset_from_email/$',
|
url(r'^password_reset_from_email/$',
|
||||||
views.PasswordResetView.as_view(from_email='staffmember@example.com')),
|
views.PasswordResetView.as_view(from_email='staffmember@example.com')),
|
||||||
url(r'^password_reset_extra_email_context/$',
|
url(r'^password_reset_extra_email_context/$',
|
||||||
views.PasswordResetView.as_view(extra_email_context=dict(greeting='Hello!'))),
|
views.PasswordResetView.as_view(extra_email_context={'greeting': 'Hello!'})),
|
||||||
url(r'^password_reset/custom_redirect/$',
|
url(r'^password_reset/custom_redirect/$',
|
||||||
views.PasswordResetView.as_view(success_url='/custom/')),
|
views.PasswordResetView.as_view(success_url='/custom/')),
|
||||||
url(r'^password_reset/custom_redirect/named/$',
|
url(r'^password_reset/custom_redirect/named/$',
|
||||||
|
@ -15,21 +15,21 @@ urlpatterns = [
|
|||||||
views.password_reset_confirm, name='password_reset_confirm'),
|
views.password_reset_confirm, name='password_reset_confirm'),
|
||||||
url(r'^reset/done/$', views.password_reset_complete, name='password_reset_complete'),
|
url(r'^reset/done/$', views.password_reset_complete, name='password_reset_complete'),
|
||||||
|
|
||||||
url(r'^password_reset_from_email/$', views.password_reset, dict(from_email='staffmember@example.com')),
|
url(r'^password_reset_from_email/$', views.password_reset, {'from_email': 'staffmember@example.com'}),
|
||||||
url(r'^password_reset_extra_email_context/$', views.password_reset,
|
url(r'^password_reset_extra_email_context/$', views.password_reset,
|
||||||
dict(extra_email_context=dict(greeting='Hello!'))),
|
{'extra_email_context': {'greeting': 'Hello!'}}),
|
||||||
url(r'^password_reset/custom_redirect/$', views.password_reset, dict(post_reset_redirect='/custom/')),
|
url(r'^password_reset/custom_redirect/$', views.password_reset, {'post_reset_redirect': '/custom/'}),
|
||||||
url(r'^password_reset/custom_redirect/named/$', views.password_reset, dict(post_reset_redirect='password_reset')),
|
url(r'^password_reset/custom_redirect/named/$', views.password_reset, {'post_reset_redirect': 'password_reset'}),
|
||||||
url(r'^password_reset/html_email_template/$', views.password_reset,
|
url(r'^password_reset/html_email_template/$', views.password_reset,
|
||||||
dict(html_email_template_name='registration/html_password_reset_email.html')),
|
{'html_email_template_name': 'registration/html_password_reset_email.html'}),
|
||||||
url(r'^reset/custom/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
|
url(r'^reset/custom/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
|
||||||
views.password_reset_confirm,
|
views.password_reset_confirm,
|
||||||
dict(post_reset_redirect='/custom/')),
|
{'post_reset_redirect': '/custom/'}),
|
||||||
url(r'^reset/custom/named/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
|
url(r'^reset/custom/named/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
|
||||||
views.password_reset_confirm,
|
views.password_reset_confirm,
|
||||||
dict(post_reset_redirect='password_reset')),
|
{'post_reset_redirect': 'password_reset'}),
|
||||||
url(r'^password_change/custom/$', views.password_change, dict(post_change_redirect='/custom/')),
|
url(r'^password_change/custom/$', views.password_change, {'post_change_redirect': '/custom/'}),
|
||||||
url(r'^password_change/custom/named/$', views.password_change, dict(post_change_redirect='password_reset')),
|
url(r'^password_change/custom/named/$', views.password_change, {'post_change_redirect': 'password_reset'}),
|
||||||
url(r'^login_required/$', login_required(views.password_reset)),
|
url(r'^login_required/$', login_required(views.password_reset)),
|
||||||
url(r'^login_required_login_url/$', login_required(views.password_reset, login_url='/somewhere/')),
|
url(r'^login_required_login_url/$', login_required(views.password_reset, login_url='/somewhere/')),
|
||||||
|
|
||||||
|
@ -91,19 +91,19 @@ class PostgreSQLDatabaseCreationTests(SimpleTestCase):
|
|||||||
self.assertEqual(suffix, expected)
|
self.assertEqual(suffix, expected)
|
||||||
|
|
||||||
def test_sql_table_creation_suffix_with_none_settings(self):
|
def test_sql_table_creation_suffix_with_none_settings(self):
|
||||||
settings = dict(CHARSET=None, TEMPLATE=None)
|
settings = {'CHARSET': None, 'TEMPLATE': None}
|
||||||
self.check_sql_table_creation_suffix(settings, "")
|
self.check_sql_table_creation_suffix(settings, "")
|
||||||
|
|
||||||
def test_sql_table_creation_suffix_with_encoding(self):
|
def test_sql_table_creation_suffix_with_encoding(self):
|
||||||
settings = dict(CHARSET='UTF8')
|
settings = {'CHARSET': 'UTF8'}
|
||||||
self.check_sql_table_creation_suffix(settings, "WITH ENCODING 'UTF8'")
|
self.check_sql_table_creation_suffix(settings, "WITH ENCODING 'UTF8'")
|
||||||
|
|
||||||
def test_sql_table_creation_suffix_with_template(self):
|
def test_sql_table_creation_suffix_with_template(self):
|
||||||
settings = dict(TEMPLATE='template0')
|
settings = {'TEMPLATE': 'template0'}
|
||||||
self.check_sql_table_creation_suffix(settings, 'WITH TEMPLATE "template0"')
|
self.check_sql_table_creation_suffix(settings, 'WITH TEMPLATE "template0"')
|
||||||
|
|
||||||
def test_sql_table_creation_suffix_with_encoding_and_template(self):
|
def test_sql_table_creation_suffix_with_encoding_and_template(self):
|
||||||
settings = dict(CHARSET='UTF8', TEMPLATE='template0')
|
settings = {'CHARSET': 'UTF8', 'TEMPLATE': 'template0'}
|
||||||
self.check_sql_table_creation_suffix(settings, '''WITH ENCODING 'UTF8' TEMPLATE "template0"''')
|
self.check_sql_table_creation_suffix(settings, '''WITH ENCODING 'UTF8' TEMPLATE "template0"''')
|
||||||
|
|
||||||
def _execute_raise_database_already_exists(self, cursor, parameters, keepdb=False):
|
def _execute_raise_database_already_exists(self, cursor, parameters, keepdb=False):
|
||||||
|
@ -970,9 +970,7 @@ class ThreadTests(TransactionTestCase):
|
|||||||
t.start()
|
t.start()
|
||||||
t.join()
|
t.join()
|
||||||
# Each created connection got different inner connection.
|
# Each created connection got different inner connection.
|
||||||
self.assertEqual(
|
self.assertEqual(len({conn.connection for conn in connections_dict.values()}), 3)
|
||||||
len(set(conn.connection for conn in connections_dict.values())),
|
|
||||||
3)
|
|
||||||
# Finish by closing the connections opened by the other threads (the
|
# Finish by closing the connections opened by the other threads (the
|
||||||
# connection opened in the main thread will automatically be closed on
|
# connection opened in the main thread will automatically be closed on
|
||||||
# teardown).
|
# teardown).
|
||||||
|
@ -186,7 +186,7 @@ class DeletionTests(TestCase):
|
|||||||
obj = kwargs['instance']
|
obj = kwargs['instance']
|
||||||
deleted.append(obj)
|
deleted.append(obj)
|
||||||
if isinstance(obj, R):
|
if isinstance(obj, R):
|
||||||
related_setnull_sets.append(list(a.pk for a in obj.setnull_set.all()))
|
related_setnull_sets.append([a.pk for a in obj.setnull_set.all()])
|
||||||
|
|
||||||
models.signals.pre_delete.connect(pre_delete)
|
models.signals.pre_delete.connect(pre_delete)
|
||||||
a = create_a('update_setnull')
|
a = create_a('update_setnull')
|
||||||
|
@ -66,7 +66,7 @@ class FileSystemStorageTests(unittest.TestCase):
|
|||||||
def test_deconstruction(self):
|
def test_deconstruction(self):
|
||||||
path, args, kwargs = temp_storage.deconstruct()
|
path, args, kwargs = temp_storage.deconstruct()
|
||||||
self.assertEqual(path, "django.core.files.storage.FileSystemStorage")
|
self.assertEqual(path, "django.core.files.storage.FileSystemStorage")
|
||||||
self.assertEqual(args, tuple())
|
self.assertEqual(args, ())
|
||||||
self.assertEqual(kwargs, {'location': temp_storage_location})
|
self.assertEqual(kwargs, {'location': temp_storage_location})
|
||||||
|
|
||||||
kwargs_orig = {
|
kwargs_orig = {
|
||||||
|
@ -51,7 +51,7 @@ class StartsWithRelation(models.ForeignObject):
|
|||||||
return StartsWith(to_field.get_col(alias), from_field.get_col(related_alias))
|
return StartsWith(to_field.get_col(alias), from_field.get_col(related_alias))
|
||||||
|
|
||||||
def get_joining_columns(self, reverse_join=False):
|
def get_joining_columns(self, reverse_join=False):
|
||||||
return tuple()
|
return ()
|
||||||
|
|
||||||
def get_path_info(self):
|
def get_path_info(self):
|
||||||
to_opts = self.remote_field.model._meta
|
to_opts = self.remote_field.model._meta
|
||||||
|
@ -920,7 +920,7 @@ Java</label></li>
|
|||||||
f = SongForm(data)
|
f = SongForm(data)
|
||||||
self.assertEqual(f.errors, {})
|
self.assertEqual(f.errors, {})
|
||||||
|
|
||||||
data = MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P']))
|
data = MultiValueDict({'name': ['Yesterday'], 'composers': ['J', 'P']})
|
||||||
f = SongForm(data)
|
f = SongForm(data)
|
||||||
self.assertEqual(f.errors, {})
|
self.assertEqual(f.errors, {})
|
||||||
|
|
||||||
@ -946,7 +946,7 @@ Java</label></li>
|
|||||||
widget=MultipleHiddenInput,
|
widget=MultipleHiddenInput,
|
||||||
)
|
)
|
||||||
|
|
||||||
f = SongFormHidden(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])), auto_id=False)
|
f = SongFormHidden(MultiValueDict({'name': ['Yesterday'], 'composers': ['J', 'P']}), auto_id=False)
|
||||||
self.assertHTMLEqual(
|
self.assertHTMLEqual(
|
||||||
f.as_ul(),
|
f.as_ul(),
|
||||||
"""<li>Name: <input type="text" name="name" value="Yesterday" required />
|
"""<li>Name: <input type="text" name="name" value="Yesterday" required />
|
||||||
@ -3390,7 +3390,7 @@ Good luck picking a username that doesn't already exist.</p>
|
|||||||
email = EmailField()
|
email = EmailField()
|
||||||
comment = CharField()
|
comment = CharField()
|
||||||
|
|
||||||
data = dict(email='invalid')
|
data = {'email': 'invalid'}
|
||||||
f = CommentForm(data, auto_id=False, error_class=DivErrorList)
|
f = CommentForm(data, auto_id=False, error_class=DivErrorList)
|
||||||
self.assertHTMLEqual(f.as_p(), """<p>Name: <input type="text" name="name" maxlength="50" /></p>
|
self.assertHTMLEqual(f.as_p(), """<p>Name: <input type="text" name="name" maxlength="50" /></p>
|
||||||
<div class="errorlist"><div class="error">Enter a valid email address.</div></div>
|
<div class="errorlist"><div class="error">Enter a valid email address.</div></div>
|
||||||
|
@ -136,9 +136,8 @@ class ViewTest(unittest.TestCase):
|
|||||||
"""
|
"""
|
||||||
# Check each of the allowed method names
|
# Check each of the allowed method names
|
||||||
for method in SimpleView.http_method_names:
|
for method in SimpleView.http_method_names:
|
||||||
kwargs = dict(((method, "value"),))
|
|
||||||
with self.assertRaises(TypeError):
|
with self.assertRaises(TypeError):
|
||||||
SimpleView.as_view(**kwargs)
|
SimpleView.as_view(**{method: 'value'})
|
||||||
|
|
||||||
# Check the case view argument is ok if predefined on the class...
|
# Check the case view argument is ok if predefined on the class...
|
||||||
CustomizableView.as_view(parameter="value")
|
CustomizableView.as_view(parameter="value")
|
||||||
|
@ -421,7 +421,7 @@ class DistanceFunctionsTests(TestCase):
|
|||||||
qs = CensusZipcode.objects.exclude(name='77005').annotate(
|
qs = CensusZipcode.objects.exclude(name='77005').annotate(
|
||||||
distance=Distance(Transform('poly', 32140), buf)
|
distance=Distance(Transform('poly', 32140), buf)
|
||||||
).order_by('name')
|
).order_by('name')
|
||||||
self.assertEqual(ref_zips, sorted([c.name for c in qs]))
|
self.assertEqual(ref_zips, sorted(c.name for c in qs))
|
||||||
for i, z in enumerate(qs):
|
for i, z in enumerate(qs):
|
||||||
self.assertAlmostEqual(z.distance.m, dists_m[i], 5)
|
self.assertAlmostEqual(z.distance.m, dists_m[i], 5)
|
||||||
|
|
||||||
|
@ -177,8 +177,8 @@ class SpatialRefTest(unittest.TestCase):
|
|||||||
]
|
]
|
||||||
srs1 = SpatialReference(srlist[0].wkt)
|
srs1 = SpatialReference(srlist[0].wkt)
|
||||||
srs2 = SpatialReference(WGS84_proj)
|
srs2 = SpatialReference(WGS84_proj)
|
||||||
self.assertTrue(all([part in proj_parts for part in srs1.proj.split()]))
|
self.assertTrue(all(part in proj_parts for part in srs1.proj.split()))
|
||||||
self.assertTrue(all([part in proj_parts for part in srs2.proj.split()]))
|
self.assertTrue(all(part in proj_parts for part in srs2.proj.split()))
|
||||||
|
|
||||||
def test05_epsg(self):
|
def test05_epsg(self):
|
||||||
"Test EPSG import."
|
"Test EPSG import."
|
||||||
|
@ -17,7 +17,7 @@ class GeoFeedTest(TestCase):
|
|||||||
|
|
||||||
def assertChildNodes(self, elem, expected):
|
def assertChildNodes(self, elem, expected):
|
||||||
"Taken from syndication/tests.py."
|
"Taken from syndication/tests.py."
|
||||||
actual = set(n.nodeName for n in elem.childNodes)
|
actual = {n.nodeName for n in elem.childNodes}
|
||||||
expected = set(expected)
|
expected = set(expected)
|
||||||
self.assertEqual(actual, expected)
|
self.assertEqual(actual, expected)
|
||||||
|
|
||||||
|
@ -19,7 +19,7 @@ class GeoSitemapTest(TestCase):
|
|||||||
|
|
||||||
def assertChildNodes(self, elem, expected):
|
def assertChildNodes(self, elem, expected):
|
||||||
"Taken from syndication/tests.py."
|
"Taken from syndication/tests.py."
|
||||||
actual = set(n.nodeName for n in elem.childNodes)
|
actual = {n.nodeName for n in elem.childNodes}
|
||||||
expected = set(expected)
|
expected = set(expected)
|
||||||
self.assertEqual(actual, expected)
|
self.assertEqual(actual, expected)
|
||||||
|
|
||||||
|
@ -317,7 +317,7 @@ class RasterFieldTest(TransactionTestCase):
|
|||||||
|
|
||||||
def test_lookup_value_error(self):
|
def test_lookup_value_error(self):
|
||||||
# Test with invalid dict lookup parameter
|
# Test with invalid dict lookup parameter
|
||||||
obj = dict()
|
obj = {}
|
||||||
msg = "Couldn't create spatial object from lookup value '%s'." % obj
|
msg = "Couldn't create spatial object from lookup value '%s'." % obj
|
||||||
with self.assertRaisesMessage(ValueError, msg):
|
with self.assertRaisesMessage(ValueError, msg):
|
||||||
RasterModel.objects.filter(geom__intersects=obj)
|
RasterModel.objects.filter(geom__intersects=obj)
|
||||||
|
@ -350,13 +350,13 @@ class BasicExtractorTests(ExtractorTests):
|
|||||||
cmd.locale_paths = []
|
cmd.locale_paths = []
|
||||||
cmd.default_locale_path = os.path.join(self.test_dir, 'locale')
|
cmd.default_locale_path = os.path.join(self.test_dir, 'locale')
|
||||||
found_files = cmd.find_files(self.test_dir)
|
found_files = cmd.find_files(self.test_dir)
|
||||||
found_exts = set([os.path.splitext(tfile.file)[1] for tfile in found_files])
|
found_exts = {os.path.splitext(tfile.file)[1] for tfile in found_files}
|
||||||
self.assertEqual(found_exts.difference({'.py', '.html', '.txt'}), set())
|
self.assertEqual(found_exts.difference({'.py', '.html', '.txt'}), set())
|
||||||
|
|
||||||
cmd.extensions = ['js']
|
cmd.extensions = ['js']
|
||||||
cmd.domain = 'djangojs'
|
cmd.domain = 'djangojs'
|
||||||
found_files = cmd.find_files(self.test_dir)
|
found_files = cmd.find_files(self.test_dir)
|
||||||
found_exts = set([os.path.splitext(tfile.file)[1] for tfile in found_files])
|
found_exts = {os.path.splitext(tfile.file)[1] for tfile in found_files}
|
||||||
self.assertEqual(found_exts.difference({'.js'}), set())
|
self.assertEqual(found_exts.difference({'.js'}), set())
|
||||||
|
|
||||||
@mock.patch('django.core.management.commands.makemessages.popen_wrapper')
|
@mock.patch('django.core.management.commands.makemessages.popen_wrapper')
|
||||||
|
@ -42,7 +42,7 @@ class ExistingRelatedInstancesTests(TestCase):
|
|||||||
tournament_2 = self.t2
|
tournament_2 = self.t2
|
||||||
with self.assertNumQueries(1):
|
with self.assertNumQueries(1):
|
||||||
pools = tournament_1.pool_set.all() | tournament_2.pool_set.all()
|
pools = tournament_1.pool_set.all() | tournament_2.pool_set.all()
|
||||||
related_objects = set(pool.tournament for pool in pools)
|
related_objects = {pool.tournament for pool in pools}
|
||||||
self.assertEqual(related_objects, {tournament_1, tournament_2})
|
self.assertEqual(related_objects, {tournament_1, tournament_2})
|
||||||
|
|
||||||
def test_queryset_or_different_cached_items(self):
|
def test_queryset_or_different_cached_items(self):
|
||||||
@ -60,12 +60,12 @@ class ExistingRelatedInstancesTests(TestCase):
|
|||||||
# 2 queries here as pool 3 has tournament 2, which is not cached
|
# 2 queries here as pool 3 has tournament 2, which is not cached
|
||||||
with self.assertNumQueries(2):
|
with self.assertNumQueries(2):
|
||||||
pools = tournament_1.pool_set.all() | Pool.objects.filter(pk=self.p3.pk)
|
pools = tournament_1.pool_set.all() | Pool.objects.filter(pk=self.p3.pk)
|
||||||
related_objects = set(pool.tournament for pool in pools)
|
related_objects = {pool.tournament for pool in pools}
|
||||||
self.assertEqual(related_objects, {tournament_1, tournament_2})
|
self.assertEqual(related_objects, {tournament_1, tournament_2})
|
||||||
# and the other direction
|
# and the other direction
|
||||||
with self.assertNumQueries(2):
|
with self.assertNumQueries(2):
|
||||||
pools = Pool.objects.filter(pk=self.p3.pk) | tournament_1.pool_set.all()
|
pools = Pool.objects.filter(pk=self.p3.pk) | tournament_1.pool_set.all()
|
||||||
related_objects = set(pool.tournament for pool in pools)
|
related_objects = {pool.tournament for pool in pools}
|
||||||
self.assertEqual(related_objects, {tournament_1, tournament_2})
|
self.assertEqual(related_objects, {tournament_1, tournament_2})
|
||||||
|
|
||||||
def test_queryset_and(self):
|
def test_queryset_and(self):
|
||||||
|
@ -40,7 +40,7 @@ class MultiTableTests(TestCase):
|
|||||||
result = Event.objects.filter(name='Exposition Match').prefetch_related('special_people')
|
result = Event.objects.filter(name='Exposition Match').prefetch_related('special_people')
|
||||||
with self.assertNumQueries(2):
|
with self.assertNumQueries(2):
|
||||||
self.assertCountEqual(result, [self.event])
|
self.assertCountEqual(result, [self.event])
|
||||||
self.assertEqual(sorted([p.name for p in result[0].special_people.all()]), ['Chris', 'Dan'])
|
self.assertEqual(sorted(p.name for p in result[0].special_people.all()), ['Chris', 'Dan'])
|
||||||
|
|
||||||
def test_m2m_prefetch_reverse_proxied(self):
|
def test_m2m_prefetch_reverse_proxied(self):
|
||||||
result = Person.objects.filter(name='Dan').prefetch_related('special_event_set')
|
result = Person.objects.filter(name='Dan').prefetch_related('special_event_set')
|
||||||
|
@ -19,23 +19,23 @@ class RecorderTests(TestCase):
|
|||||||
"""
|
"""
|
||||||
recorder = MigrationRecorder(connection)
|
recorder = MigrationRecorder(connection)
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
set((x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"),
|
{(x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"},
|
||||||
set(),
|
set(),
|
||||||
)
|
)
|
||||||
recorder.record_applied("myapp", "0432_ponies")
|
recorder.record_applied("myapp", "0432_ponies")
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
set((x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"),
|
{(x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"},
|
||||||
{("myapp", "0432_ponies")},
|
{("myapp", "0432_ponies")},
|
||||||
)
|
)
|
||||||
# That should not affect records of another database
|
# That should not affect records of another database
|
||||||
recorder_other = MigrationRecorder(connections['other'])
|
recorder_other = MigrationRecorder(connections['other'])
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
set((x, y) for (x, y) in recorder_other.applied_migrations() if x == "myapp"),
|
{(x, y) for (x, y) in recorder_other.applied_migrations() if x == "myapp"},
|
||||||
set(),
|
set(),
|
||||||
)
|
)
|
||||||
recorder.record_unapplied("myapp", "0432_ponies")
|
recorder.record_unapplied("myapp", "0432_ponies")
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
set((x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"),
|
{(x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"},
|
||||||
set(),
|
set(),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -1144,7 +1144,7 @@ class RelatedModelsTests(SimpleTestCase):
|
|||||||
'apps': self.apps,
|
'apps': self.apps,
|
||||||
'proxy': proxy,
|
'proxy': proxy,
|
||||||
}
|
}
|
||||||
meta = type("Meta", tuple(), meta_contents)
|
meta = type("Meta", (), meta_contents)
|
||||||
if not bases:
|
if not bases:
|
||||||
bases = (models.Model,)
|
bases = (models.Model,)
|
||||||
body = {
|
body = {
|
||||||
|
@ -318,8 +318,8 @@ class AbstractInheritanceTests(TestCase):
|
|||||||
|
|
||||||
def fields(model):
|
def fields(model):
|
||||||
if not hasattr(model, '_meta'):
|
if not hasattr(model, '_meta'):
|
||||||
return list()
|
return []
|
||||||
return list((f.name, f.__class__) for f in model._meta.get_fields())
|
return [(f.name, f.__class__) for f in model._meta.get_fields()]
|
||||||
|
|
||||||
model_dict = {'__module__': 'model_inheritance'}
|
model_dict = {'__module__': 'model_inheritance'}
|
||||||
model1 = type('Model1', (AbstractModel, Mixin), model_dict.copy())
|
model1 = type('Model1', (AbstractModel, Mixin), model_dict.copy())
|
||||||
|
@ -162,7 +162,7 @@ class PrivateFieldsTests(OptionsBaseTests):
|
|||||||
def test_private_fields(self):
|
def test_private_fields(self):
|
||||||
for model, expected_names in TEST_RESULTS['private_fields'].items():
|
for model, expected_names in TEST_RESULTS['private_fields'].items():
|
||||||
objects = model._meta.private_fields
|
objects = model._meta.private_fields
|
||||||
self.assertEqual(sorted([f.name for f in objects]), sorted(expected_names))
|
self.assertEqual(sorted(f.name for f in objects), sorted(expected_names))
|
||||||
|
|
||||||
|
|
||||||
class GetFieldByNameTests(OptionsBaseTests):
|
class GetFieldByNameTests(OptionsBaseTests):
|
||||||
@ -243,8 +243,8 @@ class RelationTreeTests(SimpleTestCase):
|
|||||||
def test_relations_related_objects(self):
|
def test_relations_related_objects(self):
|
||||||
# Testing non hidden related objects
|
# Testing non hidden related objects
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
sorted([field.related_query_name() for field in Relation._meta._relation_tree
|
sorted(field.related_query_name() for field in Relation._meta._relation_tree
|
||||||
if not field.remote_field.field.remote_field.is_hidden()]),
|
if not field.remote_field.field.remote_field.is_hidden()),
|
||||||
sorted([
|
sorted([
|
||||||
'fk_abstract_rel', 'fk_base_rel', 'fk_concrete_rel', 'fo_abstract_rel',
|
'fk_abstract_rel', 'fk_base_rel', 'fk_concrete_rel', 'fo_abstract_rel',
|
||||||
'fo_base_rel', 'fo_concrete_rel', 'm2m_abstract_rel',
|
'fo_base_rel', 'fo_concrete_rel', 'm2m_abstract_rel',
|
||||||
@ -253,7 +253,7 @@ class RelationTreeTests(SimpleTestCase):
|
|||||||
)
|
)
|
||||||
# Testing hidden related objects
|
# Testing hidden related objects
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
sorted([field.related_query_name() for field in BasePerson._meta._relation_tree]),
|
sorted(field.related_query_name() for field in BasePerson._meta._relation_tree),
|
||||||
sorted([
|
sorted([
|
||||||
'+', '_relating_basepeople_hidden_+', 'BasePerson_following_abstract+',
|
'+', '_relating_basepeople_hidden_+', 'BasePerson_following_abstract+',
|
||||||
'BasePerson_following_abstract+', 'BasePerson_following_base+', 'BasePerson_following_base+',
|
'BasePerson_following_abstract+', 'BasePerson_following_base+', 'BasePerson_following_base+',
|
||||||
|
@ -221,7 +221,7 @@ class ModelAdminTests(TestCase):
|
|||||||
name = forms.CharField()
|
name = forms.CharField()
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
exclude = tuple()
|
exclude = ()
|
||||||
model = Band
|
model = Band
|
||||||
|
|
||||||
class BandAdmin(ModelAdmin):
|
class BandAdmin(ModelAdmin):
|
||||||
|
@ -858,7 +858,7 @@ class GenericRelationTests(TestCase):
|
|||||||
|
|
||||||
with self.assertNumQueries(3):
|
with self.assertNumQueries(3):
|
||||||
bookmark = Bookmark.objects.filter(pk=b.pk).prefetch_related('tags', 'favorite_tags')[0]
|
bookmark = Bookmark.objects.filter(pk=b.pk).prefetch_related('tags', 'favorite_tags')[0]
|
||||||
self.assertEqual(sorted([i.tag for i in bookmark.tags.all()]), ["django", "python"])
|
self.assertEqual(sorted(i.tag for i in bookmark.tags.all()), ["django", "python"])
|
||||||
self.assertEqual([i.tag for i in bookmark.favorite_tags.all()], ["python"])
|
self.assertEqual([i.tag for i in bookmark.favorite_tags.all()], ["python"])
|
||||||
|
|
||||||
def test_custom_queryset(self):
|
def test_custom_queryset(self):
|
||||||
|
@ -171,7 +171,7 @@ class SchemaTests(TransactionTestCase):
|
|||||||
constraints = self.get_constraints(table)
|
constraints = self.get_constraints(table)
|
||||||
self.assertIn(index, constraints)
|
self.assertIn(index, constraints)
|
||||||
index_orders = constraints[index]['orders']
|
index_orders = constraints[index]['orders']
|
||||||
self.assertTrue(all([(val == expected) for val, expected in zip(index_orders, order)]))
|
self.assertTrue(all(val == expected for val, expected in zip(index_orders, order)))
|
||||||
|
|
||||||
def assertForeignKeyExists(self, model, column, expected_fk_table):
|
def assertForeignKeyExists(self, model, column, expected_fk_table):
|
||||||
"""
|
"""
|
||||||
|
@ -41,7 +41,7 @@ class FeedTestCase(TestCase):
|
|||||||
cls.a1 = Article.objects.create(title='My first article', entry=cls.e1)
|
cls.a1 = Article.objects.create(title='My first article', entry=cls.e1)
|
||||||
|
|
||||||
def assertChildNodes(self, elem, expected):
|
def assertChildNodes(self, elem, expected):
|
||||||
actual = set(n.nodeName for n in elem.childNodes)
|
actual = {n.nodeName for n in elem.childNodes}
|
||||||
expected = set(expected)
|
expected = set(expected)
|
||||||
self.assertEqual(actual, expected)
|
self.assertEqual(actual, expected)
|
||||||
|
|
||||||
@ -52,7 +52,7 @@ class FeedTestCase(TestCase):
|
|||||||
|
|
||||||
def assertCategories(self, elem, expected):
|
def assertCategories(self, elem, expected):
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
set(i.firstChild.wholeText for i in elem.childNodes if i.nodeName == 'category'),
|
{i.firstChild.wholeText for i in elem.childNodes if i.nodeName == 'category'},
|
||||||
set(expected)
|
set(expected)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -210,7 +210,7 @@ class IfChangedTests(SimpleTestCase):
|
|||||||
'include': '{% ifchanged %}{{ x }}{% endifchanged %}',
|
'include': '{% ifchanged %}{{ x }}{% endifchanged %}',
|
||||||
}),
|
}),
|
||||||
])
|
])
|
||||||
output = engine.render_to_string('template', dict(vars=[1, 1, 2, 2, 3, 3]))
|
output = engine.render_to_string('template', {'vars': [1, 1, 2, 2, 3, 3]})
|
||||||
self.assertEqual(output, "123")
|
self.assertEqual(output, "123")
|
||||||
|
|
||||||
def test_include_state(self):
|
def test_include_state(self):
|
||||||
@ -221,5 +221,5 @@ class IfChangedTests(SimpleTestCase):
|
|||||||
'include': '{% ifchanged %}{{ x }}{% endifchanged %}',
|
'include': '{% ifchanged %}{{ x }}{% endifchanged %}',
|
||||||
}),
|
}),
|
||||||
])
|
])
|
||||||
output = engine.render_to_string('template', dict(vars=[1, 1, 2, 2, 3, 3]))
|
output = engine.render_to_string('template', {'vars': [1, 1, 2, 2, 3, 3]})
|
||||||
self.assertEqual(output, '112233')
|
self.assertEqual(output, '112233')
|
||||||
|
@ -326,5 +326,5 @@ class IncludeTests(SimpleTestCase):
|
|||||||
'next': '{% load custom %}{% counter %}'
|
'next': '{% load custom %}{% counter %}'
|
||||||
}),
|
}),
|
||||||
], libraries={'custom': 'template_tests.templatetags.custom'})
|
], libraries={'custom': 'template_tests.templatetags.custom'})
|
||||||
output = engine.render_to_string('template', dict(vars=range(9)))
|
output = engine.render_to_string('template', {'vars': range(9)})
|
||||||
self.assertEqual(output, '012345678')
|
self.assertEqual(output, '012345678')
|
||||||
|
@ -28,43 +28,43 @@ from .views import empty_view
|
|||||||
resolve_test_data = (
|
resolve_test_data = (
|
||||||
# These entries are in the format: (path, url_name, app_name, namespace, view_name, func, args, kwargs)
|
# These entries are in the format: (path, url_name, app_name, namespace, view_name, func, args, kwargs)
|
||||||
# Simple case
|
# Simple case
|
||||||
('/normal/42/37/', 'normal-view', '', '', 'normal-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}),
|
('/normal/42/37/', 'normal-view', '', '', 'normal-view', views.empty_view, (), {'arg1': '42', 'arg2': '37'}),
|
||||||
(
|
(
|
||||||
'/view_class/42/37/', 'view-class', '', '', 'view-class', views.view_class_instance, tuple(),
|
'/view_class/42/37/', 'view-class', '', '', 'view-class', views.view_class_instance, (),
|
||||||
{'arg1': '42', 'arg2': '37'}
|
{'arg1': '42', 'arg2': '37'}
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
'/included/normal/42/37/', 'inc-normal-view', 'included_namespace_urls',
|
'/included/normal/42/37/', 'inc-normal-view', 'included_namespace_urls',
|
||||||
'included_namespace_urls', 'included_namespace_urls:inc-normal-view',
|
'included_namespace_urls', 'included_namespace_urls:inc-normal-view',
|
||||||
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
|
views.empty_view, (), {'arg1': '42', 'arg2': '37'}
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
'/included/view_class/42/37/', 'inc-view-class', 'included_namespace_urls',
|
'/included/view_class/42/37/', 'inc-view-class', 'included_namespace_urls',
|
||||||
'included_namespace_urls', 'included_namespace_urls:inc-view-class',
|
'included_namespace_urls', 'included_namespace_urls:inc-view-class',
|
||||||
views.view_class_instance, tuple(), {'arg1': '42', 'arg2': '37'}
|
views.view_class_instance, (), {'arg1': '42', 'arg2': '37'}
|
||||||
),
|
),
|
||||||
|
|
||||||
# Unnamed args are dropped if you have *any* kwargs in a pattern
|
# Unnamed args are dropped if you have *any* kwargs in a pattern
|
||||||
('/mixed_args/42/37/', 'mixed-args', '', '', 'mixed-args', views.empty_view, tuple(), {'arg2': '37'}),
|
('/mixed_args/42/37/', 'mixed-args', '', '', 'mixed-args', views.empty_view, (), {'arg2': '37'}),
|
||||||
(
|
(
|
||||||
'/included/mixed_args/42/37/', 'inc-mixed-args', 'included_namespace_urls',
|
'/included/mixed_args/42/37/', 'inc-mixed-args', 'included_namespace_urls',
|
||||||
'included_namespace_urls', 'included_namespace_urls:inc-mixed-args',
|
'included_namespace_urls', 'included_namespace_urls:inc-mixed-args',
|
||||||
views.empty_view, tuple(), {'arg2': '37'}
|
views.empty_view, (), {'arg2': '37'}
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
'/included/12/mixed_args/42/37/', 'inc-mixed-args', 'included_namespace_urls',
|
'/included/12/mixed_args/42/37/', 'inc-mixed-args', 'included_namespace_urls',
|
||||||
'included_namespace_urls', 'included_namespace_urls:inc-mixed-args',
|
'included_namespace_urls', 'included_namespace_urls:inc-mixed-args',
|
||||||
views.empty_view, tuple(), {'arg2': '37'}
|
views.empty_view, (), {'arg2': '37'}
|
||||||
),
|
),
|
||||||
|
|
||||||
# Unnamed views should have None as the url_name. Regression data for #21157.
|
# Unnamed views should have None as the url_name. Regression data for #21157.
|
||||||
(
|
(
|
||||||
'/unnamed/normal/42/37/', None, '', '', 'urlpatterns_reverse.views.empty_view', views.empty_view, tuple(),
|
'/unnamed/normal/42/37/', None, '', '', 'urlpatterns_reverse.views.empty_view', views.empty_view, (),
|
||||||
{'arg1': '42', 'arg2': '37'}
|
{'arg1': '42', 'arg2': '37'}
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
'/unnamed/view_class/42/37/', None, '', '', 'urlpatterns_reverse.views.ViewClass', views.view_class_instance,
|
'/unnamed/view_class/42/37/', None, '', '', 'urlpatterns_reverse.views.ViewClass', views.view_class_instance,
|
||||||
tuple(), {'arg1': '42', 'arg2': '37'}
|
(), {'arg1': '42', 'arg2': '37'}
|
||||||
),
|
),
|
||||||
|
|
||||||
# If you have no kwargs, you get an args list.
|
# If you have no kwargs, you get an args list.
|
||||||
@ -83,69 +83,69 @@ resolve_test_data = (
|
|||||||
# Namespaces
|
# Namespaces
|
||||||
(
|
(
|
||||||
'/test1/inner/42/37/', 'urlobject-view', 'testapp', 'test-ns1', 'test-ns1:urlobject-view',
|
'/test1/inner/42/37/', 'urlobject-view', 'testapp', 'test-ns1', 'test-ns1:urlobject-view',
|
||||||
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
|
views.empty_view, (), {'arg1': '42', 'arg2': '37'}
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
'/included/test3/inner/42/37/', 'urlobject-view', 'included_namespace_urls:testapp',
|
'/included/test3/inner/42/37/', 'urlobject-view', 'included_namespace_urls:testapp',
|
||||||
'included_namespace_urls:test-ns3', 'included_namespace_urls:test-ns3:urlobject-view',
|
'included_namespace_urls:test-ns3', 'included_namespace_urls:test-ns3:urlobject-view',
|
||||||
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
|
views.empty_view, (), {'arg1': '42', 'arg2': '37'}
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
'/ns-included1/normal/42/37/', 'inc-normal-view', 'included_namespace_urls',
|
'/ns-included1/normal/42/37/', 'inc-normal-view', 'included_namespace_urls',
|
||||||
'inc-ns1', 'inc-ns1:inc-normal-view',
|
'inc-ns1', 'inc-ns1:inc-normal-view',
|
||||||
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
|
views.empty_view, (), {'arg1': '42', 'arg2': '37'}
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
'/included/test3/inner/42/37/', 'urlobject-view', 'included_namespace_urls:testapp',
|
'/included/test3/inner/42/37/', 'urlobject-view', 'included_namespace_urls:testapp',
|
||||||
'included_namespace_urls:test-ns3', 'included_namespace_urls:test-ns3:urlobject-view',
|
'included_namespace_urls:test-ns3', 'included_namespace_urls:test-ns3:urlobject-view',
|
||||||
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
|
views.empty_view, (), {'arg1': '42', 'arg2': '37'}
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
'/default/inner/42/37/', 'urlobject-view', 'testapp', 'testapp', 'testapp:urlobject-view',
|
'/default/inner/42/37/', 'urlobject-view', 'testapp', 'testapp', 'testapp:urlobject-view',
|
||||||
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
|
views.empty_view, (), {'arg1': '42', 'arg2': '37'}
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
'/other2/inner/42/37/', 'urlobject-view', 'nodefault', 'other-ns2', 'other-ns2:urlobject-view',
|
'/other2/inner/42/37/', 'urlobject-view', 'nodefault', 'other-ns2', 'other-ns2:urlobject-view',
|
||||||
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
|
views.empty_view, (), {'arg1': '42', 'arg2': '37'}
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
'/other1/inner/42/37/', 'urlobject-view', 'nodefault', 'other-ns1', 'other-ns1:urlobject-view',
|
'/other1/inner/42/37/', 'urlobject-view', 'nodefault', 'other-ns1', 'other-ns1:urlobject-view',
|
||||||
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
|
views.empty_view, (), {'arg1': '42', 'arg2': '37'}
|
||||||
),
|
),
|
||||||
|
|
||||||
# Nested namespaces
|
# Nested namespaces
|
||||||
(
|
(
|
||||||
'/ns-included1/test3/inner/42/37/', 'urlobject-view', 'included_namespace_urls:testapp',
|
'/ns-included1/test3/inner/42/37/', 'urlobject-view', 'included_namespace_urls:testapp',
|
||||||
'inc-ns1:test-ns3', 'inc-ns1:test-ns3:urlobject-view',
|
'inc-ns1:test-ns3', 'inc-ns1:test-ns3:urlobject-view',
|
||||||
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
|
views.empty_view, (), {'arg1': '42', 'arg2': '37'}
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
'/ns-included1/ns-included4/ns-included2/test3/inner/42/37/', 'urlobject-view',
|
'/ns-included1/ns-included4/ns-included2/test3/inner/42/37/', 'urlobject-view',
|
||||||
'included_namespace_urls:namespace_urls:included_namespace_urls:testapp',
|
'included_namespace_urls:namespace_urls:included_namespace_urls:testapp',
|
||||||
'inc-ns1:inc-ns4:inc-ns2:test-ns3',
|
'inc-ns1:inc-ns4:inc-ns2:test-ns3',
|
||||||
'inc-ns1:inc-ns4:inc-ns2:test-ns3:urlobject-view',
|
'inc-ns1:inc-ns4:inc-ns2:test-ns3:urlobject-view',
|
||||||
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
|
views.empty_view, (), {'arg1': '42', 'arg2': '37'}
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
'/app-included/test3/inner/42/37/', 'urlobject-view', 'included_namespace_urls:testapp', 'inc-app:test-ns3',
|
'/app-included/test3/inner/42/37/', 'urlobject-view', 'included_namespace_urls:testapp', 'inc-app:test-ns3',
|
||||||
'inc-app:test-ns3:urlobject-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
|
'inc-app:test-ns3:urlobject-view', views.empty_view, (), {'arg1': '42', 'arg2': '37'}
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
'/app-included/ns-included4/ns-included2/test3/inner/42/37/', 'urlobject-view',
|
'/app-included/ns-included4/ns-included2/test3/inner/42/37/', 'urlobject-view',
|
||||||
'included_namespace_urls:namespace_urls:included_namespace_urls:testapp',
|
'included_namespace_urls:namespace_urls:included_namespace_urls:testapp',
|
||||||
'inc-app:inc-ns4:inc-ns2:test-ns3',
|
'inc-app:inc-ns4:inc-ns2:test-ns3',
|
||||||
'inc-app:inc-ns4:inc-ns2:test-ns3:urlobject-view',
|
'inc-app:inc-ns4:inc-ns2:test-ns3:urlobject-view',
|
||||||
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
|
views.empty_view, (), {'arg1': '42', 'arg2': '37'}
|
||||||
),
|
),
|
||||||
|
|
||||||
# Namespaces capturing variables
|
# Namespaces capturing variables
|
||||||
(
|
(
|
||||||
'/inc70/', 'inner-nothing', 'included_urls', 'inc-ns5', 'inc-ns5:inner-nothing',
|
'/inc70/', 'inner-nothing', 'included_urls', 'inc-ns5', 'inc-ns5:inner-nothing',
|
||||||
views.empty_view, tuple(), {'outer': '70'}
|
views.empty_view, (), {'outer': '70'}
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
'/inc78/extra/foobar/', 'inner-extra', 'included_urls', 'inc-ns5', 'inc-ns5:inner-extra',
|
'/inc78/extra/foobar/', 'inner-extra', 'included_urls', 'inc-ns5', 'inc-ns5:inner-extra',
|
||||||
views.empty_view, tuple(), {'outer': '78', 'extra': 'foobar'}
|
views.empty_view, (), {'outer': '78', 'extra': 'foobar'}
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -195,10 +195,10 @@ test_data = (
|
|||||||
('price2', '/price/$10/', ['10'], {}),
|
('price2', '/price/$10/', ['10'], {}),
|
||||||
('price3', '/price/$10/', ['10'], {}),
|
('price3', '/price/$10/', ['10'], {}),
|
||||||
('product', '/product/chocolate+($2.00)/', [], {'price': '2.00', 'product': 'chocolate'}),
|
('product', '/product/chocolate+($2.00)/', [], {'price': '2.00', 'product': 'chocolate'}),
|
||||||
('headlines', '/headlines/2007.5.21/', [], dict(year=2007, month=5, day=21)),
|
('headlines', '/headlines/2007.5.21/', [], {'year': 2007, 'month': 5, 'day': 21}),
|
||||||
(
|
(
|
||||||
'windows', r'/windows_path/C:%5CDocuments%20and%20Settings%5Cspam/', [],
|
'windows', r'/windows_path/C:%5CDocuments%20and%20Settings%5Cspam/', [],
|
||||||
dict(drive_name='C', path=r'Documents and Settings\spam')
|
{'drive_name': 'C', 'path': r'Documents and Settings\spam'}
|
||||||
),
|
),
|
||||||
('special', r'/special_chars/~@+%5C$*%7C/', [r'~@+\$*|'], {}),
|
('special', r'/special_chars/~@+%5C$*%7C/', [r'~@+\$*|'], {}),
|
||||||
('special', r'/special_chars/some%20resource/', [r'some resource'], {}),
|
('special', r'/special_chars/some%20resource/', [r'some resource'], {}),
|
||||||
|
@ -313,7 +313,7 @@ class ExceptionReporterTests(SimpleTestCase):
|
|||||||
|
|
||||||
def test_eol_support(self):
|
def test_eol_support(self):
|
||||||
"""The ExceptionReporter supports Unix, Windows and Macintosh EOL markers"""
|
"""The ExceptionReporter supports Unix, Windows and Macintosh EOL markers"""
|
||||||
LINES = list('print %d' % i for i in range(1, 6))
|
LINES = ['print %d' % i for i in range(1, 6)]
|
||||||
reporter = ExceptionReporter(None, None, None, None)
|
reporter = ExceptionReporter(None, None, None, None)
|
||||||
|
|
||||||
for newline in ['\n', '\r\n', '\r']:
|
for newline in ['\n', '\r\n', '\r']:
|
||||||
|
@ -32,7 +32,7 @@ class SetLanguageTests(TestCase):
|
|||||||
The user is redirected to the 'next' argument if provided.
|
The user is redirected to the 'next' argument if provided.
|
||||||
"""
|
"""
|
||||||
lang_code = self._get_inactive_language_code()
|
lang_code = self._get_inactive_language_code()
|
||||||
post_data = dict(language=lang_code, next='/')
|
post_data = {'language': lang_code, 'next': '/'}
|
||||||
response = self.client.post('/i18n/setlang/', post_data, HTTP_REFERER='/i_should_not_be_used/')
|
response = self.client.post('/i18n/setlang/', post_data, HTTP_REFERER='/i_should_not_be_used/')
|
||||||
self.assertRedirects(response, '/')
|
self.assertRedirects(response, '/')
|
||||||
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
|
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
|
||||||
@ -43,7 +43,7 @@ class SetLanguageTests(TestCase):
|
|||||||
"safe".
|
"safe".
|
||||||
"""
|
"""
|
||||||
lang_code = self._get_inactive_language_code()
|
lang_code = self._get_inactive_language_code()
|
||||||
post_data = dict(language=lang_code, next='//unsafe/redirection/')
|
post_data = {'language': lang_code, 'next': '//unsafe/redirection/'}
|
||||||
response = self.client.post('/i18n/setlang/', data=post_data)
|
response = self.client.post('/i18n/setlang/', data=post_data)
|
||||||
self.assertEqual(response.url, '/')
|
self.assertEqual(response.url, '/')
|
||||||
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
|
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
|
||||||
@ -55,7 +55,7 @@ class SetLanguageTests(TestCase):
|
|||||||
"""
|
"""
|
||||||
lang_code = self._get_inactive_language_code()
|
lang_code = self._get_inactive_language_code()
|
||||||
non_https_next_url = 'http://testserver/redirection/'
|
non_https_next_url = 'http://testserver/redirection/'
|
||||||
post_data = dict(language=lang_code, next=non_https_next_url)
|
post_data = {'language': lang_code, 'next': non_https_next_url}
|
||||||
# Insecure URL in POST data.
|
# Insecure URL in POST data.
|
||||||
response = self.client.post('/i18n/setlang/', data=post_data, secure=True)
|
response = self.client.post('/i18n/setlang/', data=post_data, secure=True)
|
||||||
self.assertEqual(response.url, '/')
|
self.assertEqual(response.url, '/')
|
||||||
@ -71,7 +71,7 @@ class SetLanguageTests(TestCase):
|
|||||||
there isn't a "next" parameter.
|
there isn't a "next" parameter.
|
||||||
"""
|
"""
|
||||||
lang_code = self._get_inactive_language_code()
|
lang_code = self._get_inactive_language_code()
|
||||||
post_data = dict(language=lang_code)
|
post_data = {'language': lang_code}
|
||||||
response = self.client.post('/i18n/setlang/', post_data, HTTP_REFERER='/i18n/')
|
response = self.client.post('/i18n/setlang/', post_data, HTTP_REFERER='/i18n/')
|
||||||
self.assertRedirects(response, '/i18n/', fetch_redirect_response=False)
|
self.assertRedirects(response, '/i18n/', fetch_redirect_response=False)
|
||||||
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
|
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
|
||||||
@ -82,7 +82,7 @@ class SetLanguageTests(TestCase):
|
|||||||
"next" parameter.
|
"next" parameter.
|
||||||
"""
|
"""
|
||||||
lang_code = self._get_inactive_language_code()
|
lang_code = self._get_inactive_language_code()
|
||||||
post_data = dict(language=lang_code)
|
post_data = {'language': lang_code}
|
||||||
response = self.client.post('/i18n/setlang/', post_data)
|
response = self.client.post('/i18n/setlang/', post_data)
|
||||||
self.assertRedirects(response, '/')
|
self.assertRedirects(response, '/')
|
||||||
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
|
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
|
||||||
@ -92,7 +92,7 @@ class SetLanguageTests(TestCase):
|
|||||||
The set_language view redirects to the "next" parameter for AJAX calls.
|
The set_language view redirects to the "next" parameter for AJAX calls.
|
||||||
"""
|
"""
|
||||||
lang_code = self._get_inactive_language_code()
|
lang_code = self._get_inactive_language_code()
|
||||||
post_data = dict(language=lang_code, next='/')
|
post_data = {'language': lang_code, 'next': '/'}
|
||||||
response = self.client.post('/i18n/setlang/', post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
|
response = self.client.post('/i18n/setlang/', post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
|
||||||
self.assertRedirects(response, '/')
|
self.assertRedirects(response, '/')
|
||||||
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
|
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
|
||||||
@ -103,7 +103,7 @@ class SetLanguageTests(TestCase):
|
|||||||
AJAX calls.
|
AJAX calls.
|
||||||
"""
|
"""
|
||||||
lang_code = self._get_inactive_language_code()
|
lang_code = self._get_inactive_language_code()
|
||||||
post_data = dict(language=lang_code)
|
post_data = {'language': lang_code}
|
||||||
headers = {'HTTP_REFERER': '/', 'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
|
headers = {'HTTP_REFERER': '/', 'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
|
||||||
response = self.client.post('/i18n/setlang/', post_data, **headers)
|
response = self.client.post('/i18n/setlang/', post_data, **headers)
|
||||||
self.assertEqual(response.status_code, 204)
|
self.assertEqual(response.status_code, 204)
|
||||||
@ -114,7 +114,7 @@ class SetLanguageTests(TestCase):
|
|||||||
The set_language view returns 204 for AJAX calls by default.
|
The set_language view returns 204 for AJAX calls by default.
|
||||||
"""
|
"""
|
||||||
lang_code = self._get_inactive_language_code()
|
lang_code = self._get_inactive_language_code()
|
||||||
post_data = dict(language=lang_code)
|
post_data = {'language': lang_code}
|
||||||
response = self.client.post('/i18n/setlang/', post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
|
response = self.client.post('/i18n/setlang/', post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
|
||||||
self.assertEqual(response.status_code, 204)
|
self.assertEqual(response.status_code, 204)
|
||||||
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
|
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
|
||||||
@ -124,7 +124,7 @@ class SetLanguageTests(TestCase):
|
|||||||
The fallback to root URL for the set_language view works for AJAX calls.
|
The fallback to root URL for the set_language view works for AJAX calls.
|
||||||
"""
|
"""
|
||||||
lang_code = self._get_inactive_language_code()
|
lang_code = self._get_inactive_language_code()
|
||||||
post_data = dict(language=lang_code, next='//unsafe/redirection/')
|
post_data = {'language': lang_code, 'next': '//unsafe/redirection/'}
|
||||||
response = self.client.post('/i18n/setlang/', post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
|
response = self.client.post('/i18n/setlang/', post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
|
||||||
self.assertEqual(response.url, '/')
|
self.assertEqual(response.url, '/')
|
||||||
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
|
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
|
||||||
@ -143,7 +143,7 @@ class SetLanguageTests(TestCase):
|
|||||||
'LANGUAGE_COOKIE_PATH': '/test/',
|
'LANGUAGE_COOKIE_PATH': '/test/',
|
||||||
}
|
}
|
||||||
with self.settings(**test_settings):
|
with self.settings(**test_settings):
|
||||||
post_data = dict(language='pl', next='/views/')
|
post_data = {'language': 'pl', 'next': '/views/'}
|
||||||
response = self.client.post('/i18n/setlang/', data=post_data)
|
response = self.client.post('/i18n/setlang/', data=post_data)
|
||||||
language_cookie = response.cookies.get('mylanguage')
|
language_cookie = response.cookies.get('mylanguage')
|
||||||
self.assertEqual(language_cookie.value, 'pl')
|
self.assertEqual(language_cookie.value, 'pl')
|
||||||
|
Loading…
Reference in New Issue
Block a user