diff --git a/django/apps/registry.py b/django/apps/registry.py index aff58db1c4..f522550d60 100644 --- a/django/apps/registry.py +++ b/django/apps/registry.py @@ -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" diff --git a/django/contrib/admin/templatetags/admin_urls.py b/django/contrib/admin/templatetags/admin_urls.py index 097fbcf040..b926fe447a 100644 --- a/django/contrib/admin/templatetags/admin_urls.py +++ b/django/contrib/admin/templatetags/admin_urls.py @@ -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)) diff --git a/django/contrib/auth/backends.py b/django/contrib/auth/backends.py index 7f5962b43c..52b80f8c49 100644 --- a/django/contrib/auth/backends.py +++ b/django/contrib/auth/backends.py @@ -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): diff --git a/django/contrib/auth/management/__init__.py b/django/contrib/auth/management/__init__.py index 922a6a3f28..36a2a7038f 100644 --- a/django/contrib/auth/management/__init__.py +++ b/django/contrib/auth/management/__init__.py @@ -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(): diff --git a/django/contrib/contenttypes/fields.py b/django/contrib/contenttypes/fields.py index fc269bbc73..e4e759502c 100644 --- a/django/contrib/contenttypes/fields.py +++ b/django/contrib/contenttypes/fields.py @@ -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 diff --git a/django/contrib/flatpages/templatetags/flatpages.py b/django/contrib/flatpages/templatetags/flatpages.py index 09260ebaa8..985083d363 100644 --- a/django/contrib/flatpages/templatetags/flatpages.py +++ b/django/contrib/flatpages/templatetags/flatpages.py @@ -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: diff --git a/django/core/cache/backends/memcached.py b/django/core/cache/backends/memcached.py index 6e8211bdff..acc0613e6b 100644 --- a/django/core/cache/backends/memcached.py +++ b/django/core/cache/backends/memcached.py @@ -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 diff --git a/django/core/management/base.py b/django/core/management/base.py index 857c15fb60..61ce6ebec5 100644 --- a/django/core/management/base.py +++ b/django/core/management/base.py @@ -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). " diff --git a/django/core/management/commands/loaddata.py b/django/core/management/commands/loaddata.py index 49679599a2..786957e86f 100644 --- a/django/core/management/commands/loaddata.py +++ b/django/core/management/commands/loaddata.py @@ -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: diff --git a/django/core/management/commands/makemigrations.py b/django/core/management/commands/makemigrations.py index 013b6035b7..45fce19b0f 100644 --- a/django/core/management/commands/makemigrations.py +++ b/django/core/management/commands/makemigrations.py @@ -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): diff --git a/django/core/management/commands/migrate.py b/django/core/management/commands/migrate.py index eb50026eab..e549b7200b 100644 --- a/django/core/management/commands/migrate.py +++ b/django/core/management/commands/migrate.py @@ -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: diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py index 7e338d690f..7e3163fbfc 100644 --- a/django/db/backends/base/schema.py +++ b/django/db/backends/base/schema.py @@ -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) diff --git a/django/db/backends/sqlite3/schema.py b/django/db/backends/sqlite3/schema.py index edc6331cb7..10d7c623f8 100644 --- a/django/db/backends/sqlite3/schema.py +++ b/django/db/backends/sqlite3/schema.py @@ -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__ diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py index 3804cfd959..3a49e26c92 100644 --- a/django/db/migrations/autodetector.py +++ b/django/db/migrations/autodetector.py @@ -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, diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py index 08cf6e314b..7daf8a7eec 100644 --- a/django/db/migrations/operations/models.py +++ b/django/db/migrations/operations/models.py @@ -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): diff --git a/django/db/migrations/recorder.py b/django/db/migrations/recorder.py index 1b4508ff85..dcc27d525c 100644 --- a/django/db/migrations/recorder.py +++ b/django/db/migrations/recorder.py @@ -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.""" diff --git a/django/db/migrations/state.py b/django/db/migrations/state.py index a4027ef6f1..0578badabe 100644 --- a/django/db/migrations/state.py +++ b/django/db/migrations/state.py @@ -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( diff --git a/django/db/models/base.py b/django/db/models/base.py index 11887d4a9d..16c7d3636f 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -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 [ diff --git a/django/db/models/fields/related_descriptors.py b/django/db/models/fields/related_descriptors.py index 542cafb6bd..86da637f26 100644 --- a/django/db/models/fields/related_descriptors.py +++ b/django/db/models/fields/related_descriptors.py @@ -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) diff --git a/django/db/models/options.py b/django/db/models/options.py index d1439f7973..82d96b739c 100644 --- a/django/db/models/options.py +++ b/django/db/models/options.py @@ -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 " diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index 39f40d604d..d53bd7758c 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -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} diff --git a/django/forms/boundfield.py b/django/forms/boundfield.py index 128d9ce80a..771661ba6a 100644 --- a/django/forms/boundfield.py +++ b/django/forms/boundfield.py @@ -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. diff --git a/django/forms/fields.py b/django/forms/fields.py index d665606745..eb16f2c353 100644 --- a/django/forms/fields.py +++ b/django/forms/fields.py @@ -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 diff --git a/django/forms/models.py b/django/forms/models.py index f4c415ed4f..98b56392d0 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -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 diff --git a/django/utils/cache.py b/django/utils/cache.py index 7e7428f112..e8576b539f 100644 --- a/django/utils/cache.py +++ b/django/utils/cache.py @@ -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 diff --git a/django/views/i18n.py b/django/views/i18n.py index 71f8cd575e..9edf83e857 100644 --- a/django/views/i18n.py +++ b/django/views/i18n.py @@ -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] diff --git a/docs/_ext/djangodocs.py b/docs/_ext/djangodocs.py index 7ccf0a0715..66e87cdddf 100644 --- a/docs/_ext/djangodocs.py +++ b/docs/_ext/djangodocs.py @@ -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(')') diff --git a/scripts/manage_translations.py b/scripts/manage_translations.py index 74534d47da..5397d35bae 100644 --- a/scripts/manage_translations.py +++ b/scripts/manage_translations.py @@ -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' % { diff --git a/tests/admin_views/urls.py b/tests/admin_views/urls.py index ca9b165626..d0a671dc00 100644 --- a/tests/admin_views/urls.py +++ b/tests/admin_views/urls.py @@ -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), diff --git a/tests/admin_widgets/tests.py b/tests/admin_widgets/tests.py index b7814f966c..d53ac0b435 100644 --- a/tests/admin_widgets/tests.py +++ b/tests/admin_widgets/tests.py @@ -564,14 +564,14 @@ class ManyToManyRawIdWidgetTest(TestCase): w.render('test', [m1.pk, m2.pk], attrs={}), ( '' '' - ) % dict(m1pk=m1.pk, m2pk=m2.pk) + ) % {'m1pk': m1.pk, 'm2pk': m2.pk} ) self.assertHTMLEqual( w.render('test', [m1.pk]), ( '' '' - ) % dict(m1pk=m1.pk) + ) % {'m1pk': m1.pk} ) def test_m2m_related_model_not_in_admin(self): diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py index 8178cb8bcc..8cf0596347 100644 --- a/tests/aggregation/tests.py +++ b/tests/aggregation/tests.py @@ -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) diff --git a/tests/annotations/tests.py b/tests/annotations/tests.py index 2ad395e65c..981e73e43e 100644 --- a/tests/annotations/tests.py +++ b/tests/annotations/tests.py @@ -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( diff --git a/tests/apps/tests.py b/tests/apps/tests.py index d53719a7fb..50b3927434 100644 --- a/tests/apps/tests.py +++ b/tests/apps/tests.py @@ -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) diff --git a/tests/auth_tests/urls.py b/tests/auth_tests/urls.py index cd21e6f69d..b69c554bc8 100644 --- a/tests/auth_tests/urls.py +++ b/tests/auth_tests/urls.py @@ -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/$', diff --git a/tests/auth_tests/urls_deprecated.py b/tests/auth_tests/urls_deprecated.py index 49bb6adb25..7fba46d269 100644 --- a/tests/auth_tests/urls_deprecated.py +++ b/tests/auth_tests/urls_deprecated.py @@ -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[0-9A-Za-z_\-]+)/(?P[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[0-9A-Za-z_\-]+)/(?P[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/')), diff --git a/tests/backends/test_creation.py b/tests/backends/test_creation.py index 4b5d01ea2d..7a18a8d19b 100644 --- a/tests/backends/test_creation.py +++ b/tests/backends/test_creation.py @@ -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): diff --git a/tests/backends/tests.py b/tests/backends/tests.py index 7a9981c0ac..5e7c6ae99c 100644 --- a/tests/backends/tests.py +++ b/tests/backends/tests.py @@ -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). diff --git a/tests/delete/tests.py b/tests/delete/tests.py index 5abae7622e..0c7e218d38 100644 --- a/tests/delete/tests.py +++ b/tests/delete/tests.py @@ -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') diff --git a/tests/file_storage/tests.py b/tests/file_storage/tests.py index 1ac86f6751..3d232bb176 100644 --- a/tests/file_storage/tests.py +++ b/tests/file_storage/tests.py @@ -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 = { diff --git a/tests/foreign_object/models/empty_join.py b/tests/foreign_object/models/empty_join.py index 4ad1ad688b..202676b075 100644 --- a/tests/foreign_object/models/empty_join.py +++ b/tests/foreign_object/models/empty_join.py @@ -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 diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py index f5d992442b..3f4fb4e10b 100644 --- a/tests/forms_tests/tests/test_forms.py +++ b/tests/forms_tests/tests/test_forms.py @@ -920,7 +920,7 @@ Java 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 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(), """
  • Name: @@ -3390,7 +3390,7 @@ Good luck picking a username that doesn't already exist.

    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(), """

    Name:

    Enter a valid email address.
    diff --git a/tests/generic_views/test_base.py b/tests/generic_views/test_base.py index f8061ca09d..9f9cde9aef 100644 --- a/tests/generic_views/test_base.py +++ b/tests/generic_views/test_base.py @@ -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") diff --git a/tests/gis_tests/distapp/tests.py b/tests/gis_tests/distapp/tests.py index eab144b3e4..30dbf4d8e1 100644 --- a/tests/gis_tests/distapp/tests.py +++ b/tests/gis_tests/distapp/tests.py @@ -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) diff --git a/tests/gis_tests/gdal_tests/test_srs.py b/tests/gis_tests/gdal_tests/test_srs.py index 4179943e21..02af60bc7a 100644 --- a/tests/gis_tests/gdal_tests/test_srs.py +++ b/tests/gis_tests/gdal_tests/test_srs.py @@ -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." diff --git a/tests/gis_tests/geoapp/test_feeds.py b/tests/gis_tests/geoapp/test_feeds.py index 6ca49be471..457754a004 100644 --- a/tests/gis_tests/geoapp/test_feeds.py +++ b/tests/gis_tests/geoapp/test_feeds.py @@ -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) diff --git a/tests/gis_tests/geoapp/test_sitemaps.py b/tests/gis_tests/geoapp/test_sitemaps.py index 69c097ea5d..d1617860b5 100644 --- a/tests/gis_tests/geoapp/test_sitemaps.py +++ b/tests/gis_tests/geoapp/test_sitemaps.py @@ -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) diff --git a/tests/gis_tests/rasterapp/test_rasterfield.py b/tests/gis_tests/rasterapp/test_rasterfield.py index df2b448a7e..e8a065fa3d 100644 --- a/tests/gis_tests/rasterapp/test_rasterfield.py +++ b/tests/gis_tests/rasterapp/test_rasterfield.py @@ -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) diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py index 731c29a978..f42aae1125 100644 --- a/tests/i18n/test_extraction.py +++ b/tests/i18n/test_extraction.py @@ -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') diff --git a/tests/known_related_objects/tests.py b/tests/known_related_objects/tests.py index c0afe4f0b9..deef6560c5 100644 --- a/tests/known_related_objects/tests.py +++ b/tests/known_related_objects/tests.py @@ -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): diff --git a/tests/m2m_through_regress/test_multitable.py b/tests/m2m_through_regress/test_multitable.py index 1ae76376fc..b354be979e 100644 --- a/tests/m2m_through_regress/test_multitable.py +++ b/tests/m2m_through_regress/test_multitable.py @@ -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') diff --git a/tests/migrations/test_loader.py b/tests/migrations/test_loader.py index 620347ab90..3d0cc750d2 100644 --- a/tests/migrations/test_loader.py +++ b/tests/migrations/test_loader.py @@ -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(), ) diff --git a/tests/migrations/test_state.py b/tests/migrations/test_state.py index ee6a9544d9..9110e8d447 100644 --- a/tests/migrations/test_state.py +++ b/tests/migrations/test_state.py @@ -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 = { diff --git a/tests/model_inheritance/test_abstract_inheritance.py b/tests/model_inheritance/test_abstract_inheritance.py index 4bd0654e46..c496ac963b 100644 --- a/tests/model_inheritance/test_abstract_inheritance.py +++ b/tests/model_inheritance/test_abstract_inheritance.py @@ -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()) diff --git a/tests/model_meta/tests.py b/tests/model_meta/tests.py index 9a692ffdd2..e64676cc1b 100644 --- a/tests/model_meta/tests.py +++ b/tests/model_meta/tests.py @@ -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+', diff --git a/tests/modeladmin/tests.py b/tests/modeladmin/tests.py index 4862664dbc..a8aac7f51b 100644 --- a/tests/modeladmin/tests.py +++ b/tests/modeladmin/tests.py @@ -221,7 +221,7 @@ class ModelAdminTests(TestCase): name = forms.CharField() class Meta: - exclude = tuple() + exclude = () model = Band class BandAdmin(ModelAdmin): diff --git a/tests/prefetch_related/tests.py b/tests/prefetch_related/tests.py index 2f322482e3..7be7cbbac4 100644 --- a/tests/prefetch_related/tests.py +++ b/tests/prefetch_related/tests.py @@ -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): diff --git a/tests/schema/tests.py b/tests/schema/tests.py index d6773afa00..ecc6aeb1c6 100644 --- a/tests/schema/tests.py +++ b/tests/schema/tests.py @@ -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): """ diff --git a/tests/syndication_tests/tests.py b/tests/syndication_tests/tests.py index 0563fd444c..28fe026414 100644 --- a/tests/syndication_tests/tests.py +++ b/tests/syndication_tests/tests.py @@ -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) ) diff --git a/tests/template_tests/syntax_tests/test_if_changed.py b/tests/template_tests/syntax_tests/test_if_changed.py index 2e6b2c9684..5ea6b0dcf4 100644 --- a/tests/template_tests/syntax_tests/test_if_changed.py +++ b/tests/template_tests/syntax_tests/test_if_changed.py @@ -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') diff --git a/tests/template_tests/syntax_tests/test_include.py b/tests/template_tests/syntax_tests/test_include.py index 5f92efc05a..760a801377 100644 --- a/tests/template_tests/syntax_tests/test_include.py +++ b/tests/template_tests/syntax_tests/test_include.py @@ -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') diff --git a/tests/urlpatterns_reverse/tests.py b/tests/urlpatterns_reverse/tests.py index f013d30e15..4c7c5d0465 100644 --- a/tests/urlpatterns_reverse/tests.py +++ b/tests/urlpatterns_reverse/tests.py @@ -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'], {}), diff --git a/tests/view_tests/tests/test_debug.py b/tests/view_tests/tests/test_debug.py index 1f01242af9..746d6cab8f 100644 --- a/tests/view_tests/tests/test_debug.py +++ b/tests/view_tests/tests/test_debug.py @@ -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']: diff --git a/tests/view_tests/tests/test_i18n.py b/tests/view_tests/tests/test_i18n.py index 8cd6376507..c4d9a9a986 100644 --- a/tests/view_tests/tests/test_i18n.py +++ b/tests/view_tests/tests/test_i18n.py @@ -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')