1
0
mirror of https://github.com/django/django.git synced 2024-12-22 09:05:43 +00:00

Refs #23968 -- Removed unnecessary lists, generators, and tuple calls.

This commit is contained in:
Jon Dufresne 2017-06-01 16:08:59 -07:00 committed by Tim Graham
parent edee5a8de6
commit 2c69824e5a
63 changed files with 145 additions and 150 deletions

View File

@ -300,7 +300,7 @@ class Apps:
This method is safe in the sense that it doesn't trigger any imports.
"""
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):
raise ValueError(
"Available apps isn't a subset of installed apps, extra apps: %s"

View File

@ -25,7 +25,7 @@ def add_preserved_filters(context, url, popup=False, to_field=None):
parsed_url = list(urlparse(url))
parsed_qs = dict(parse_qsl(parsed_url[4]))
merged_qs = dict()
merged_qs = {}
if opts and preserved_filters:
preserved_filters = dict(parse_qsl(preserved_filters))

View File

@ -54,7 +54,7 @@ class ModelBackend:
else:
perms = getattr(self, '_get_%s_permissions' % from_name)(user_obj)
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)
def get_user_permissions(self, user_obj, obj=None):

View File

@ -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
# (content_type, (codename, name))
searched_perms = list()
searched_perms = []
# The codenames and ctypes that should exist.
ctypes = set()
for klass in app_config.get_models():

View File

@ -529,7 +529,7 @@ def create_generic_related_manager(superclass, rel):
query = {
'%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

View File

@ -72,7 +72,7 @@ def get_flatpages(parser, token):
bits = token.split_contents()
syntax_message = ("%(tag_name)s expects a syntax of %(tag_name)s "
"['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
if len(bits) >= 3 and len(bits) <= 6:

View File

@ -159,7 +159,7 @@ class MemcachedCache(BaseMemcachedCache):
@property
def _cache(self):
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)
self._client = self._lib.Client(self._servers, **client_kwargs)
return self._client

View File

@ -428,7 +428,7 @@ class BaseCommand:
plan = executor.migration_plan(executor.loader.graph.leaf_nodes())
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.style.NOTICE(
"\nYou have %(unpplied_migration_count)s unapplied migration(s). "

View File

@ -235,7 +235,7 @@ class Command(BaseCommand):
'.'.join(ext for ext in combo if ext)
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 = []
for fixture_dir in fixture_dirs:

View File

@ -78,7 +78,7 @@ class Command(BaseCommand):
loader = MigrationLoader(None, ignore_no_migrations=True)
# 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.
aliases_to_check = connections if settings.DATABASE_ROUTERS else [DEFAULT_DB_ALIAS]
for alias in sorted(aliases_to_check):

View File

@ -143,7 +143,7 @@ class Command(BaseCommand):
if target_app_labels_only:
self.stdout.write(
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:
if targets[0][1] is None:

View File

@ -324,8 +324,8 @@ class BaseDatabaseSchemaEditor:
unique_togethers must be doubly-nested, not the single-nested
["foo", "bar"] format.
"""
olds = set(tuple(fields) for fields in old_unique_together)
news = set(tuple(fields) for fields in new_unique_together)
olds = {tuple(fields) for fields in old_unique_together}
news = {tuple(fields) for fields in new_unique_together}
# Deleted uniques
for fields in olds.difference(news):
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
["foo", "bar"] format.
"""
olds = set(tuple(fields) for fields in old_index_together)
news = set(tuple(fields) for fields in new_index_together)
olds = {tuple(fields) for fields in old_index_together}
news = {tuple(fields) for fields in new_index_together}
# Deleted indexes
for fields in olds.difference(news):
self._delete_composed_index(model, fields, {'index': True}, self.sql_delete_index)

View File

@ -169,7 +169,7 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
'indexes': indexes,
'apps': apps,
}
meta = type("Meta", tuple(), meta_contents)
meta = type("Meta", (), meta_contents)
body['Meta'] = meta
body['__module__'] = model.__module__

View File

@ -1065,14 +1065,14 @@ class MigrationAutodetector:
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]
new_model_state = self.to_state.models[app_label, model_name]
old_options = dict(
option for option in old_model_state.options.items()
if option[0] in AlterModelOptions.ALTER_OPTION_KEYS
)
new_options = dict(
option for option in new_model_state.options.items()
if option[0] in AlterModelOptions.ALTER_OPTION_KEYS
)
old_options = {
key: value for key, value in old_model_state.options.items()
if key in AlterModelOptions.ALTER_OPTION_KEYS
}
new_options = {
key: value for key, value in new_model_state.options.items()
if key in AlterModelOptions.ALTER_OPTION_KEYS
}
if old_options != new_options:
self.add_operation(
app_label,

View File

@ -496,7 +496,7 @@ class AlterUniqueTogether(FieldRelatedOptionOperation):
def __init__(self, name, 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)
def deconstruct(self):
@ -550,7 +550,7 @@ class AlterIndexTogether(FieldRelatedOptionOperation):
def __init__(self, name, 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)
def deconstruct(self):

View File

@ -55,7 +55,7 @@ class MigrationRecorder:
def applied_migrations(self):
"""Return a set of (app, name) of applied migrations."""
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):
"""Record that a migration was applied."""

View File

@ -559,7 +559,7 @@ class ModelState:
# First, make a Meta object
meta_contents = {'app_label': self.app_label, "apps": apps}
meta_contents.update(self.options)
meta = type("Meta", tuple(), meta_contents)
meta = type("Meta", (), meta_contents)
# Then, work out our bases
try:
bases = tuple(

View File

@ -1294,7 +1294,7 @@ class Model(metaclass=ModelBase):
@classmethod
def _check_id_field(cls):
"""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
if fields and not fields[0].primary_key and cls._meta.pk.name == 'id':
return [

View File

@ -122,7 +122,7 @@ class ForwardManyToOneDescriptor:
# The check for len(...) == 1 is a special case that allows the query
# to be join-less and smaller. Refs #21760.
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:
query = {'%s__in' % self.field.related_query_name(): instances}
queryset = queryset.filter(**query)

View File

@ -20,7 +20,7 @@ from django.utils.translation import override
PROXY_PARENTS = object()
EMPTY_RELATION_TREE = tuple()
EMPTY_RELATION_TREE = ()
IMMUTABLE_WARNING = (
"The return type of '%s' should never be mutated. If you want to manipulate this list "

View File

@ -1251,8 +1251,7 @@ class Query:
# (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.
# So, demotion is OK.
existing_inner = set(
(a for a in self.alias_map if self.alias_map[a].join_type == INNER))
existing_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)
if clause:
self.where.add(clause, AND)
@ -1437,8 +1436,8 @@ class Query:
for pos, info in enumerate(reversed(path)):
if len(joins) == 1 or not info.direct:
break
join_targets = set(t.column for t in info.join_field.foreign_related_fields)
cur_targets = set(t.column for t in targets)
join_targets = {t.column for t in info.join_field.foreign_related_fields}
cur_targets = {t.column for t in targets}
if not cur_targets.issubset(join_targets):
break
targets_dict = {r[1].column: r[0] for r in info.join_field.related_fields if r[1].column in cur_targets}

View File

@ -47,10 +47,10 @@ class BoundField:
id_ = self.field.widget.attrs.get('id') or self.auto_id
attrs = {'id': id_} if id_ else {}
attrs = self.build_widget_attrs(attrs)
return list(
return [
BoundWidget(self.field.widget, widget, self.form.renderer)
for widget in self.field.widget.subwidgets(self.html_name, self.value(), attrs=attrs)
)
]
def __bool__(self):
# BoundField evaluates to True even if it doesn't have subwidgets.

View File

@ -873,8 +873,8 @@ class MultipleChoiceField(ChoiceField):
data = []
if len(initial) != len(data):
return True
initial_set = set(str(value) for value in initial)
data_set = set(str(value) for value in data)
initial_set = {str(value) for value in initial}
data_set = {str(value) for value in data}
return data_set != initial_set

View File

@ -1289,7 +1289,7 @@ class ModelMultipleChoiceField(ModelChoiceField):
params={'pk': pk},
)
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:
if str(val) not in pks:
raise ValidationError(
@ -1313,8 +1313,8 @@ class ModelMultipleChoiceField(ModelChoiceField):
data = []
if len(initial) != len(data):
return True
initial_set = set(str(value) for value in self.prepare_value(initial))
data_set = set(str(value) for value in data)
initial_set = {str(value) for value in self.prepare_value(initial)}
data_set = {str(value) for value in data}
return data_set != initial_set

View File

@ -287,7 +287,7 @@ def patch_vary_headers(response, newheaders):
else:
vary_headers = []
# 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
if newheader.lower() not in existing_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'):
return False
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

View File

@ -230,7 +230,7 @@ class JavaScriptCatalog(View):
return self.render_to_response(context)
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]
# paths of requested packages
return [os.path.join(app.path, 'locale') for app in app_configs]

View File

@ -250,8 +250,7 @@ class DjangoHTMLTranslator(HTMLTranslator):
self.first_param = 1
self.optional_param_level = 0
self.param_separator = node.child_text_separator
self.required_params_left = sum([isinstance(c, addnodes.desc_parameter)
for c in node.children])
self.required_params_left = sum(isinstance(c, addnodes.desc_parameter) for c in node.children)
def depart_desc_parameterlist(self, node):
self.body.append(')')

View File

@ -114,7 +114,7 @@ def lang_stats(resources=None, languages=None):
for name, dir_ in locale_dirs:
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:
if languages and lang not in languages:
continue
@ -142,7 +142,7 @@ def fetch(resources=None, languages=None):
# Transifex pull
if languages is None:
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:
for lang in languages:
call('tx pull -r %(res)s -f -l %(lang)s' % {

View File

@ -8,7 +8,7 @@ urlpatterns = [
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/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/admin5/', admin.site2.urls),
url(r'^test_admin/admin7/', admin.site7.urls),

View File

@ -564,14 +564,14 @@ class ManyToManyRawIdWidgetTest(TestCase):
w.render('test', [m1.pk, m2.pk], attrs={}), (
'<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>'
) % dict(m1pk=m1.pk, m2pk=m2.pk)
) % {'m1pk': m1.pk, 'm2pk': m2.pk}
)
self.assertHTMLEqual(
w.render('test', [m1.pk]), (
'<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>'
) % dict(m1pk=m1.pk)
) % {'m1pk': m1.pk}
)
def test_m2m_related_model_not_in_admin(self):

View File

@ -1114,7 +1114,7 @@ class AggregateTestCase(TestCase):
# test completely changing how the output is rendered
def lower_case_function_override(self, compiler, connection):
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)
return self.template % substitutions, params
setattr(MySum, 'as_' + connection.vendor, lower_case_function_override)
@ -1141,7 +1141,7 @@ class AggregateTestCase(TestCase):
# test overriding all parts of the template
def be_evil(self, compiler, connection):
substitutions = dict(function='MAX', expressions='2')
substitutions = {'function': 'MAX', 'expressions': '2'}
substitutions.update(self.extra)
return self.template % substitutions, ()
setattr(MySum, 'as_' + connection.vendor, be_evil)

View File

@ -197,7 +197,7 @@ class NonAggregateAnnotationTestCase(TestCase):
name_lower=Lower('last_name'),
).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)
people2 = Employee.objects.annotate(

View File

@ -194,7 +194,7 @@ class AppsTests(SimpleTestCase):
'app_label': "apps",
'apps': new_apps,
}
meta = type("Meta", tuple(), meta_contents)
meta = type("Meta", (), meta_contents)
body['Meta'] = meta
body['__module__'] = TotallyNormal.__module__
temp_model = type("SouthPonies", (models.Model,), body)
@ -215,7 +215,7 @@ class AppsTests(SimpleTestCase):
}
body = {}
body['Meta'] = type("Meta", tuple(), meta_contents)
body['Meta'] = type("Meta", (), meta_contents)
body['__module__'] = TotallyNormal.__module__
type("SouthPonies", (models.Model,), body)
@ -223,7 +223,7 @@ class AppsTests(SimpleTestCase):
# was reloaded and issue a warning. This use-case is
# useful for REPL. Refs #23621.
body = {}
body['Meta'] = type("Meta", tuple(), meta_contents)
body['Meta'] = type("Meta", (), meta_contents)
body['__module__'] = TotallyNormal.__module__
msg = (
"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
# a RuntimeError.
body = {}
body['Meta'] = type("Meta", tuple(), meta_contents)
body['Meta'] = type("Meta", (), meta_contents)
body['__module__'] = TotallyNormal.__module__ + '.whatever'
with self.assertRaisesMessage(RuntimeError, "Conflicting 'southponies' models in application 'apps':"):
type("SouthPonies", (models.Model,), body)

View File

@ -75,7 +75,7 @@ urlpatterns = auth_urlpatterns + [
url(r'^password_reset_from_email/$',
views.PasswordResetView.as_view(from_email='staffmember@example.com')),
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/$',
views.PasswordResetView.as_view(success_url='/custom/')),
url(r'^password_reset/custom_redirect/named/$',

View File

@ -15,21 +15,21 @@ urlpatterns = [
views.password_reset_confirm, name='password_reset_confirm'),
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,
dict(extra_email_context=dict(greeting='Hello!'))),
url(r'^password_reset/custom_redirect/$', views.password_reset, dict(post_reset_redirect='/custom/')),
url(r'^password_reset/custom_redirect/named/$', views.password_reset, dict(post_reset_redirect='password_reset')),
{'extra_email_context': {'greeting': 'Hello!'}}),
url(r'^password_reset/custom_redirect/$', views.password_reset, {'post_reset_redirect': '/custom/'}),
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,
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})/$',
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})/$',
views.password_reset_confirm,
dict(post_reset_redirect='password_reset')),
url(r'^password_change/custom/$', views.password_change, dict(post_change_redirect='/custom/')),
url(r'^password_change/custom/named/$', views.password_change, dict(post_change_redirect='password_reset')),
{'post_reset_redirect': 'password_reset'}),
url(r'^password_change/custom/$', views.password_change, {'post_change_redirect': '/custom/'}),
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_url/$', login_required(views.password_reset, login_url='/somewhere/')),

View File

@ -91,19 +91,19 @@ class PostgreSQLDatabaseCreationTests(SimpleTestCase):
self.assertEqual(suffix, expected)
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, "")
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'")
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"')
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"''')
def _execute_raise_database_already_exists(self, cursor, parameters, keepdb=False):

View File

@ -970,9 +970,7 @@ class ThreadTests(TransactionTestCase):
t.start()
t.join()
# Each created connection got different inner connection.
self.assertEqual(
len(set(conn.connection for conn in connections_dict.values())),
3)
self.assertEqual(len({conn.connection for conn in connections_dict.values()}), 3)
# Finish by closing the connections opened by the other threads (the
# connection opened in the main thread will automatically be closed on
# teardown).

View File

@ -186,7 +186,7 @@ class DeletionTests(TestCase):
obj = kwargs['instance']
deleted.append(obj)
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)
a = create_a('update_setnull')

View File

@ -66,7 +66,7 @@ class FileSystemStorageTests(unittest.TestCase):
def test_deconstruction(self):
path, args, kwargs = temp_storage.deconstruct()
self.assertEqual(path, "django.core.files.storage.FileSystemStorage")
self.assertEqual(args, tuple())
self.assertEqual(args, ())
self.assertEqual(kwargs, {'location': temp_storage_location})
kwargs_orig = {

View File

@ -51,7 +51,7 @@ class StartsWithRelation(models.ForeignObject):
return StartsWith(to_field.get_col(alias), from_field.get_col(related_alias))
def get_joining_columns(self, reverse_join=False):
return tuple()
return ()
def get_path_info(self):
to_opts = self.remote_field.model._meta

View File

@ -920,7 +920,7 @@ Java</label></li>
f = SongForm(data)
self.assertEqual(f.errors, {})
data = MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P']))
data = MultiValueDict({'name': ['Yesterday'], 'composers': ['J', 'P']})
f = SongForm(data)
self.assertEqual(f.errors, {})
@ -946,7 +946,7 @@ Java</label></li>
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(
f.as_ul(),
"""<li>Name: <input type="text" name="name" value="Yesterday" required />
@ -3390,7 +3390,7 @@ Good luck picking a username that doesn&#39;t already exist.</p>
email = EmailField()
comment = CharField()
data = dict(email='invalid')
data = {'email': 'invalid'}
f = CommentForm(data, auto_id=False, error_class=DivErrorList)
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>

View File

@ -136,9 +136,8 @@ class ViewTest(unittest.TestCase):
"""
# Check each of the allowed method names
for method in SimpleView.http_method_names:
kwargs = dict(((method, "value"),))
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...
CustomizableView.as_view(parameter="value")

View File

@ -421,7 +421,7 @@ class DistanceFunctionsTests(TestCase):
qs = CensusZipcode.objects.exclude(name='77005').annotate(
distance=Distance(Transform('poly', 32140), buf)
).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):
self.assertAlmostEqual(z.distance.m, dists_m[i], 5)

View File

@ -177,8 +177,8 @@ class SpatialRefTest(unittest.TestCase):
]
srs1 = SpatialReference(srlist[0].wkt)
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 srs2.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()))
def test05_epsg(self):
"Test EPSG import."

View File

@ -17,7 +17,7 @@ class GeoFeedTest(TestCase):
def assertChildNodes(self, elem, expected):
"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)
self.assertEqual(actual, expected)

View File

@ -19,7 +19,7 @@ class GeoSitemapTest(TestCase):
def assertChildNodes(self, elem, expected):
"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)
self.assertEqual(actual, expected)

View File

@ -317,7 +317,7 @@ class RasterFieldTest(TransactionTestCase):
def test_lookup_value_error(self):
# Test with invalid dict lookup parameter
obj = dict()
obj = {}
msg = "Couldn't create spatial object from lookup value '%s'." % obj
with self.assertRaisesMessage(ValueError, msg):
RasterModel.objects.filter(geom__intersects=obj)

View File

@ -350,13 +350,13 @@ class BasicExtractorTests(ExtractorTests):
cmd.locale_paths = []
cmd.default_locale_path = os.path.join(self.test_dir, 'locale')
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())
cmd.extensions = ['js']
cmd.domain = 'djangojs'
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())
@mock.patch('django.core.management.commands.makemessages.popen_wrapper')

View File

@ -42,7 +42,7 @@ class ExistingRelatedInstancesTests(TestCase):
tournament_2 = self.t2
with self.assertNumQueries(1):
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})
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
with self.assertNumQueries(2):
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})
# and the other direction
with self.assertNumQueries(2):
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})
def test_queryset_and(self):

View File

@ -40,7 +40,7 @@ class MultiTableTests(TestCase):
result = Event.objects.filter(name='Exposition Match').prefetch_related('special_people')
with self.assertNumQueries(2):
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):
result = Person.objects.filter(name='Dan').prefetch_related('special_event_set')

View File

@ -19,23 +19,23 @@ class RecorderTests(TestCase):
"""
recorder = MigrationRecorder(connection)
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(),
)
recorder.record_applied("myapp", "0432_ponies")
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")},
)
# That should not affect records of another database
recorder_other = MigrationRecorder(connections['other'])
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(),
)
recorder.record_unapplied("myapp", "0432_ponies")
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(),
)

View File

@ -1144,7 +1144,7 @@ class RelatedModelsTests(SimpleTestCase):
'apps': self.apps,
'proxy': proxy,
}
meta = type("Meta", tuple(), meta_contents)
meta = type("Meta", (), meta_contents)
if not bases:
bases = (models.Model,)
body = {

View File

@ -318,8 +318,8 @@ class AbstractInheritanceTests(TestCase):
def fields(model):
if not hasattr(model, '_meta'):
return list()
return list((f.name, f.__class__) for f in model._meta.get_fields())
return []
return [(f.name, f.__class__) for f in model._meta.get_fields()]
model_dict = {'__module__': 'model_inheritance'}
model1 = type('Model1', (AbstractModel, Mixin), model_dict.copy())

View File

@ -162,7 +162,7 @@ class PrivateFieldsTests(OptionsBaseTests):
def test_private_fields(self):
for model, expected_names in TEST_RESULTS['private_fields'].items():
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):
@ -243,8 +243,8 @@ class RelationTreeTests(SimpleTestCase):
def test_relations_related_objects(self):
# Testing non hidden related objects
self.assertEqual(
sorted([field.related_query_name() for field in Relation._meta._relation_tree
if not field.remote_field.field.remote_field.is_hidden()]),
sorted(field.related_query_name() for field in Relation._meta._relation_tree
if not field.remote_field.field.remote_field.is_hidden()),
sorted([
'fk_abstract_rel', 'fk_base_rel', 'fk_concrete_rel', 'fo_abstract_rel',
'fo_base_rel', 'fo_concrete_rel', 'm2m_abstract_rel',
@ -253,7 +253,7 @@ class RelationTreeTests(SimpleTestCase):
)
# Testing hidden related objects
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([
'+', '_relating_basepeople_hidden_+', 'BasePerson_following_abstract+',
'BasePerson_following_abstract+', 'BasePerson_following_base+', 'BasePerson_following_base+',

View File

@ -221,7 +221,7 @@ class ModelAdminTests(TestCase):
name = forms.CharField()
class Meta:
exclude = tuple()
exclude = ()
model = Band
class BandAdmin(ModelAdmin):

View File

@ -858,7 +858,7 @@ class GenericRelationTests(TestCase):
with self.assertNumQueries(3):
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"])
def test_custom_queryset(self):

View File

@ -171,7 +171,7 @@ class SchemaTests(TransactionTestCase):
constraints = self.get_constraints(table)
self.assertIn(index, constraints)
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):
"""

View File

@ -41,7 +41,7 @@ class FeedTestCase(TestCase):
cls.a1 = Article.objects.create(title='My first article', entry=cls.e1)
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)
self.assertEqual(actual, expected)
@ -52,7 +52,7 @@ class FeedTestCase(TestCase):
def assertCategories(self, elem, expected):
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)
)

View File

@ -210,7 +210,7 @@ class IfChangedTests(SimpleTestCase):
'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")
def test_include_state(self):
@ -221,5 +221,5 @@ class IfChangedTests(SimpleTestCase):
'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')

View File

@ -326,5 +326,5 @@ class IncludeTests(SimpleTestCase):
'next': '{% load custom %}{% counter %}'
}),
], 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')

View File

@ -28,43 +28,43 @@ from .views import empty_view
resolve_test_data = (
# These entries are in the format: (path, url_name, app_name, namespace, view_name, func, args, kwargs)
# 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'}
),
(
'/included/normal/42/37/', 'inc-normal-view', 'included_namespace_urls',
'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_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
('/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_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_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/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'}
),
(
'/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.
@ -83,69 +83,69 @@ resolve_test_data = (
# Namespaces
(
'/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_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',
'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_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',
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',
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',
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
views.empty_view, (), {'arg1': '42', 'arg2': '37'}
),
# Nested namespaces
(
'/ns-included1/test3/inner/42/37/', 'urlobject-view', 'included_namespace_urls:testapp',
'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',
'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: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',
'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',
'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:urlobject-view',
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
views.empty_view, (), {'arg1': '42', 'arg2': '37'}
),
# Namespaces capturing variables
(
'/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',
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'], {}),
('price3', '/price/$10/', ['10'], {}),
('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/', [],
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/some%20resource/', [r'some resource'], {}),

View File

@ -313,7 +313,7 @@ class ExceptionReporterTests(SimpleTestCase):
def test_eol_support(self):
"""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)
for newline in ['\n', '\r\n', '\r']:

View File

@ -32,7 +32,7 @@ class SetLanguageTests(TestCase):
The user is redirected to the 'next' argument if provided.
"""
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/')
self.assertRedirects(response, '/')
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
@ -43,7 +43,7 @@ class SetLanguageTests(TestCase):
"safe".
"""
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)
self.assertEqual(response.url, '/')
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
@ -55,7 +55,7 @@ class SetLanguageTests(TestCase):
"""
lang_code = self._get_inactive_language_code()
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.
response = self.client.post('/i18n/setlang/', data=post_data, secure=True)
self.assertEqual(response.url, '/')
@ -71,7 +71,7 @@ class SetLanguageTests(TestCase):
there isn't a "next" parameter.
"""
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/')
self.assertRedirects(response, '/i18n/', fetch_redirect_response=False)
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
@ -82,7 +82,7 @@ class SetLanguageTests(TestCase):
"next" parameter.
"""
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)
self.assertRedirects(response, '/')
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.
"""
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')
self.assertRedirects(response, '/')
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
@ -103,7 +103,7 @@ class SetLanguageTests(TestCase):
AJAX calls.
"""
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'}
response = self.client.post('/i18n/setlang/', post_data, **headers)
self.assertEqual(response.status_code, 204)
@ -114,7 +114,7 @@ class SetLanguageTests(TestCase):
The set_language view returns 204 for AJAX calls by default.
"""
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')
self.assertEqual(response.status_code, 204)
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.
"""
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')
self.assertEqual(response.url, '/')
self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
@ -143,7 +143,7 @@ class SetLanguageTests(TestCase):
'LANGUAGE_COOKIE_PATH': '/test/',
}
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)
language_cookie = response.cookies.get('mylanguage')
self.assertEqual(language_cookie.value, 'pl')