From b1e33ceceda1e75ff68c7deed8f6659683a195d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dra=C5=BEen=20Odoba=C5=A1i=C4=87?= Date: Fri, 11 Sep 2015 19:33:12 -0400 Subject: [PATCH] Fixed #23395 -- Limited line lengths to 119 characters. --- django/contrib/auth/admin.py | 6 +- .../contrib/auth/migrations/0001_initial.py | 38 +- .../0004_alter_user_username_opts.py | 11 +- .../flatpages/migrations/0001_initial.py | 12 +- .../redirects/migrations/0001_initial.py | 11 +- .../sessions/migrations/0001_initial.py | 4 +- .../contrib/sites/migrations/0001_initial.py | 4 +- .../migrations/0002_alter_domain_unique.py | 5 +- django/core/management/commands/inspectdb.py | 5 +- django/core/serializers/python.py | 22 +- django/core/serializers/xml_serializer.py | 19 +- django/db/migrations/autodetector.py | 12 +- django/db/migrations/loader.py | 5 +- django/db/models/fields/related.py | 20 +- django/forms/models.py | 8 +- django/test/client.py | 5 +- django/views/debug.py | 12 +- docs/conf.py | 10 +- setup.cfg | 2 +- tests/admin_changelist/tests.py | 17 +- tests/admin_checks/tests.py | 20 +- tests/admin_filters/models.py | 10 +- tests/admin_filters/tests.py | 53 +- tests/admin_inlines/tests.py | 112 +- tests/admin_scripts/tests.py | 88 +- tests/admin_views/admin.py | 4 +- tests/admin_views/tests.py | 215 +++- tests/admin_widgets/tests.py | 87 +- tests/aggregation/tests.py | 70 +- tests/aggregation_regress/tests.py | 182 ++- tests/auth_tests/test_middleware.py | 3 +- tests/backends/tests.py | 40 +- tests/cache/tests.py | 3 +- tests/contenttypes_tests/tests.py | 10 +- tests/createsuperuser/tests.py | 5 +- tests/custom_columns/tests.py | 3 +- tests/db_typecasts/tests.py | 6 +- tests/expressions_case/tests.py | 19 +- tests/extra_regress/tests.py | 112 +- tests/file_uploads/tests.py | 20 +- tests/fixtures/tests.py | 273 +++- tests/fixtures_regress/tests.py | 58 +- .../forms_tests/tests/test_error_messages.py | 16 +- tests/forms_tests/tests/test_fields.py | 319 ++++- tests/forms_tests/tests/test_forms.py | 1093 +++++++++++++---- tests/forms_tests/tests/test_formsets.py | 203 ++- tests/forms_tests/tests/test_media.py | 294 +++-- tests/forms_tests/tests/test_regressions.py | 95 +- tests/forms_tests/tests/test_utils.py | 49 +- tests/forms_tests/tests/test_validators.py | 6 +- tests/forms_tests/tests/test_widgets.py | 36 +- tests/forms_tests/tests/tests.py | 87 +- tests/generic_inline_admin/tests.py | 89 +- tests/generic_relations/tests.py | 57 +- tests/generic_views/test_dates.py | 55 +- tests/generic_views/urls.py | 7 +- tests/gis_tests/distapp/tests.py | 2 +- tests/i18n/test_extraction.py | 54 +- tests/i18n/tests.py | 413 ++++++- tests/inspectdb/tests.py | 5 +- tests/introspection/tests.py | 10 +- .../test_relative_fields.py | 33 +- tests/lookup/tests.py | 12 +- tests/m2m_through/models.py | 19 +- tests/m2m_through_regress/tests.py | 20 +- tests/mail/tests.py | 160 ++- tests/many_to_one/tests.py | 10 +- tests/middleware_exceptions/tests.py | 60 +- tests/migrations/test_autodetector.py | 5 +- tests/migrations/test_commands.py | 9 +- tests/migrations/test_graph.py | 16 +- tests/migrations/test_operations.py | 23 +- tests/migrations/test_optimizer.py | 16 +- tests/migrations/test_state.py | 5 +- tests/migrations/test_writer.py | 4 +- tests/model_fields/test_uuid.py | 5 +- tests/model_forms/tests.py | 159 ++- tests/model_formsets/tests.py | 450 +++++-- tests/model_formsets_regress/tests.py | 5 +- tests/model_meta/tests.py | 13 +- tests/modeladmin/models.py | 3 +- tests/modeladmin/tests.py | 15 +- tests/multiple_database/tests.py | 358 ++++-- tests/nested_foreign_keys/tests.py | 10 +- tests/or_lookups/tests.py | 5 +- .../array_index_migrations/0001_initial.py | 4 +- tests/postgres_tests/test_array.py | 14 +- tests/postgres_tests/test_ranges.py | 3 +- tests/prefetch_related/tests.py | 43 +- tests/queries/tests.py | 56 +- tests/raw_query/tests.py | 31 +- tests/requests/tests.py | 21 +- tests/schema/tests.py | 14 +- tests/select_related/tests.py | 6 +- tests/select_related_regress/tests.py | 7 +- tests/serializers/tests.py | 2 +- tests/sites_framework/tests.py | 5 +- tests/syndication_tests/tests.py | 29 +- .../template_tests/filter_tests/test_date.py | 4 +- .../filter_tests/test_random.py | 8 +- .../filter_tests/test_timesince.py | 16 +- .../filter_tests/test_timeuntil.py | 8 +- .../filter_tests/test_truncatewords.py | 13 +- .../filter_tests/test_urlize.py | 2 +- .../filter_tests/test_urlizetrunc.py | 2 +- .../syntax_tests/test_extends.py | 4 +- tests/template_tests/syntax_tests/test_for.py | 4 +- .../syntax_tests/test_if_changed.py | 4 +- tests/template_tests/syntax_tests/test_url.py | 4 +- tests/template_tests/templatetags/custom.py | 4 +- .../template_tests/templatetags/inclusion.py | 49 +- tests/template_tests/test_custom.py | 5 +- tests/template_tests/test_extends.py | 17 +- tests/template_tests/test_nodelist.py | 18 +- tests/test_client/tests.py | 4 +- tests/test_client/views.py | 8 +- tests/test_client_regress/tests.py | 58 +- tests/test_runner/runner.py | 3 +- tests/test_utils/tests.py | 29 +- tests/timezones/tests.py | 36 +- tests/urlpatterns_reverse/namespace_urls.py | 5 +- tests/urlpatterns_reverse/tests.py | 199 ++- .../management/commands/optparse_cmd.py | 4 +- tests/utils_tests/test_datetime_safe.py | 20 +- tests/utils_tests/test_feedgenerator.py | 5 +- tests/utils_tests/test_html.py | 10 +- tests/utils_tests/test_jslex.py | 32 +- tests/utils_tests/test_lorem_ipsum.py | 14 +- tests/utils_tests/test_timezone.py | 4 +- tests/view_tests/urls.py | 6 +- 130 files changed, 5259 insertions(+), 1501 deletions(-) diff --git a/django/contrib/auth/admin.py b/django/contrib/auth/admin.py index 4296a703aa..76345e92f5 100644 --- a/django/contrib/auth/admin.py +++ b/django/contrib/auth/admin.py @@ -83,7 +83,11 @@ class UserAdmin(admin.ModelAdmin): def get_urls(self): return [ - url(r'^(.+)/password/$', self.admin_site.admin_view(self.user_change_password), name='auth_user_password_change'), + url( + r'^(.+)/password/$', + self.admin_site.admin_view(self.user_change_password), + name='auth_user_password_change', + ), ] + super(UserAdmin, self).get_urls() def lookup_allowed(self, lookup, value): diff --git a/django/contrib/auth/migrations/0001_initial.py b/django/contrib/auth/migrations/0001_initial.py index fcc9d05318..7df5603879 100644 --- a/django/contrib/auth/migrations/0001_initial.py +++ b/django/contrib/auth/migrations/0001_initial.py @@ -58,16 +58,42 @@ class Migration(migrations.Migration): ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(default=timezone.now, verbose_name='last login')), - ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), - ('username', models.CharField(help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', unique=True, max_length=30, verbose_name='username', validators=[validators.RegexValidator('^[\\w.@+-]+$', 'Enter a valid username.', 'invalid')])), + ('is_superuser', models.BooleanField( + default=False, + help_text='Designates that this user has all permissions without explicitly assigning them.', + verbose_name='superuser status' + )), + ('username', models.CharField( + help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', unique=True, + max_length=30, verbose_name='username', + validators=[validators.RegexValidator('^[\\w.@+-]+$', 'Enter a valid username.', 'invalid')] + )), ('first_name', models.CharField(max_length=30, verbose_name='first name', blank=True)), ('last_name', models.CharField(max_length=30, verbose_name='last name', blank=True)), ('email', models.EmailField(max_length=75, verbose_name='email address', blank=True)), - ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), - ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), + ('is_staff', models.BooleanField( + default=False, help_text='Designates whether the user can log into this admin site.', + verbose_name='staff status' + )), + ('is_active', models.BooleanField( + default=True, verbose_name='active', help_text=( + 'Designates whether this user should be treated as active. Unselect this instead of deleting ' + 'accounts.' + ) + )), ('date_joined', models.DateTimeField(default=timezone.now, verbose_name='date joined')), - ('groups', models.ManyToManyField(to='auth.Group', verbose_name='groups', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user')), - ('user_permissions', models.ManyToManyField(to='auth.Permission', verbose_name='user permissions', blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user')), + ('groups', models.ManyToManyField( + to='auth.Group', verbose_name='groups', blank=True, related_name='user_set', + related_query_name='user', help_text=( + 'The groups this user belongs to. A user will get all permissions granted to each of their ' + 'groups.' + ) + )), + ('user_permissions', models.ManyToManyField( + to='auth.Permission', verbose_name='user permissions', blank=True, + help_text='Specific permissions for this user.', related_name='user_set', + related_query_name='user') + ), ], options={ 'swappable': 'AUTH_USER_MODEL', diff --git a/django/contrib/auth/migrations/0004_alter_user_username_opts.py b/django/contrib/auth/migrations/0004_alter_user_username_opts.py index 0f7bfdf3a7..151cda7b74 100644 --- a/django/contrib/auth/migrations/0004_alter_user_username_opts.py +++ b/django/contrib/auth/migrations/0004_alter_user_username_opts.py @@ -16,6 +16,15 @@ class Migration(migrations.Migration): migrations.AlterField( model_name='user', name='username', - field=models.CharField(error_messages={'unique': 'A user with that username already exists.'}, max_length=30, validators=[django.core.validators.RegexValidator('^[\\w.@+-]+$', 'Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.', 'invalid')], help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', unique=True, verbose_name='username'), + field=models.CharField( + error_messages={'unique': 'A user with that username already exists.'}, max_length=30, + validators=[django.core.validators.RegexValidator( + '^[\\w.@+-]+$', + 'Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.', + 'invalid' + )], + help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', + unique=True, verbose_name='username' + ), ), ] diff --git a/django/contrib/flatpages/migrations/0001_initial.py b/django/contrib/flatpages/migrations/0001_initial.py index 3281e54bf6..13e417b41b 100644 --- a/django/contrib/flatpages/migrations/0001_initial.py +++ b/django/contrib/flatpages/migrations/0001_initial.py @@ -19,8 +19,16 @@ class Migration(migrations.Migration): ('title', models.CharField(max_length=200, verbose_name='title')), ('content', models.TextField(verbose_name='content', blank=True)), ('enable_comments', models.BooleanField(default=False, verbose_name='enable comments')), - ('template_name', models.CharField(help_text="Example: 'flatpages/contact_page.html'. If this isn't provided, the system will use 'flatpages/default.html'.", max_length=70, verbose_name='template name', blank=True)), - ('registration_required', models.BooleanField(default=False, help_text='If this is checked, only logged-in users will be able to view the page.', verbose_name='registration required')), + ('template_name', models.CharField( + help_text=( + "Example: 'flatpages/contact_page.html'. If this isn't provided, the system will use " + "'flatpages/default.html'." + ), max_length=70, verbose_name='template name', blank=True + )), + ('registration_required', models.BooleanField( + default=False, help_text='If this is checked, only logged-in users will be able to view the page.', + verbose_name='registration required' + )), ('sites', models.ManyToManyField(to='sites.Site', verbose_name='sites')), ], options={ diff --git a/django/contrib/redirects/migrations/0001_initial.py b/django/contrib/redirects/migrations/0001_initial.py index cfd5dcf5a3..905ec266aa 100644 --- a/django/contrib/redirects/migrations/0001_initial.py +++ b/django/contrib/redirects/migrations/0001_initial.py @@ -21,8 +21,15 @@ class Migration(migrations.Migration): on_delete=models.CASCADE, verbose_name='site', )), - ('old_path', models.CharField(help_text="This should be an absolute path, excluding the domain name. Example: '/events/search/'.", max_length=200, verbose_name='redirect from', db_index=True)), - ('new_path', models.CharField(help_text="This can be either an absolute path (as above) or a full URL starting with 'http://'.", max_length=200, verbose_name='redirect to', blank=True)), + ('old_path', models.CharField( + help_text=( + "This should be an absolute path, excluding the domain name. Example: '/events/search/'." + ), max_length=200, verbose_name='redirect from', db_index=True + )), + ('new_path', models.CharField( + help_text="This can be either an absolute path (as above) or a full URL starting with 'http://'.", + max_length=200, verbose_name='redirect to', blank=True + )), ], options={ 'ordering': ('old_path',), diff --git a/django/contrib/sessions/migrations/0001_initial.py b/django/contrib/sessions/migrations/0001_initial.py index 0a4acc9382..e9fd627b79 100644 --- a/django/contrib/sessions/migrations/0001_initial.py +++ b/django/contrib/sessions/migrations/0001_initial.py @@ -14,7 +14,9 @@ class Migration(migrations.Migration): migrations.CreateModel( name='Session', fields=[ - ('session_key', models.CharField(max_length=40, serialize=False, verbose_name='session key', primary_key=True)), + ('session_key', models.CharField( + max_length=40, serialize=False, verbose_name='session key', primary_key=True + )), ('session_data', models.TextField(verbose_name='session data')), ('expire_date', models.DateTimeField(verbose_name='expire date', db_index=True)), ], diff --git a/django/contrib/sites/migrations/0001_initial.py b/django/contrib/sites/migrations/0001_initial.py index 84ad0cd408..b1803682ae 100644 --- a/django/contrib/sites/migrations/0001_initial.py +++ b/django/contrib/sites/migrations/0001_initial.py @@ -15,7 +15,9 @@ class Migration(migrations.Migration): name='Site', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), - ('domain', models.CharField(max_length=100, verbose_name='domain name', validators=[_simple_domain_name_validator])), + ('domain', models.CharField( + max_length=100, verbose_name='domain name', validators=[_simple_domain_name_validator] + )), ('name', models.CharField(max_length=50, verbose_name='display name')), ], options={ diff --git a/django/contrib/sites/migrations/0002_alter_domain_unique.py b/django/contrib/sites/migrations/0002_alter_domain_unique.py index e7f414fb5c..468718cde3 100644 --- a/django/contrib/sites/migrations/0002_alter_domain_unique.py +++ b/django/contrib/sites/migrations/0002_alter_domain_unique.py @@ -15,6 +15,9 @@ class Migration(migrations.Migration): migrations.AlterField( model_name='site', name='domain', - field=models.CharField(max_length=100, unique=True, validators=[django.contrib.sites.models._simple_domain_name_validator], verbose_name='domain name'), + field=models.CharField( + max_length=100, unique=True, validators=[django.contrib.sites.models._simple_domain_name_validator], + verbose_name='domain name' + ), ), ] diff --git a/django/core/management/commands/inspectdb.py b/django/core/management/commands/inspectdb.py index 3e0a9e5df3..9b9e350f4b 100644 --- a/django/core/management/commands/inspectdb.py +++ b/django/core/management/commands/inspectdb.py @@ -92,7 +92,10 @@ class Command(BaseCommand): extra_params['unique'] = True if is_relation: - rel_to = "self" if relations[column_name][1] == table_name else table2model(relations[column_name][1]) + rel_to = ( + "self" if relations[column_name][1] == table_name + else table2model(relations[column_name][1]) + ) if rel_to in known_models: field_type = 'ForeignKey(%s' % rel_to else: diff --git a/django/core/serializers/python.py b/django/core/serializers/python.py index ff506d50cb..b64169bb62 100644 --- a/django/core/serializers/python.py +++ b/django/core/serializers/python.py @@ -124,14 +124,15 @@ def Deserializer(object_list, **options): # Handle M2M relations if field.remote_field and isinstance(field.remote_field, models.ManyToManyRel): - if hasattr(field.remote_field.model._default_manager, 'get_by_natural_key'): + model = field.remote_field.model + if hasattr(model._default_manager, 'get_by_natural_key'): def m2m_convert(value): if hasattr(value, '__iter__') and not isinstance(value, six.text_type): - return field.remote_field.model._default_manager.db_manager(db).get_by_natural_key(*value).pk + return model._default_manager.db_manager(db).get_by_natural_key(*value).pk else: - return force_text(field.remote_field.model._meta.pk.to_python(value), strings_only=True) + return force_text(model._meta.pk.to_python(value), strings_only=True) else: - m2m_convert = lambda v: force_text(field.remote_field.model._meta.pk.to_python(v), strings_only=True) + m2m_convert = lambda v: force_text(model._meta.pk.to_python(v), strings_only=True) try: m2m_data[field.name] = [] @@ -142,21 +143,24 @@ def Deserializer(object_list, **options): # Handle FK fields elif field.remote_field and isinstance(field.remote_field, models.ManyToOneRel): + model = field.remote_field.model if field_value is not None: try: - if hasattr(field.remote_field.model._default_manager, 'get_by_natural_key'): + default_manager = model._default_manager + field_name = field.remote_field.field_name + if hasattr(default_manager, 'get_by_natural_key'): if hasattr(field_value, '__iter__') and not isinstance(field_value, six.text_type): - obj = field.remote_field.model._default_manager.db_manager(db).get_by_natural_key(*field_value) + obj = default_manager.db_manager(db).get_by_natural_key(*field_value) value = getattr(obj, field.remote_field.field_name) # If this is a natural foreign key to an object that # has a FK/O2O as the foreign key, use the FK value - if field.remote_field.model._meta.pk.remote_field: + if model._meta.pk.remote_field: value = value.pk else: - value = field.remote_field.model._meta.get_field(field.remote_field.field_name).to_python(field_value) + value = model._meta.get_field(field_name).to_python(field_value) data[field.attname] = value else: - data[field.attname] = field.remote_field.model._meta.get_field(field.remote_field.field_name).to_python(field_value) + data[field.attname] = model._meta.get_field(field_name).to_python(field_value) except Exception as e: raise base.DeserializationError.WithData(e, d['model'], d.get('pk'), field_value) else: diff --git a/django/core/serializers/xml_serializer.py b/django/core/serializers/xml_serializer.py index 9bddda46da..44d745d55d 100644 --- a/django/core/serializers/xml_serializer.py +++ b/django/core/serializers/xml_serializer.py @@ -236,12 +236,13 @@ class Deserializer(base.Deserializer): if node.getElementsByTagName('None'): return None else: - if hasattr(field.remote_field.model._default_manager, 'get_by_natural_key'): + model = field.remote_field.model + if hasattr(model._default_manager, 'get_by_natural_key'): keys = node.getElementsByTagName('natural') if keys: # If there are 'natural' subelements, it must be a natural key field_value = [getInnerText(k).strip() for k in keys] - obj = field.remote_field.model._default_manager.db_manager(self.db).get_by_natural_key(*field_value) + obj = model._default_manager.db_manager(self.db).get_by_natural_key(*field_value) obj_pk = getattr(obj, field.remote_field.field_name) # If this is a natural foreign key to an object that # has a FK/O2O as the foreign key, use the FK value @@ -250,29 +251,31 @@ class Deserializer(base.Deserializer): else: # Otherwise, treat like a normal PK field_value = getInnerText(node).strip() - obj_pk = field.remote_field.model._meta.get_field(field.remote_field.field_name).to_python(field_value) + obj_pk = model._meta.get_field(field.remote_field.field_name).to_python(field_value) return obj_pk else: field_value = getInnerText(node).strip() - return field.remote_field.model._meta.get_field(field.remote_field.field_name).to_python(field_value) + return model._meta.get_field(field.remote_field.field_name).to_python(field_value) def _handle_m2m_field_node(self, node, field): """ Handle a node for a ManyToManyField. """ - if hasattr(field.remote_field.model._default_manager, 'get_by_natural_key'): + model = field.remote_field.model + default_manager = model._default_manager + if hasattr(default_manager, 'get_by_natural_key'): def m2m_convert(n): keys = n.getElementsByTagName('natural') if keys: # If there are 'natural' subelements, it must be a natural key field_value = [getInnerText(k).strip() for k in keys] - obj_pk = field.remote_field.model._default_manager.db_manager(self.db).get_by_natural_key(*field_value).pk + obj_pk = default_manager.db_manager(self.db).get_by_natural_key(*field_value).pk else: # Otherwise, treat like a normal PK value. - obj_pk = field.remote_field.model._meta.pk.to_python(n.getAttribute('pk')) + obj_pk = model._meta.pk.to_python(n.getAttribute('pk')) return obj_pk else: - m2m_convert = lambda n: field.remote_field.model._meta.pk.to_python(n.getAttribute('pk')) + m2m_convert = lambda n: model._meta.pk.to_python(n.getAttribute('pk')) return [m2m_convert(c) for c in node.getElementsByTagName("object")] def _get_model_from_node(self, node, attr): diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py index b2181818ea..513bb543d1 100644 --- a/django/db/migrations/autodetector.py +++ b/django/db/migrations/autodetector.py @@ -468,7 +468,11 @@ class MigrationAutodetector(object): ) ) self.renamed_models[app_label, model_name] = rem_model_name - self.renamed_models_rel['%s.%s' % (rem_model_state.app_label, rem_model_state.name)] = '%s.%s' % (model_state.app_label, model_state.name) + renamed_models_rel_key = '%s.%s' % (rem_model_state.app_label, rem_model_state.name) + self.renamed_models_rel[renamed_models_rel_key] = '%s.%s' % ( + model_state.app_label, + model_state.name, + ) self.old_model_keys.remove((rem_app_label, rem_model_name)) self.old_model_keys.append((app_label, model_name)) break @@ -505,7 +509,8 @@ class MigrationAutodetector(object): related_fields[field.name] = field # through will be none on M2Ms on swapped-out models; # we can treat lack of through as auto_created=True, though. - if getattr(field.remote_field, "through", None) and not field.remote_field.through._meta.auto_created: + if (getattr(field.remote_field, "through", None) + and not field.remote_field.through._meta.auto_created): related_fields[field.name] = field for field in model_opts.local_many_to_many: if field.remote_field.model: @@ -681,7 +686,8 @@ class MigrationAutodetector(object): related_fields[field.name] = field # through will be none on M2Ms on swapped-out models; # we can treat lack of through as auto_created=True, though. - if getattr(field.remote_field, "through", None) and not field.remote_field.through._meta.auto_created: + if (getattr(field.remote_field, "through", None) + and not field.remote_field.through._meta.auto_created): related_fields[field.name] = field for field in model._meta.local_many_to_many: if field.remote_field.model: diff --git a/django/db/migrations/loader.py b/django/db/migrations/loader.py index 93aa8e61f7..fac33c3ce7 100644 --- a/django/db/migrations/loader.py +++ b/django/db/migrations/loader.py @@ -119,7 +119,10 @@ class MigrationLoader(object): if hasattr(migration_module.Migration, "forwards"): south_style_migrations = True break - self.disk_migrations[app_config.label, migration_name] = migration_module.Migration(migration_name, app_config.label) + self.disk_migrations[app_config.label, migration_name] = migration_module.Migration( + migration_name, + app_config.label, + ) if south_style_migrations: self.unmigrated_apps.add(app_config.label) diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index 609d262127..2e2ec38335 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -346,7 +346,10 @@ class RelatedField(Field): return None def set_attributes_from_rel(self): - self.name = self.name or (self.remote_field.model._meta.model_name + '_' + self.remote_field.model._meta.pk.name) + self.name = ( + self.name or + (self.remote_field.model._meta.model_name + '_' + self.remote_field.model._meta.pk.name) + ) if self.verbose_name is None: self.verbose_name = self.remote_field.model._meta.verbose_name self.remote_field.set_field_name() @@ -830,7 +833,9 @@ def create_foreign_related_manager(superclass, rel): if self.field.get_local_related_value(obj) == val: old_ids.add(obj.pk) else: - raise self.field.remote_field.model.DoesNotExist("%r is not related to %r." % (obj, self.instance)) + raise self.field.remote_field.model.DoesNotExist( + "%r is not related to %r." % (obj, self.instance) + ) self._clear(self.filter(pk__in=old_ids), bulk) remove.alters_data = True @@ -955,7 +960,8 @@ def create_many_related_manager(superclass, rel, reverse): self.core_filters = {} for lh_field, rh_field in self.source_field.related_fields: - self.core_filters['%s__%s' % (self.query_field_name, rh_field.name)] = getattr(instance, rh_field.attname) + core_filter_key = '%s__%s' % (self.query_field_name, rh_field.name) + self.core_filters[core_filter_key] = getattr(instance, rh_field.attname) self.related_val = self.source_field.get_foreign_related_value(instance) if None in self.related_val: @@ -1688,7 +1694,10 @@ class ForeignObject(RelatedField): if isinstance(self.remote_field.model, six.string_types): kwargs['to'] = self.remote_field.model else: - kwargs['to'] = "%s.%s" % (self.remote_field.model._meta.app_label, self.remote_field.model._meta.object_name) + kwargs['to'] = "%s.%s" % ( + self.remote_field.model._meta.app_label, + self.remote_field.model._meta.object_name, + ) # If swappable is True, then see if we're actually pointing to the target # of a swap. swappable_setting = self.swappable_setting @@ -1999,7 +2008,8 @@ class ForeignKey(ForeignObject): kwargs['db_constraint'] = self.db_constraint # Rel needs more work. to_meta = getattr(self.remote_field.model, "_meta", None) - if self.remote_field.field_name and (not to_meta or (to_meta.pk and self.remote_field.field_name != to_meta.pk.name)): + if self.remote_field.field_name and ( + not to_meta or (to_meta.pk and self.remote_field.field_name != to_meta.pk.name)): kwargs['to_field'] = self.remote_field.field_name return name, path, args, kwargs diff --git a/django/forms/models.py b/django/forms/models.py index 651749a356..0fba08855f 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -788,8 +788,12 @@ class BaseModelFormSet(BaseFormSet): # True, so check for that as well. def pk_is_not_editable(pk): - return ((not pk.editable) or (pk.auto_created or isinstance(pk, AutoField)) - or (pk.remote_field and pk.remote_field.parent_link and pk_is_not_editable(pk.remote_field.model._meta.pk))) + return ( + (not pk.editable) or (pk.auto_created or isinstance(pk, AutoField)) or ( + pk.remote_field and pk.remote_field.parent_link + and pk_is_not_editable(pk.remote_field.model._meta.pk) + ) + ) if pk_is_not_editable(pk) or pk.name not in form.fields: if form.is_bound: # If we're adding the related instance, ignore its primary key diff --git a/django/test/client.py b/django/test/client.py index 8d46ea629a..a1ee223fdb 100644 --- a/django/test/client.py +++ b/django/test/client.py @@ -655,7 +655,10 @@ class Client(RequestFactory): def _parse_json(self, response, **extra): if 'application/json' not in response.get('Content-Type'): - raise ValueError('Content-Type header is "{0}", not "application/json"'.format(response.get('Content-Type'))) + raise ValueError( + 'Content-Type header is "{0}", not "application/json"' + .format(response.get('Content-Type')) + ) return json.loads(response.content.decode(), **extra) def _handle_redirects(self, response, **extra): diff --git a/django/views/debug.py b/django/views/debug.py index 55357b3344..b6201ab54a 100644 --- a/django/views/debug.py +++ b/django/views/debug.py @@ -862,12 +862,12 @@ Installed Middleware: {% if postmortem %}Django tried loading these templates, in this order: {% for entry in postmortem %} Using engine {{ entry.backend.name }}: -{% if entry.tried %}{% for attempt in entry.tried %} * {{ attempt.0.loader_name }}: {{ attempt.0.name }} ({{ attempt.1 }}) +{% if entry.tried %}{% for attempt in entry.tried %}""" +""" * {{ attempt.0.loader_name }}: {{ attempt.0.name }} ({{ attempt.1 }}) {% endfor %}{% else %} This engine did not provide a list of tried templates. {% endif %}{% endfor %} {% else %}No templates were found because your 'TEMPLATES' setting is not configured. -{% endif %} -{% endif %}{% if template_info %} +{% endif %}{% endif %}{% if template_info %} Template error: In template {{ template_info.name }}, error at line {{ template_info.line }} {{ template_info.message }}""" @@ -1044,7 +1044,8 @@ Exception Value: {{ exception_value|force_escape }} """) -TECHNICAL_500_TEXT_TEMPLATE = ("""{% firstof exception_type 'Report' %}{% if request %} at {{ request.path_info }}{% endif %} +TECHNICAL_500_TEXT_TEMPLATE = ("""""" +"""{% firstof exception_type 'Report' %}{% if request %} at {{ request.path_info }}{% endif %} {% firstof exception_value 'No exception message supplied' %} {% if request %} Request Method: {{ request.META.REQUEST_METHOD }} @@ -1062,7 +1063,8 @@ Installed Middleware: {% if postmortem %}Django tried loading these templates, in this order: {% for entry in postmortem %} Using engine {{ entry.backend.name }}: -{% if entry.tried %}{% for attempt in entry.tried %} * {{ attempt.0.loader_name }}: {{ attempt.0.name }} ({{ attempt.1 }}) +{% if entry.tried %}{% for attempt in entry.tried %}""" +""" * {{ attempt.0.loader_name }}: {{ attempt.0.name }} ({{ attempt.1 }}) {% endfor %}{% else %} This engine did not provide a list of tried templates. {% endif %}{% endfor %} {% else %}No templates were found because your 'TEMPLATES' setting is not configured. diff --git a/docs/conf.py b/docs/conf.py index a8006e2f94..10caf0ce8a 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -272,9 +272,13 @@ latex_documents = [ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [ - ('ref/django-admin', 'django-admin', 'Utility script for the Django Web framework', ['Django Software Foundation'], 1), -] +man_pages = [( + 'ref/django-admin', + 'django-admin', + 'Utility script for the Django Web framework', + ['Django Software Foundation'], + 1 +), ] # -- Options for Texinfo output ------------------------------------------------ diff --git a/setup.cfg b/setup.cfg index 64b31f97d5..a0b89d02e5 100644 --- a/setup.cfg +++ b/setup.cfg @@ -4,7 +4,7 @@ install-script = scripts/rpm-install.sh [flake8] exclude = build,.git,./django/utils/lru_cache.py,./django/utils/six.py,./django/conf/app_template/*,./django/dispatch/weakref_backports.py,./tests/.env,./xmlrunner,tests/view_tests/tests/py3_test_debug.py -ignore = E123,E128,E402,E501,W503,E731,W601 +ignore = E123,E128,E402,W503,E731,W601 max-line-length = 119 [isort] diff --git a/tests/admin_changelist/tests.py b/tests/admin_changelist/tests.py index 5e773bcb9a..005aad6a3b 100644 --- a/tests/admin_changelist/tests.py +++ b/tests/admin_changelist/tests.py @@ -227,12 +227,23 @@ class ChangeListTests(TestCase): context = Context({'cl': cl}) table_output = template.render(context) # make sure that hidden fields are in the correct place - hiddenfields_div = '
' % new_child.id + hiddenfields_div = ( + '
' + '' + '
' + ) % new_child.id self.assertInHTML(hiddenfields_div, table_output, msg_prefix='Failed to find hidden fields') # make sure that list editable fields are rendered in divs correctly - editable_name_field = '' - self.assertInHTML('%s' % editable_name_field, table_output, msg_prefix='Failed to find "name" list_editable field') + editable_name_field = ( + '' + ) + self.assertInHTML( + '%s' % editable_name_field, + table_output, + msg_prefix='Failed to find "name" list_editable field', + ) def test_result_list_editable(self): """ diff --git a/tests/admin_checks/tests.py b/tests/admin_checks/tests.py index 4544ddd382..280af17e1f 100644 --- a/tests/admin_checks/tests.py +++ b/tests/admin_checks/tests.py @@ -340,7 +340,10 @@ class SystemChecksTestCase(SimpleTestCase): self.assertEqual(errors, expected) def test_generic_inline_model_admin_non_gfk_ct_field(self): - "A GenericInlineModelAdmin raises problems if the ct_field points to a field that isn't part of a GenericForeignKey" + """ + A GenericInlineModelAdmin raises problems if the ct_field points to a + field that isn't part of a GenericForeignKey. + """ class InfluenceInline(GenericStackedInline): model = Influence ct_field = 'name' @@ -351,7 +354,8 @@ class SystemChecksTestCase(SimpleTestCase): errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( - "'admin_checks.Influence' has no GenericForeignKey using content type field 'name' and object ID field 'object_id'.", + "'admin_checks.Influence' has no GenericForeignKey using " + "content type field 'name' and object ID field 'object_id'.", hint=None, obj=InfluenceInline, id='admin.E304', @@ -360,7 +364,10 @@ class SystemChecksTestCase(SimpleTestCase): self.assertEqual(errors, expected) def test_generic_inline_model_admin_non_gfk_fk_field(self): - "A GenericInlineModelAdmin raises problems if the ct_fk_field points to a field that isn't part of a GenericForeignKey" + """ + A GenericInlineModelAdmin raises problems if the ct_fk_field points to + a field that isn't part of a GenericForeignKey. + """ class InfluenceInline(GenericStackedInline): model = Influence ct_fk_field = 'name' @@ -371,7 +378,8 @@ class SystemChecksTestCase(SimpleTestCase): errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( - "'admin_checks.Influence' has no GenericForeignKey using content type field 'content_type' and object ID field 'name'.", + "'admin_checks.Influence' has no GenericForeignKey using " + "content type field 'content_type' and object ID field 'name'.", hint=None, obj=InfluenceInline, id='admin.E304', @@ -389,8 +397,8 @@ class SystemChecksTestCase(SimpleTestCase): errors = RawIdNonexistingAdmin(Album, AdminSite()).check() expected = [ checks.Error( - ("The value of 'raw_id_fields[0]' refers to 'nonexisting', which is " - "not an attribute of 'admin_checks.Album'."), + "The value of 'raw_id_fields[0]' refers to 'nonexisting', " + "which is not an attribute of 'admin_checks.Album'.", hint=None, obj=RawIdNonexistingAdmin, id='admin.E002', diff --git a/tests/admin_filters/models.py b/tests/admin_filters/models.py index 9f89809349..40f25d2f30 100644 --- a/tests/admin_filters/models.py +++ b/tests/admin_filters/models.py @@ -20,10 +20,16 @@ class Book(models.Model): related_name='books_authored', blank=True, null=True, ) - contributors = models.ManyToManyField(User, verbose_name="Verbose Contributors", related_name='books_contributed', blank=True) + contributors = models.ManyToManyField( + User, + verbose_name="Verbose Contributors", + related_name='books_contributed', + blank=True, + ) is_best_seller = models.NullBooleanField(default=0) date_registered = models.DateField(null=True) - no = models.IntegerField(verbose_name='number', blank=True, null=True) # This field is intentionally 2 characters long. See #16080. + # This field name is intentionally 2 characters long (#16080). + no = models.IntegerField(verbose_name='number', blank=True, null=True) def __str__(self): return self.title diff --git a/tests/admin_filters/tests.py b/tests/admin_filters/tests.py index 5a230cd983..f17928e4b1 100644 --- a/tests/admin_filters/tests.py +++ b/tests/admin_filters/tests.py @@ -129,11 +129,25 @@ class BookAdmin(ModelAdmin): class BookAdminWithTupleBooleanFilter(BookAdmin): - list_filter = ('year', 'author', 'contributors', ('is_best_seller', BooleanFieldListFilter), 'date_registered', 'no') + list_filter = ( + 'year', + 'author', + 'contributors', + ('is_best_seller', BooleanFieldListFilter), + 'date_registered', + 'no', + ) class BookAdminWithUnderscoreLookupAndTuple(BookAdmin): - list_filter = ('year', ('author__email', AllValuesFieldListFilter), 'contributors', 'is_best_seller', 'date_registered', 'no') + list_filter = ( + 'year', + ('author__email', AllValuesFieldListFilter), + 'contributors', + 'is_best_seller', + 'date_registered', + 'no', + ) class BookAdminWithCustomQueryset(ModelAdmin): @@ -231,10 +245,22 @@ class ListFiltersTests(TestCase): self.lisa = User.objects.create_user('lisa', 'lisa@example.com') # Books - self.djangonaut_book = Book.objects.create(title='Djangonaut: an art of living', year=2009, author=self.alfred, is_best_seller=True, date_registered=self.today) - self.bio_book = Book.objects.create(title='Django: a biography', year=1999, author=self.alfred, is_best_seller=False, no=207) - self.django_book = Book.objects.create(title='The Django Book', year=None, author=self.bob, is_best_seller=None, date_registered=self.today, no=103) - self.gipsy_book = Book.objects.create(title='Gipsy guitar for dummies', year=2002, is_best_seller=True, date_registered=self.one_week_ago) + self.djangonaut_book = Book.objects.create( + title='Djangonaut: an art of living', year=2009, + author=self.alfred, is_best_seller=True, date_registered=self.today, + ) + self.bio_book = Book.objects.create( + title='Django: a biography', year=1999, author=self.alfred, + is_best_seller=False, no=207, + ) + self.django_book = Book.objects.create( + title='The Django Book', year=None, author=self.bob, + is_best_seller=None, date_registered=self.today, no=103, + ) + self.gipsy_book = Book.objects.create( + title='Gipsy guitar for dummies', year=2002, is_best_seller=True, + date_registered=self.one_week_ago, + ) self.gipsy_book.contributors = [self.bob, self.lisa] self.gipsy_book.save() @@ -247,9 +273,13 @@ class ListFiltersTests(TestCase): self.jack = Employee.objects.create(name='Jack Red', department=self.design) def get_changelist(self, request, model, modeladmin): - return ChangeList(request, model, modeladmin.list_display, modeladmin.list_display_links, - modeladmin.list_filter, modeladmin.date_hierarchy, modeladmin.search_fields, - modeladmin.list_select_related, modeladmin.list_per_page, modeladmin.list_max_show_all, modeladmin.list_editable, modeladmin) + return ChangeList( + request, model, modeladmin.list_display, + modeladmin.list_display_links, modeladmin.list_filter, + modeladmin.date_hierarchy, modeladmin.search_fields, + modeladmin.list_select_related, modeladmin.list_per_page, + modeladmin.list_max_show_all, modeladmin.list_editable, modeladmin, + ) def test_datefieldlistfilter(self): modeladmin = BookAdmin(Book, site) @@ -730,7 +760,10 @@ class ListFiltersTests(TestCase): choices = list(filterspec.choices(changelist)) self.assertEqual(choices[3]['display'], 'the 2000\'s') self.assertEqual(choices[3]['selected'], True) - self.assertEqual(choices[3]['query_string'], '?author__id__exact=%s&publication-decade=the+00s' % self.alfred.pk) + self.assertEqual( + choices[3]['query_string'], + '?author__id__exact=%s&publication-decade=the+00s' % self.alfred.pk + ) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(force_text(filterspec.title), 'Verbose Author') diff --git a/tests/admin_inlines/tests.py b/tests/admin_inlines/tests.py index 98d37a7e24..e5e4a66a3b 100644 --- a/tests/admin_inlines/tests.py +++ b/tests/admin_inlines/tests.py @@ -114,7 +114,11 @@ class TestInline(TestDataMixin, TestCase): } response = self.client.post(reverse('admin:admin_inlines_titlecollection_add'), data) # Here colspan is "4": two fields (title1 and title2), one hidden field and the delete checkbox. - self.assertContains(response, '') + self.assertContains( + response, + '' + ) def test_no_parent_callable_lookup(self): """Admin inline `readonly_field` shouldn't invoke parent ModelAdmin callable""" @@ -143,10 +147,24 @@ class TestInline(TestDataMixin, TestCase): """ response = self.client.get(reverse('admin:admin_inlines_holder4_add')) self.assertContains(response, '

Awesome stacked help text is awesome.

', 4) - self.assertContains(response, '(Awesome tabular help text is awesome.)', 1) + self.assertContains( + response, + '', + 1 + ) # ReadOnly fields response = self.client.get(reverse('admin:admin_inlines_capofamiglia_add')) - self.assertContains(response, '(Help text for ReadOnlyInline)', 1) + self.assertContains( + response, + '', + 1 + ) def test_inline_hidden_field_no_column(self): """#18263 -- Make sure hidden fields don't get a column in tabular inlines""" @@ -228,13 +246,17 @@ class TestInline(TestDataMixin, TestCase): def test_custom_get_extra_form(self): bt_head = BinaryTree.objects.create(name="Tree Head") BinaryTree.objects.create(name="First Child", parent=bt_head) - # The maximum number of forms should respect 'get_max_num' on the # ModelAdmin - max_forms_input = '' + max_forms_input = ( + '' + ) # The total number of forms will remain the same in either case - total_forms_hidden = '' - + total_forms_hidden = ( + '' + ) response = self.client.get(reverse('admin:admin_inlines_binarytree_add')) self.assertContains(response, max_forms_input % 3) self.assertContains(response, total_forms_hidden) @@ -254,10 +276,14 @@ class TestInline(TestDataMixin, TestCase): modeladmin = ModelAdmin(BinaryTree, admin_site) modeladmin.inlines = [MinNumInline] - - min_forms = '' - total_forms = '' - + min_forms = ( + '' + ) + total_forms = ( + '' + ) request = self.factory.get(reverse('admin:admin_inlines_binarytree_add')) request.user = User(username='super', is_superuser=True) response = modeladmin.changeform_view(request) @@ -282,10 +308,14 @@ class TestInline(TestDataMixin, TestCase): modeladmin = ModelAdmin(BinaryTree, admin_site) modeladmin.inlines = [MinNumInline] - - min_forms = '' - total_forms = '' - + min_forms = ( + '' + ) + total_forms = ( + '' + ) request = self.factory.get(reverse('admin:admin_inlines_binarytree_add')) request.user = User(username='super', is_superuser=True) response = modeladmin.changeform_view(request) @@ -300,21 +330,33 @@ class TestInline(TestDataMixin, TestCase): def test_inline_nonauto_noneditable_pk(self): response = self.client.get(reverse('admin:admin_inlines_author_add')) - self.assertContains(response, - '', - html=True) - self.assertContains(response, - '', - html=True) + self.assertContains( + response, + '', + html=True + ) + self.assertContains( + response, + '', + html=True + ) def test_inline_editable_pk(self): response = self.client.get(reverse('admin:admin_inlines_author_add')) - self.assertContains(response, - '', - html=True, count=1) - self.assertContains(response, - '', - html=True, count=1) + self.assertContains( + response, + '', + html=True, count=1 + ) + self.assertContains( + response, + '', + html=True, count=1 + ) def test_stacked_inline_edit_form_contains_has_original_class(self): holder = Holder.objects.create(dummy=1) @@ -585,8 +627,12 @@ class TestInlinePermissions(TestCase): self.assertContains(response, 'Add another Author\\u002Dbook relationship') self.assertContains(response, '', html=True) - self.assertContains(response, '' % self.author_book_auto_m2m_intermediate_id, html=True) + self.assertContains( + response, + '' % self.author_book_auto_m2m_intermediate_id, + html=True + ) self.assertContains(response, 'id="id_Author_books-0-DELETE"') def test_inline_change_fk_add_perm(self): @@ -597,8 +643,12 @@ class TestInlinePermissions(TestCase): self.assertContains(response, '

Inner2s

') self.assertContains(response, 'Add another Inner2') # 3 extra forms only, not the existing instance form - self.assertContains(response, '', html=True) + self.assertContains( + response, + '', + html=True + ) self.assertNotContains(response, '' % self.inner2_id, html=True) diff --git a/tests/admin_scripts/tests.py b/tests/admin_scripts/tests.py index 397856912e..4e976d89fd 100644 --- a/tests/admin_scripts/tests.py +++ b/tests/admin_scripts/tests.py @@ -964,21 +964,36 @@ class ManageAlternateSettings(AdminScriptTestCase): "alternate: manage.py can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=alternate_settings'] out, err = self.run_manage(args) - self.assertOutput(out, "EXECUTE: noargs_command options=[('no_color', False), ('pythonpath', None), ('settings', 'alternate_settings'), ('traceback', False), ('verbosity', 1)]") + self.assertOutput( + out, + "EXECUTE: noargs_command options=[('no_color', False), " + "('pythonpath', None), ('settings', 'alternate_settings'), " + "('traceback', False), ('verbosity', 1)]" + ) self.assertNoOutput(err) def test_custom_command_with_environment(self): "alternate: manage.py can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_manage(args, 'alternate_settings') - self.assertOutput(out, "EXECUTE: noargs_command options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', False), ('verbosity', 1)]") + self.assertOutput( + out, + "EXECUTE: noargs_command options=[('no_color', False), " + "('pythonpath', None), ('settings', None), ('traceback', False), " + "('verbosity', 1)]" + ) self.assertNoOutput(err) def test_custom_command_output_color(self): "alternate: manage.py output syntax color can be deactivated with the `--no-color` option" args = ['noargs_command', '--no-color', '--settings=alternate_settings'] out, err = self.run_manage(args) - self.assertOutput(out, "EXECUTE: noargs_command options=[('no_color', True), ('pythonpath', None), ('settings', 'alternate_settings'), ('traceback', False), ('verbosity', 1)]") + self.assertOutput( + out, + "EXECUTE: noargs_command options=[('no_color', True), " + "('pythonpath', None), ('settings', 'alternate_settings'), " + "('traceback', False), ('verbosity', 1)]" + ) self.assertNoOutput(err) @@ -1660,7 +1675,12 @@ class CommandTypes(AdminScriptTestCase): args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(err) - self.assertOutput(out, "EXECUTE: noargs_command options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', False), ('verbosity', 1)]") + self.assertOutput( + out, + "EXECUTE: noargs_command options=[('no_color', False), " + "('pythonpath', None), ('settings', None), ('traceback', False), " + "('verbosity', 1)]" + ) def test_noargs_with_args(self): "NoArg Commands raise an error if an argument is provided" @@ -1674,7 +1694,11 @@ class CommandTypes(AdminScriptTestCase): out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=") - self.assertOutput(out, ", options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', False), ('verbosity', 1)]") + self.assertOutput( + out, + ", options=[('no_color', False), ('pythonpath', None), " + "('settings', None), ('traceback', False), ('verbosity', 1)]" + ) def test_app_command_no_apps(self): "User AppCommands raise an error when no app name is provided" @@ -1688,9 +1712,17 @@ class CommandTypes(AdminScriptTestCase): out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=") - self.assertOutput(out, ", options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', False), ('verbosity', 1)]") + self.assertOutput( + out, + ", options=[('no_color', False), ('pythonpath', None), " + "('settings', None), ('traceback', False), ('verbosity', 1)]" + ) self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.contenttypes, options=") - self.assertOutput(out, ", options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', False), ('verbosity', 1)]") + self.assertOutput( + out, + ", options=[('no_color', False), ('pythonpath', None), " + "('settings', None), ('traceback', False), ('verbosity', 1)]" + ) def test_app_command_invalid_app_label(self): "User AppCommands can execute when a single app name is provided" @@ -1709,7 +1741,11 @@ class CommandTypes(AdminScriptTestCase): args = ['label_command', 'testlabel'] out, err = self.run_manage(args) self.assertNoOutput(err) - self.assertOutput(out, "EXECUTE:LabelCommand label=testlabel, options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', False), ('verbosity', 1)]") + self.assertOutput( + out, + "EXECUTE:LabelCommand label=testlabel, options=[('no_color', False), " + "('pythonpath', None), ('settings', None), ('traceback', False), ('verbosity', 1)]" + ) def test_label_command_no_label(self): "User LabelCommands raise an error if no label is provided" @@ -1722,8 +1758,16 @@ class CommandTypes(AdminScriptTestCase): args = ['label_command', 'testlabel', 'anotherlabel'] out, err = self.run_manage(args) self.assertNoOutput(err) - self.assertOutput(out, "EXECUTE:LabelCommand label=testlabel, options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', False), ('verbosity', 1)]") - self.assertOutput(out, "EXECUTE:LabelCommand label=anotherlabel, options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', False), ('verbosity', 1)]") + self.assertOutput( + out, + "EXECUTE:LabelCommand label=testlabel, options=[('no_color', False), " + "('pythonpath', None), ('settings', None), ('traceback', False), ('verbosity', 1)]" + ) + self.assertOutput( + out, + "EXECUTE:LabelCommand label=anotherlabel, options=[('no_color', False), " + "('pythonpath', None), ('settings', None), ('traceback', False), ('verbosity', 1)]" + ) class Discovery(SimpleTestCase): @@ -1794,7 +1838,13 @@ class ArgumentOrder(AdminScriptTestCase): def _test(self, args, option_b="'2'"): out, err = self.run_manage(args) self.assertNoOutput(err) - self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('no_color', False), ('option_a', 'x'), ('option_b', %s), ('option_c', '3'), ('pythonpath', None), ('settings', 'alternate_settings'), ('traceback', False), ('verbosity', 1)]" % option_b) + self.assertOutput( + out, + "EXECUTE:BaseCommand labels=('testlabel',), options=[('no_color', False), " + "('option_a', 'x'), ('option_b', %s), ('option_c', '3'), " + "('pythonpath', None), ('settings', 'alternate_settings'), " + "('traceback', False), ('verbosity', 1)]" % option_b + ) @override_settings(ROOT_URLCONF='admin_scripts.urls') @@ -1907,7 +1957,10 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase): self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py'))) def test_custom_project_template_from_tarball_by_url(self): - "Make sure the startproject management command is able to use a different project template from a tarball via a url" + """ + The startproject management command is able to use a different project + template from a tarball via a URL. + """ template_url = '%s/custom_templates/project_template.tgz' % self.live_server_url args = ['startproject', '--template', template_url, 'urltestproject'] @@ -1971,7 +2024,11 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase): self.write_settings('alternate_settings.py') self.addCleanup(self.remove_settings, 'alternate_settings.py') template_path = os.path.join(custom_templates_dir, 'project_template') - args = ['custom_startproject', '--template', template_path, 'another_project', 'project_dir', '--extra', '<&>', '--settings=alternate_settings'] + args = [ + 'custom_startproject', '--template', template_path, + 'another_project', 'project_dir', '--extra', '<&>', + '--settings=alternate_settings', + ] testproject_dir = os.path.join(self.test_dir, 'project_dir') os.mkdir(testproject_dir) self.addCleanup(shutil.rmtree, testproject_dir) @@ -1996,7 +2053,10 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase): self.assertFalse(os.path.exists(testproject_dir)) def test_custom_project_template_with_non_ascii_templates(self): - "Ticket 18091: Make sure the startproject management command is able to render templates with non-ASCII content" + """ + The startproject management command is able to render templates with + non-ASCII content. + """ template_path = os.path.join(custom_templates_dir, 'project_template') args = ['startproject', '--template', template_path, '--extension=txt', 'customtestproject'] testproject_dir = os.path.join(self.test_dir, 'customtestproject') diff --git a/tests/admin_views/admin.py b/tests/admin_views/admin.py index 0104181d96..ca114680d0 100644 --- a/tests/admin_views/admin.py +++ b/tests/admin_views/admin.py @@ -587,7 +587,9 @@ class PluggableSearchPersonAdmin(admin.ModelAdmin): search_fields = ('name',) def get_search_results(self, request, queryset, search_term): - queryset, use_distinct = super(PluggableSearchPersonAdmin, self).get_search_results(request, queryset, search_term) + queryset, use_distinct = super(PluggableSearchPersonAdmin, self).get_search_results( + request, queryset, search_term + ) try: search_term_as_int = int(search_term) queryset |= self.model.objects.filter(age=search_term_as_int) diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py index fbeca604d4..87d6f86ae4 100644 --- a/tests/admin_views/tests.py +++ b/tests/admin_views/tests.py @@ -300,7 +300,8 @@ class AdminViewBasicTest(AdminViewBasicTestCase): """ A smoke test to ensure POST on edit_view works. """ - response = self.client.post(reverse('admin:admin_views_section_change', args=(self.s1.pk,)), self.inline_post_data) + url = reverse('admin:admin_views_section_change', args=(self.s1.pk,)) + response = self.client.post(url, self.inline_post_data) self.assertEqual(response.status_code, 302) # redirect somewhere def test_edit_save_as(self): @@ -600,7 +601,10 @@ class AdminViewBasicTest(AdminViewBasicTestCase): link1 = reverse('admin:admin_views_fabric_change', args=(self.fab1.pk,)) link2 = reverse('admin:admin_views_fabric_change', args=(self.fab2.pk,)) response = self.client.get(reverse('admin:admin_views_fabric_changelist')) - fail_msg = "Changelist table isn't showing the right human-readable values set by a model field 'choices' option named group." + fail_msg = ( + "Changelist table isn't showing the right human-readable values " + "set by a model field 'choices' option named group." + ) self.assertContains(response, 'Horizontal' % link1, msg_prefix=fail_msg, html=True) self.assertContains(response, 'Vertical' % link2, msg_prefix=fail_msg, html=True) @@ -610,7 +614,10 @@ class AdminViewBasicTest(AdminViewBasicTestCase): been used in the choices option of a model field. """ response = self.client.get(reverse('admin:admin_views_fabric_changelist')) - fail_msg = "Changelist filter isn't showing options contained inside a model field 'choices' option named group." + fail_msg = ( + "Changelist filter isn't showing options contained inside a model " + "field 'choices' option named group." + ) self.assertContains(response, '
') self.assertContains(response, 'Horizontal', msg_prefix=fail_msg, html=True) @@ -684,7 +691,8 @@ class AdminViewBasicTest(AdminViewBasicTestCase): def test_disallowed_to_field(self): with patch_logger('django.security.DisallowedModelAdminToField', 'error') as calls: - response = self.client.get(reverse('admin:admin_views_section_changelist'), {TO_FIELD_VAR: 'missing_field'}) + url = reverse('admin:admin_views_section_changelist') + response = self.client.get(url, {TO_FIELD_VAR: 'missing_field'}) self.assertEqual(response.status_code, 400) self.assertEqual(len(calls), 1) @@ -726,12 +734,14 @@ class AdminViewBasicTest(AdminViewBasicTestCase): section = Section.objects.create() with patch_logger('django.security.DisallowedModelAdminToField', 'error') as calls: - response = self.client.post(reverse('admin:admin_views_section_change', args=(section.pk,)), {TO_FIELD_VAR: 'name'}) + url = reverse('admin:admin_views_section_change', args=(section.pk,)) + response = self.client.post(url, {TO_FIELD_VAR: 'name'}) self.assertEqual(response.status_code, 400) self.assertEqual(len(calls), 1) with patch_logger('django.security.DisallowedModelAdminToField', 'error') as calls: - response = self.client.post(reverse('admin:admin_views_section_delete', args=(section.pk,)), {TO_FIELD_VAR: 'name'}) + url = reverse('admin:admin_views_section_delete', args=(section.pk,)) + response = self.client.post(url, {TO_FIELD_VAR: 'name'}) self.assertEqual(response.status_code, 400) self.assertEqual(len(calls), 1) @@ -742,7 +752,8 @@ class AdminViewBasicTest(AdminViewBasicTestCase): can break. """ # Filters should be allowed if they are defined on a ForeignKey pointing to this model - response = self.client.get("%s?leader__name=Palin&leader__age=27" % reverse('admin:admin_views_inquisition_changelist')) + url = "%s?leader__name=Palin&leader__age=27" % reverse('admin:admin_views_inquisition_changelist') + response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_popup_dismiss_related(self): @@ -1787,24 +1798,24 @@ class AdminViewPermissionsTest(TestCase): rl2 = RowLevelChangePermissionModel.objects.create(name="even id") for login_dict in [self.super_login, self.changeuser_login, self.adduser_login, self.deleteuser_login]: self.client.post(login_url, login_dict) - response = self.client.get(reverse('admin:admin_views_rowlevelchangepermissionmodel_history', args=(rl1.pk,))) + url = reverse('admin:admin_views_rowlevelchangepermissionmodel_history', args=(rl1.pk,)) + response = self.client.get(url) self.assertEqual(response.status_code, 403) - response = self.client.get(reverse('admin:admin_views_rowlevelchangepermissionmodel_history', args=(rl2.pk,))) + url = reverse('admin:admin_views_rowlevelchangepermissionmodel_history', args=(rl2.pk,)) + response = self.client.get(url) self.assertEqual(response.status_code, 200) self.client.get(reverse('admin:logout')) for login_dict in [self.joepublic_login, self.no_username_login]: self.client.post(login_url, login_dict) - response = self.client.get( - reverse('admin:admin_views_rowlevelchangepermissionmodel_history', args=(rl1.pk,)), follow=True - ) + url = reverse('admin:admin_views_rowlevelchangepermissionmodel_history', args=(rl1.pk,)) + response = self.client.get(url, follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, 'login-form') - response = self.client.get( - reverse('admin:admin_views_rowlevelchangepermissionmodel_history', args=(rl2.pk,)), follow=True - ) + url = reverse('admin:admin_views_rowlevelchangepermissionmodel_history', args=(rl2.pk,)) + response = self.client.get(url, follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, 'login-form') @@ -2118,11 +2129,15 @@ class AdminViewDeletedObjectsTest(TestCase): Objects should be nested to display the relationships that cause them to be scheduled for deletion. """ - pattern = re.compile(force_bytes( - r'
  • Plot: World Domination\s*
      \s*
    • Plot details: almost finished' % ( - reverse('admin:admin_views_plot_change', args=(self.pl1.pk,)), - reverse('admin:admin_views_plotdetails_change', args=(self.pd1.pk,))) - )) + pattern = re.compile( + force_bytes( + r'
    • Plot: World Domination\s*
        \s*' + r'
      • Plot details: almost finished' % ( + reverse('admin:admin_views_plot_change', args=(self.pl1.pk,)), + reverse('admin:admin_views_plotdetails_change', args=(self.pd1.pk,)), + ) + ) + ) response = self.client.get(reverse('admin:admin_views_villain_delete', args=(self.v1.pk,))) six.assertRegex(self, response.content, pattern) @@ -2210,7 +2225,9 @@ class AdminViewDeletedObjectsTest(TestCase): """ should_contain = [ '
      • Villain: Bob' % reverse('admin:admin_views_villain_change', args=(self.sv1.pk,)), - '
      • Super villain: Bob' % reverse('admin:admin_views_supervillain_change', args=(self.sv1.pk,)), + '
      • Super villain: Bob' % reverse( + 'admin:admin_views_supervillain_change', args=(self.sv1.pk,) + ), '
      • Secret hideout: floating castle', '
      • Super secret hideout: super floating castle!', ] @@ -2324,7 +2341,10 @@ class AdminViewStringPrimaryKeyTest(TestCase): content='

        Newest content

        ', date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1 ) cls.p1 = PrePopulatedPost.objects.create(title='A Long Title', published=True, slug='a-long-title') - cls.pk = """abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 -_.!~*'() ;/?:@&=+$, <>#%" {}|\^[]`""" + cls.pk = ( + "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 " + """-_.!~*'() ;/?:@&=+$, <>#%" {}|\^[]`""" + ) cls.m1 = ModelWithStringPrimaryKey.objects.create(string_pk=cls.pk) content_type_pk = ContentType.objects.get_for_model(ModelWithStringPrimaryKey).pk LogEntry.objects.log_action(100, content_type_pk, cls.pk, cls.pk, 2, change_message='Changed something') @@ -2389,7 +2409,10 @@ class AdminViewStringPrimaryKeyTest(TestCase): counted_presence_after) def test_logentry_get_admin_url(self): - "LogEntry.get_admin_url returns a URL to edit the entry's object or None for non-existent (possibly deleted) models" + """ + LogEntry.get_admin_url returns a URL to edit the entry's object or + None for non-existent (possibly deleted) models. + """ log_entry_model = "modelwithstringprimarykey" # capitalized in Recent Actions logentry = LogEntry.objects.get(content_type__model__iexact=log_entry_model) desired_admin_url = reverse('admin:admin_views_modelwithstringprimarykey_change', args=(quote(self.pk),)) @@ -2418,7 +2441,8 @@ class AdminViewStringPrimaryKeyTest(TestCase): def test_deleteconfirmation_link(self): "The link from the delete confirmation page referring back to the changeform of the object should be quoted" - response = self.client.get(reverse('admin:admin_views_modelwithstringprimarykey_delete', args=(quote(self.pk),))) + url = reverse('admin:admin_views_modelwithstringprimarykey_delete', args=(quote(self.pk),)) + response = self.client.get(url) # this URL now comes through reverse(), thus url quoting and iri_to_uri encoding change_url = reverse( 'admin:admin_views_modelwithstringprimarykey_change', args=('__fk__',) @@ -3028,11 +3052,22 @@ class AdminViewListEditable(TestCase): Refs #12475. """ story1 = Story.objects.create(title='The adventures of Guido', content='Once upon a time in Djangoland...') - story2 = Story.objects.create(title='Crouching Tiger, Hidden Python', content='The Python was sneaking into...') + story2 = Story.objects.create( + title='Crouching Tiger, Hidden Python', + content='The Python was sneaking into...', + ) response = self.client.get(reverse('admin:admin_views_story_changelist')) - self.assertContains(response, 'id="id_form-0-id"', 1) # Only one hidden field, in a separate place than the table. + # Only one hidden field, in a separate place than the table. + self.assertContains(response, 'id="id_form-0-id"', 1) self.assertContains(response, 'id="id_form-1-id"', 1) - self.assertContains(response, '
        \n\n
        ' % (story2.id, story1.id), html=True) + self.assertContains( + response, + '
        \n' + '' + '\n
        ' + % (story2.id, story1.id), + html=True + ) self.assertContains(response, '%d' % story1.id, 1) self.assertContains(response, '%d' % story2.id, 1) @@ -3041,14 +3076,28 @@ class AdminViewListEditable(TestCase): referenced in list_display_links. Refs #12475. """ - story1 = OtherStory.objects.create(title='The adventures of Guido', content='Once upon a time in Djangoland...') - story2 = OtherStory.objects.create(title='Crouching Tiger, Hidden Python', content='The Python was sneaking into...') + story1 = OtherStory.objects.create( + title='The adventures of Guido', + content='Once upon a time in Djangoland...', + ) + story2 = OtherStory.objects.create( + title='Crouching Tiger, Hidden Python', + content='The Python was sneaking into...', + ) link1 = reverse('admin:admin_views_otherstory_change', args=(story1.pk,)) link2 = reverse('admin:admin_views_otherstory_change', args=(story2.pk,)) response = self.client.get(reverse('admin:admin_views_otherstory_changelist')) - self.assertContains(response, 'id="id_form-0-id"', 1) # Only one hidden field, in a separate place than the table. + # Only one hidden field, in a separate place than the table. + self.assertContains(response, 'id="id_form-0-id"', 1) self.assertContains(response, 'id="id_form-1-id"', 1) - self.assertContains(response, '
        \n\n
        ' % (story2.id, story1.id), html=True) + self.assertContains( + response, + '
        \n' + '' + '\n
        ' + % (story2.id, story1.id), + html=True + ) self.assertContains(response, '%d' % (link1, story1.id), 1) self.assertContains(response, '%d' % (link2, story2.id), 1) @@ -3850,9 +3899,11 @@ class AdminCustomQuerysetTest(TestCase): # Message should contain non-ugly model verbose name. The ugly(!) # instance representation is set by six.text_type() self.assertContains( - response, - '
      • The short message "ShortMessage_Deferred_timestamp object" was changed successfully.
      • ', - html=True + response, ( + '
      • The short message ' + '"ShortMessage_Deferred_timestamp object" was ' + 'changed successfully.
      • ' + ), html=True ) def test_edit_model_modeladmin_only_qs(self): @@ -4462,9 +4513,15 @@ class SeleniumAdminViewsFirefoxTests(AdminSeleniumWebDriverTestCase): # Initial inline self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-0-pubdate').send_keys('2011-12-17') self.get_select_option('#id_relatedprepopulated_set-0-status', 'option one').click() - self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-0-name').send_keys(' here is a sŤāÇkeð inline ! ') - slug1 = self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-0-slug1').get_attribute('value') - slug2 = self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-0-slug2').get_attribute('value') + self.selenium.find_element_by_css_selector( + '#id_relatedprepopulated_set-0-name' + ).send_keys(' here is a sŤāÇkeð inline ! ') + slug1 = self.selenium.find_element_by_css_selector( + '#id_relatedprepopulated_set-0-slug1' + ).get_attribute('value') + slug2 = self.selenium.find_element_by_css_selector( + '#id_relatedprepopulated_set-0-slug2' + ).get_attribute('value') self.assertEqual(slug1, 'here-stacked-inline-2011-12-17') self.assertEqual(slug2, 'option-one-here-stacked-inline') @@ -4472,19 +4529,34 @@ class SeleniumAdminViewsFirefoxTests(AdminSeleniumWebDriverTestCase): self.selenium.find_elements_by_link_text('Add another Related prepopulated')[0].click() self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-1-pubdate').send_keys('1999-01-25') self.get_select_option('#id_relatedprepopulated_set-1-status', 'option two').click() - self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-1-name').send_keys(' now you haVe anöther sŤāÇkeð inline with a very ... loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooog text... ') - slug1 = self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-1-slug1').get_attribute('value') - slug2 = self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-1-slug2').get_attribute('value') - self.assertEqual(slug1, 'now-you-have-another-stacked-inline-very-loooooooo') # 50 characters maximum for slug1 field - self.assertEqual(slug2, 'option-two-now-you-have-another-stacked-inline-very-looooooo') # 60 characters maximum for slug2 field + self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-1-name').send_keys( + ' now you haVe anöther sŤāÇkeð inline with a very ... ' + 'loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooog text... ' + ) + slug1 = self.selenium.find_element_by_css_selector( + '#id_relatedprepopulated_set-1-slug1' + ).get_attribute('value') + slug2 = self.selenium.find_element_by_css_selector( + '#id_relatedprepopulated_set-1-slug2' + ).get_attribute('value') + # 50 characters maximum for slug1 field + self.assertEqual(slug1, 'now-you-have-another-stacked-inline-very-loooooooo') + # 60 characters maximum for slug2 field + self.assertEqual(slug2, 'option-two-now-you-have-another-stacked-inline-very-looooooo') # Tabular inlines ---------------------------------------------------- # Initial inline self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-0-pubdate').send_keys('1234-12-07') self.get_select_option('#id_relatedprepopulated_set-2-0-status', 'option two').click() - self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-0-name').send_keys('And now, with a tÃbűlaŘ inline !!!') - slug1 = self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-0-slug1').get_attribute('value') - slug2 = self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-0-slug2').get_attribute('value') + self.selenium.find_element_by_css_selector( + '#id_relatedprepopulated_set-2-0-name' + ).send_keys('And now, with a tÃbűlaŘ inline !!!') + slug1 = self.selenium.find_element_by_css_selector( + '#id_relatedprepopulated_set-2-0-slug1' + ).get_attribute('value') + slug2 = self.selenium.find_element_by_css_selector( + '#id_relatedprepopulated_set-2-0-slug2' + ).get_attribute('value') self.assertEqual(slug1, 'and-now-tabular-inline-1234-12-07') self.assertEqual(slug2, 'option-two-and-now-tabular-inline') @@ -4492,9 +4564,15 @@ class SeleniumAdminViewsFirefoxTests(AdminSeleniumWebDriverTestCase): self.selenium.find_elements_by_link_text('Add another Related prepopulated')[1].click() self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-1-pubdate').send_keys('1981-08-22') self.get_select_option('#id_relatedprepopulated_set-2-1-status', 'option one').click() - self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-1-name').send_keys('a tÃbűlaŘ inline with ignored ;"&*^\%$#@-/`~ characters') - slug1 = self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-1-slug1').get_attribute('value') - slug2 = self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-1-slug2').get_attribute('value') + self.selenium.find_element_by_css_selector('#id_relatedprepopulated_set-2-1-name').send_keys( + 'a tÃbűlaŘ inline with ignored ;"&*^\%$#@-/`~ characters' + ) + slug1 = self.selenium.find_element_by_css_selector( + '#id_relatedprepopulated_set-2-1-slug1' + ).get_attribute('value') + slug2 = self.selenium.find_element_by_css_selector( + '#id_relatedprepopulated_set-2-1-slug2' + ).get_attribute('value') self.assertEqual(slug1, 'tabular-inline-ignored-characters-1981-08-22') self.assertEqual(slug2, 'option-one-tabular-inline-ignored-characters') @@ -4518,7 +4596,8 @@ class SeleniumAdminViewsFirefoxTests(AdminSeleniumWebDriverTestCase): slug2='option-one-here-stacked-inline', ) RelatedPrepopulated.objects.get( - name=' now you haVe anöther sŤāÇkeð inline with a very ... loooooooooooooooooo', # 75 characters in name field + # 75 characters in name field + name=' now you haVe anöther sŤāÇkeð inline with a very ... loooooooooooooooooo', pubdate='1999-01-25', status='option two', slug1='now-you-have-another-stacked-inline-very-loooooooo', @@ -4713,9 +4792,21 @@ class ReadonlyTest(TestCase): self.assertContains(response, '
        ') self.assertContains(response, '
        ') self.assertContains(response, '

        ', 3) - self.assertContains(response, '

        Some help text for the title (with unicode ŠĐĆŽćžšđ)

        ', html=True) - self.assertContains(response, '

        Some help text for the content (with unicode ŠĐĆŽćžšđ)

        ', html=True) - self.assertContains(response, '

        Some help text for the date (with unicode ŠĐĆŽćžšđ)

        ', html=True) + self.assertContains( + response, + '

        Some help text for the title (with unicode ŠĐĆŽćžšđ)

        ', + html=True + ) + self.assertContains( + response, + '

        Some help text for the content (with unicode ŠĐĆŽćžšđ)

        ', + html=True + ) + self.assertContains( + response, + '

        Some help text for the date (with unicode ŠĐĆŽćžšđ)

        ', + html=True + ) p = Post.objects.create(title="I worked on readonly_fields", content="Its good stuff") response = self.client.get(reverse('admin:admin_views_post_change', args=(p.pk,))) @@ -5741,20 +5832,30 @@ class AdminKeepChangeListFiltersTests(TestCase): # Test equality. change_user_url = reverse('admin:auth_user_change', args=(self.u5.pk,)) self.assertURLEqual( - 'http://testserver{}?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0'.format(change_user_url), - 'http://testserver{}?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0'.format(change_user_url) + 'http://testserver{}?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0'.format( + change_user_url + ), + 'http://testserver{}?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0'.format( + change_user_url + ) ) # Test inequality. with self.assertRaises(AssertionError): self.assertURLEqual( - 'http://testserver{}?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0'.format(change_user_url), - 'http://testserver{}?_changelist_filters=is_staff__exact%3D1%26is_superuser__exact%3D1'.format(change_user_url) + 'http://testserver{}?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0'.format( + change_user_url + ), + 'http://testserver{}?_changelist_filters=is_staff__exact%3D1%26is_superuser__exact%3D1'.format( + change_user_url + ) ) # Ignore scheme and host. self.assertURLEqual( - 'http://testserver{}?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0'.format(change_user_url), + 'http://testserver{}?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0'.format( + change_user_url + ), '{}?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0'.format(change_user_url) ) diff --git a/tests/admin_widgets/tests.py b/tests/admin_widgets/tests.py index efdc7eab93..8572db508a 100644 --- a/tests/admin_widgets/tests.py +++ b/tests/admin_widgets/tests.py @@ -189,7 +189,10 @@ class AdminFormfieldForDBFieldTests(SimpleTestCase): filter_vertical=['companies']) ma = AdvisorAdmin(models.Advisor, admin.site) f = ma.formfield_for_dbfield(models.Advisor._meta.get_field('companies'), request=None) - self.assertEqual(six.text_type(f.help_text), 'Hold down "Control", or "Command" on a Mac, to select more than one.') + self.assertEqual( + six.text_type(f.help_text), + 'Hold down "Control", or "Command" on a Mac, to select more than one.' + ) @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], @@ -327,7 +330,11 @@ class AdminSplitDateTimeWidgetTest(SimpleTestCase): w = widgets.AdminSplitDateTime() self.assertHTMLEqual( w.render('test', datetime(2007, 12, 1, 9, 30)), - '

        Date:
        Time:

        ', + '

        ' + 'Date:
        ' + 'Time:

        ' ) def test_localization(self): @@ -337,7 +344,11 @@ class AdminSplitDateTimeWidgetTest(SimpleTestCase): w.is_localized = True self.assertHTMLEqual( w.render('test', datetime(2007, 12, 1, 9, 30)), - '

        Datum:
        Zeit:

        ', + '

        ' + 'Datum:
        ' + 'Zeit:

        ' ) @@ -350,14 +361,20 @@ class AdminURLWidgetTest(SimpleTestCase): ) self.assertHTMLEqual( w.render('test', 'http://example.com'), - '

        Currently:http://example.com
        Change:

        ' + '

        Currently:' + 'http://example.com
        ' + 'Change:

        ' ) def test_render_idn(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( w.render('test', 'http://example-äüö.com'), - '

        Currently: http://example-äüö.com
        Change:

        ' + '

        Currently: ' + 'http://example-äüö.com
        ' + 'Change:

        ' ) def test_render_quoting(self): @@ -366,15 +383,29 @@ class AdminURLWidgetTest(SimpleTestCase): w = widgets.AdminURLFieldWidget() self.assertEqual( w.render('test', 'http://example.com/some text'), - '

        Currently: http://example.com/<sometag>some text</sometag>
        Change:

        ' + '

        Currently: ' + '' + 'http://example.com/<sometag>some text</sometag>
        ' + 'Change:

        ' ) self.assertEqual( w.render('test', 'http://example-äüö.com/some text'), - '

        Currently: http://example-äüö.com/<sometag>some text</sometag>
        Change:

        ' + '

        Currently: ' + '' + 'http://example-äüö.com/<sometag>some text</sometag>
        ' + 'Change:

        ' ) self.assertEqual( w.render('test', 'http://www.example.com/%C3%A4">"'), - '

        Currently: http://www.example.com/%C3%A4"><script>alert("XSS!")</script>"
        Change:

        ' + '

        Currently: ' + '' + 'http://www.example.com/%C3%A4"><script>' + 'alert("XSS!")</script>"
        ' + 'Change:

        ' ) @@ -447,11 +478,12 @@ class ForeignKeyRawIdWidgetTest(TestCase): w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( - w.render('test', band.pk, attrs={}), ( - '' - '' - ' Linkin Park' - ) % {'bandpk': band.pk} + w.render('test', band.pk, attrs={}), + '' + ' Linkin Park' + % {'bandpk': band.pk} ) def test_relations_to_non_primary_key(self): @@ -465,11 +497,12 @@ class ForeignKeyRawIdWidgetTest(TestCase): rel = models.Inventory._meta.get_field('parent').remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( - w.render('test', core.parent_id, attrs={}), ( - '' - '' - ' Apple' - ) + w.render('test', core.parent_id, attrs={}), + '' + '' + ' Apple' ) def test_fk_related_model_not_in_admin(self): @@ -482,7 +515,9 @@ class ForeignKeyRawIdWidgetTest(TestCase): w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render('honeycomb_widget', big_honeycomb.pk, attrs={}), - ' Honeycomb object' % {'hcombpk': big_honeycomb.pk} + '' + ' Honeycomb object' + % {'hcombpk': big_honeycomb.pk} ) def test_fk_to_self_model_not_in_admin(self): @@ -495,7 +530,9 @@ class ForeignKeyRawIdWidgetTest(TestCase): w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render('individual_widget', subject1.pk, attrs={}), - ' Individual object' % {'subj1pk': subject1.pk} + '' + ' Individual object' + % {'subj1pk': subject1.pk} ) def test_proper_manager_for_label_lookup(self): @@ -510,11 +547,11 @@ class ForeignKeyRawIdWidgetTest(TestCase): barcode=94, name='Child of hidden', parent=hidden ) self.assertHTMLEqual( - w.render('test', child_of_hidden.parent_id, attrs={}), ( - '' - '' - ' Hidden' - ) + w.render('test', child_of_hidden.parent_id, attrs={}), + '' + '' + ' Hidden' ) diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py index ad42aa3d77..1472bd04fd 100644 --- a/tests/aggregation/tests.py +++ b/tests/aggregation/tests.py @@ -307,7 +307,12 @@ class AggregateTestCase(TestCase): ] ) - books = Book.objects.filter(pk=self.b1.pk).annotate(mean_age=Avg('authors__age')).values('pk', 'isbn', 'mean_age') + books = ( + Book.objects + .filter(pk=self.b1.pk) + .annotate(mean_age=Avg('authors__age')) + .values('pk', 'isbn', 'mean_age') + ) self.assertEqual( list(books), [ { @@ -345,7 +350,12 @@ class AggregateTestCase(TestCase): ] ) - books = Book.objects.values("rating").annotate(n_authors=Count("authors__id"), mean_age=Avg("authors__age")).order_by("rating") + books = ( + Book.objects + .values("rating") + .annotate(n_authors=Count("authors__id"), mean_age=Avg("authors__age")) + .order_by("rating") + ) self.assertEqual( list(books), [ { @@ -561,7 +571,12 @@ class AggregateTestCase(TestCase): lambda p: p.name ) - publishers = Publisher.objects.annotate(num_books=Count("book__id")).filter(num_books__gt=1, book__price__lt=Decimal("40.0")).order_by("pk") + publishers = ( + Publisher.objects + .annotate(num_books=Count("book__id")) + .filter(num_books__gt=1, book__price__lt=Decimal("40.0")) + .order_by("pk") + ) self.assertQuerysetEqual( publishers, [ "Apress", @@ -571,7 +586,13 @@ class AggregateTestCase(TestCase): lambda p: p.name, ) - publishers = Publisher.objects.filter(book__price__lt=Decimal("40.0")).annotate(num_books=Count("book__id")).filter(num_books__gt=1).order_by("pk") + publishers = ( + Publisher.objects + .filter(book__price__lt=Decimal("40.0")) + .annotate(num_books=Count("book__id")) + .filter(num_books__gt=1) + .order_by("pk") + ) self.assertQuerysetEqual( publishers, [ "Apress", @@ -628,7 +649,12 @@ class AggregateTestCase(TestCase): lambda b: b.name ) - authors = Author.objects.annotate(num_friends=Count("friends__id", distinct=True)).filter(num_friends=0).order_by("pk") + authors = ( + Author.objects + .annotate(num_friends=Count("friends__id", distinct=True)) + .filter(num_friends=0) + .order_by("pk") + ) self.assertQuerysetEqual( authors, [ "Brad Dayley", @@ -645,7 +671,12 @@ class AggregateTestCase(TestCase): lambda p: p.name ) - publishers = Publisher.objects.filter(book__price__lt=Decimal("40.0")).annotate(num_books=Count("book__id")).filter(num_books__gt=1) + publishers = ( + Publisher.objects + .filter(book__price__lt=Decimal("40.0")) + .annotate(num_books=Count("book__id")) + .filter(num_books__gt=1) + ) self.assertQuerysetEqual( publishers, [ "Apress", @@ -653,7 +684,11 @@ class AggregateTestCase(TestCase): lambda p: p.name ) - books = Book.objects.annotate(num_authors=Count("authors__id")).filter(authors__name__contains="Norvig", num_authors__gt=1) + books = ( + Book.objects + .annotate(num_authors=Count("authors__id")) + .filter(authors__name__contains="Norvig", num_authors__gt=1) + ) self.assertQuerysetEqual( books, [ "Artificial Intelligence: A Modern Approach", @@ -667,7 +702,12 @@ class AggregateTestCase(TestCase): b.authors.add(a) b.save() - vals = Book.objects.annotate(num_authors=Count("authors__id")).filter(authors__name__contains="Norvig", num_authors__gt=1).aggregate(Avg("rating")) + vals = ( + Book.objects + .annotate(num_authors=Count("authors__id")) + .filter(authors__name__contains="Norvig", num_authors__gt=1) + .aggregate(Avg("rating")) + ) self.assertEqual(vals, {"rating__avg": 4.25}) def test_even_more_aggregate(self): @@ -718,7 +758,12 @@ class AggregateTestCase(TestCase): ) def test_annotate_values_list(self): - books = Book.objects.filter(pk=self.b1.pk).annotate(mean_age=Avg("authors__age")).values_list("pk", "isbn", "mean_age") + books = ( + Book.objects + .filter(pk=self.b1.pk) + .annotate(mean_age=Avg("authors__age")) + .values_list("pk", "isbn", "mean_age") + ) self.assertEqual( list(books), [ (1, "159059725", 34.5), @@ -739,7 +784,12 @@ class AggregateTestCase(TestCase): ] ) - books = Book.objects.filter(pk=self.b1.pk).annotate(mean_age=Avg("authors__age")).values_list("mean_age", flat=True) + books = ( + Book.objects + .filter(pk=self.b1.pk) + .annotate(mean_age=Avg("authors__age")) + .values_list("mean_age", flat=True) + ) self.assertEqual(list(books), [34.5]) books = Book.objects.values_list("price").annotate(count=Count("price")).order_by("-count", "price") diff --git a/tests/aggregation_regress/tests.py b/tests/aggregation_regress/tests.py index beb87bdb3a..380a33b66d 100644 --- a/tests/aggregation_regress/tests.py +++ b/tests/aggregation_regress/tests.py @@ -319,7 +319,13 @@ class AggregationTests(TestCase): ) # Check that consecutive calls to annotate accumulate in the query - qs = Book.objects.values('price').annotate(oldest=Max('authors__age')).order_by('oldest', 'price').annotate(Max('publisher__num_awards')) + qs = ( + Book.objects + .values('price') + .annotate(oldest=Max('authors__age')) + .order_by('oldest', 'price') + .annotate(Max('publisher__num_awards')) + ) self.assertQuerysetEqual( qs, [ {'price': Decimal("30"), 'oldest': 35, 'publisher__num_awards__max': 3}, @@ -334,7 +340,12 @@ class AggregationTests(TestCase): def test_aggrate_annotation(self): # Aggregates can be composed over annotations. # The return type is derived from the composed aggregate - vals = Book.objects.all().annotate(num_authors=Count('authors__id')).aggregate(Max('pages'), Max('price'), Sum('num_authors'), Avg('num_authors')) + vals = ( + Book.objects + .all() + .annotate(num_authors=Count('authors__id')) + .aggregate(Max('pages'), Max('price'), Sum('num_authors'), Avg('num_authors')) + ) self.assertEqual(vals, { 'num_authors__sum': 10, 'num_authors__avg': Approximate(1.666, places=2), @@ -441,18 +452,34 @@ class AggregationTests(TestCase): ) self.assertEqual( - len(Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__lt=3).exclude(num_authors__lt=2)), + len( + Book.objects + .annotate(num_authors=Count('authors')) + .filter(num_authors__lt=3) + .exclude(num_authors__lt=2) + ), 2 ) self.assertEqual( - len(Book.objects.annotate(num_authors=Count('authors')).exclude(num_authors__lt=2).filter(num_authors__lt=3)), + len( + Book.objects + .annotate(num_authors=Count('authors')) + .exclude(num_authors__lt=2) + .filter(num_authors__lt=3) + ), 2 ) def test_aggregate_fexpr(self): # Aggregates can be used with F() expressions # ... where the F() is pushed into the HAVING clause - qs = Publisher.objects.annotate(num_books=Count('book')).filter(num_books__lt=F('num_awards') / 2).order_by('name').values('name', 'num_books', 'num_awards') + qs = ( + Publisher.objects + .annotate(num_books=Count('book')) + .filter(num_books__lt=F('num_awards') / 2) + .order_by('name') + .values('name', 'num_books', 'num_awards') + ) self.assertQuerysetEqual( qs, [ {'num_books': 1, 'name': 'Morgan Kaufmann', 'num_awards': 9}, @@ -461,7 +488,13 @@ class AggregationTests(TestCase): lambda p: p, ) - qs = Publisher.objects.annotate(num_books=Count('book')).exclude(num_books__lt=F('num_awards') / 2).order_by('name').values('name', 'num_books', 'num_awards') + qs = ( + Publisher.objects + .annotate(num_books=Count('book')) + .exclude(num_books__lt=F('num_awards') / 2) + .order_by('name') + .values('name', 'num_books', 'num_awards') + ) self.assertQuerysetEqual( qs, [ {'num_books': 2, 'name': 'Apress', 'num_awards': 3}, @@ -472,7 +505,13 @@ class AggregationTests(TestCase): ) # ... and where the F() references an aggregate - qs = Publisher.objects.annotate(num_books=Count('book')).filter(num_awards__gt=2 * F('num_books')).order_by('name').values('name', 'num_books', 'num_awards') + qs = ( + Publisher.objects + .annotate(num_books=Count('book')) + .filter(num_awards__gt=2 * F('num_books')) + .order_by('name') + .values('name', 'num_books', 'num_awards') + ) self.assertQuerysetEqual( qs, [ {'num_books': 1, 'name': 'Morgan Kaufmann', 'num_awards': 9}, @@ -481,7 +520,13 @@ class AggregationTests(TestCase): lambda p: p, ) - qs = Publisher.objects.annotate(num_books=Count('book')).exclude(num_books__lt=F('num_awards') / 2).order_by('name').values('name', 'num_books', 'num_awards') + qs = ( + Publisher.objects + .annotate(num_books=Count('book')) + .exclude(num_books__lt=F('num_awards') / 2) + .order_by('name') + .values('name', 'num_books', 'num_awards') + ) self.assertQuerysetEqual( qs, [ {'num_books': 2, 'name': 'Apress', 'num_awards': 3}, @@ -493,7 +538,11 @@ class AggregationTests(TestCase): def test_db_col_table(self): # Tests on fields with non-default table and column names. - qs = Clues.objects.values('EntryID__Entry').annotate(Appearances=Count('EntryID'), Distinct_Clues=Count('Clue', distinct=True)) + qs = ( + Clues.objects + .values('EntryID__Entry') + .annotate(Appearances=Count('EntryID'), Distinct_Clues=Count('Clue', distinct=True)) + ) self.assertQuerysetEqual(qs, []) qs = Entries.objects.annotate(clue_count=Count('clues__ID')) @@ -518,17 +567,45 @@ class AggregationTests(TestCase): 0 ) - vals = Book.objects.filter(id__in=[]).aggregate(num_authors=Count('authors'), avg_authors=Avg('authors'), max_authors=Max('authors'), max_price=Max('price'), max_rating=Max('rating')) + vals = ( + Book.objects + .filter(id__in=[]) + .aggregate( + num_authors=Count('authors'), + avg_authors=Avg('authors'), + max_authors=Max('authors'), + max_price=Max('price'), + max_rating=Max('rating'), + ) + ) self.assertEqual( vals, {'max_authors': None, 'max_rating': None, 'num_authors': 0, 'avg_authors': None, 'max_price': None} ) - qs = Publisher.objects.filter(name="Jonno's House of Books").annotate(num_authors=Count('book__authors'), avg_authors=Avg('book__authors'), max_authors=Max('book__authors'), max_price=Max('book__price'), max_rating=Max('book__rating')).values() + qs = ( + Publisher.objects + .filter(name="Jonno's House of Books") + .annotate( + num_authors=Count('book__authors'), + avg_authors=Avg('book__authors'), + max_authors=Max('book__authors'), + max_price=Max('book__price'), + max_rating=Max('book__rating'), + ).values() + ) self.assertQuerysetEqual( - qs, [ - {'max_authors': None, 'name': "Jonno's House of Books", 'num_awards': 0, 'max_price': None, 'num_authors': 0, 'max_rating': None, 'id': self.p5.id, 'avg_authors': None} - ], + qs, + [{ + 'max_authors': None, + 'name': "Jonno's House of Books", + 'num_awards': 0, + 'max_price': None, + 'num_authors': 0, + 'max_rating': None, + 'id': self.p5.id, + 'avg_authors': None, + }], lambda p: p ) @@ -551,10 +628,16 @@ class AggregationTests(TestCase): # Regression for #10127 - Empty select_related() works with annotate qs = Book.objects.filter(rating__lt=4.5).select_related().annotate(Avg('authors__age')) self.assertQuerysetEqual( - qs, [ + qs, + [ ('Artificial Intelligence: A Modern Approach', 51.5, 'Prentice Hall', 'Peter Norvig'), ('Practical Django Projects', 29.0, 'Apress', 'James Bennett'), - ('Python Web Development with Django', Approximate(30.333, places=2), 'Prentice Hall', 'Jeffrey Forcier'), + ( + 'Python Web Development with Django', + Approximate(30.333, places=2), + 'Prentice Hall', + 'Jeffrey Forcier', + ), ('Sams Teach Yourself Django in 24 Hours', 45.0, 'Sams', 'Brad Dayley') ], lambda b: (b.name, b.authors__age__avg, b.publisher.name, b.contact.name) @@ -573,7 +656,13 @@ class AggregationTests(TestCase): lambda b: b ) - qs = Book.objects.extra(select={'pub': 'publisher_id', 'foo': 'pages'}).values('pub').annotate(Count('id')).order_by('pub') + qs = ( + Book.objects + .extra(select={'pub': 'publisher_id', 'foo': 'pages'}) + .values('pub') + .annotate(Count('id')) + .order_by('pub') + ) self.assertQuerysetEqual( qs, [ {'pub': self.p1.id, 'id__count': 2}, @@ -586,7 +675,13 @@ class AggregationTests(TestCase): # Regression for #10182 - Queries with aggregate calls are correctly # realiased when used in a subquery - ids = Book.objects.filter(pages__gt=100).annotate(n_authors=Count('authors')).filter(n_authors__gt=2).order_by('n_authors') + ids = ( + Book.objects + .filter(pages__gt=100) + .annotate(n_authors=Count('authors')) + .filter(n_authors__gt=2) + .order_by('n_authors') + ) self.assertQuerysetEqual( Book.objects.filter(id__in=ids), [ "Python Web Development with Django", @@ -603,14 +698,20 @@ class AggregationTests(TestCase): def test_duplicate_alias(self): # Regression for #11256 - duplicating a default alias raises ValueError. - self.assertRaises(ValueError, Book.objects.all().annotate, Avg('authors__age'), authors__age__avg=Avg('authors__age')) + self.assertRaises( + ValueError, + Book.objects.all().annotate, + Avg('authors__age'), authors__age__avg=Avg('authors__age') + ) def test_field_name_conflict(self): - # Regression for #11256 - providing an aggregate name that conflicts with a field name on the model raises ValueError + # Regression for #11256 - providing an aggregate name + # that conflicts with a field name on the model raises ValueError self.assertRaises(ValueError, Author.objects.annotate, age=Avg('friends__age')) def test_m2m_name_conflict(self): - # Regression for #11256 - providing an aggregate name that conflicts with an m2m name on the model raises ValueError + # Regression for #11256 - providing an aggregate name + # that conflicts with an m2m name on the model raises ValueError self.assertRaises(ValueError, Author.objects.annotate, friends=Count('friends')) def test_values_queryset_non_conflict(self): @@ -636,7 +737,8 @@ class AggregationTests(TestCase): self.assertEqual(results[0]['friends'], 2) def test_reverse_relation_name_conflict(self): - # Regression for #11256 - providing an aggregate name that conflicts with a reverse-related name on the model raises ValueError + # Regression for #11256 - providing an aggregate name + # that conflicts with a reverse-related name on the model raises ValueError self.assertRaises(ValueError, Author.objects.annotate, book_contact_set=Avg('friends__age')) def test_pickle(self): @@ -682,7 +784,13 @@ class AggregationTests(TestCase): # Regression for #10290 - extra selects with parameters can be used for # grouping. - qs = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'sheets': '(pages + %s) / %s'}, select_params=[1, 2]).order_by('sheets').values('sheets') + qs = ( + Book.objects + .annotate(mean_auth_age=Avg('authors__age')) + .extra(select={'sheets': '(pages + %s) / %s'}, select_params=[1, 2]) + .order_by('sheets') + .values('sheets') + ) self.assertQuerysetEqual( qs, [ 150, @@ -766,18 +874,26 @@ class AggregationTests(TestCase): qs = HardbackBook.objects.annotate(n_authors=Count('book_ptr__authors')).values('name', 'n_authors') self.assertQuerysetEqual( - qs, [ + qs, + [ {'n_authors': 2, 'name': 'Artificial Intelligence: A Modern Approach'}, - {'n_authors': 1, 'name': 'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp'} + { + 'n_authors': 1, + 'name': 'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp' + } ], lambda h: h ) qs = HardbackBook.objects.annotate(n_authors=Count('authors')).values('name', 'n_authors') self.assertQuerysetEqual( - qs, [ + qs, + [ {'n_authors': 2, 'name': 'Artificial Intelligence: A Modern Approach'}, - {'n_authors': 1, 'name': 'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp'} + { + 'n_authors': 1, + 'name': 'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp' + } ], lambda h: h, ) @@ -871,11 +987,17 @@ class AggregationTests(TestCase): attrgetter("name") ) - qs = Book.objects.annotate(n_authors=Count("authors")).filter( - Q(name="The Definitive Guide to Django: Web Development Done Right") | (Q(name="Artificial Intelligence: A Modern Approach") & Q(n_authors=3)) + qs = ( + Book.objects + .annotate(n_authors=Count("authors")) + .filter( + Q(name="The Definitive Guide to Django: Web Development Done Right") + | (Q(name="Artificial Intelligence: A Modern Approach") & Q(n_authors=3)) + ) ) self.assertQuerysetEqual( - qs, [ + qs, + [ "The Definitive Guide to Django: Web Development Done Right", ], attrgetter("name") diff --git a/tests/auth_tests/test_middleware.py b/tests/auth_tests/test_middleware.py index 44372bce01..e67a89ef26 100644 --- a/tests/auth_tests/test_middleware.py +++ b/tests/auth_tests/test_middleware.py @@ -38,7 +38,8 @@ class TestSessionAuthenticationMiddleware(TestCase): self.assertEqual(session_key, self.request.session.session_key) def test_changed_password_invalidates_session_with_middleware(self): - with self.modify_settings(MIDDLEWARE_CLASSES={'append': ['django.contrib.auth.middleware.SessionAuthenticationMiddleware']}): + with self.modify_settings( + MIDDLEWARE_CLASSES={'append': ['django.contrib.auth.middleware.SessionAuthenticationMiddleware']}): # After password change, user should be anonymous self.user.set_password('new_password') self.user.save() diff --git a/tests/backends/tests.py b/tests/backends/tests.py index 25f7432a46..b7b8c9cade 100644 --- a/tests/backends/tests.py +++ b/tests/backends/tests.py @@ -157,7 +157,11 @@ class PostgreSQLTests(TestCase): self.assert_parses("EnterpriseDB 9.3", 90300) self.assert_parses("PostgreSQL 9.3.6", 90306) self.assert_parses("PostgreSQL 9.4beta1", 90400) - self.assert_parses("PostgreSQL 9.3.1 on i386-apple-darwin9.2.2, compiled by GCC i686-apple-darwin9-gcc-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5478)", 90301) + self.assert_parses( + "PostgreSQL 9.3.1 on i386-apple-darwin9.2.2, compiled by GCC " + "i686-apple-darwin9-gcc-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5478)", + 90301 + ) def test_nodb_connection(self): """ @@ -419,13 +423,19 @@ class LongNameTest(TransactionTestCase): models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create() def test_sequence_name_length_limits_m2m(self): - """Test an m2m save of a model with a long name and a long m2m field name doesn't error as on Django >=1.2 this now uses object saves. Ref #8901""" + """ + An m2m save of a model with a long name and a long m2m field name + doesn't error (#8901). + """ obj = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create() rel_obj = models.Person.objects.create(first_name='Django', last_name='Reinhardt') obj.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.add(rel_obj) def test_sequence_name_length_limits_flush(self): - """Test that sequence resetting as part of a flush with model with long name and long pk name doesn't error. Ref #8901""" + """ + Sequence resetting as part of a flush with model with long name and + long pk name doesn't error (#8901). + """ # A full flush is expensive to the full test, so we dig into the # internals to generate the likely offending SQL and run it manually @@ -834,11 +844,16 @@ class FkConstraintsTests(TransactionTestCase): def test_disable_constraint_checks_manually(self): """ - When constraint checks are disabled, should be able to write bad data without IntegrityErrors. + When constraint checks are disabled, should be able to write bad data + without IntegrityErrors. """ with transaction.atomic(): # Create an Article. - models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r) + models.Article.objects.create( + headline="Test article", + pub_date=datetime.datetime(2010, 9, 4), + reporter=self.r, + ) # Retrieve it from the DB a = models.Article.objects.get(headline="Test article") a.reporter_id = 30 @@ -852,11 +867,16 @@ class FkConstraintsTests(TransactionTestCase): def test_disable_constraint_checks_context_manager(self): """ - When constraint checks are disabled (using context manager), should be able to write bad data without IntegrityErrors. + When constraint checks are disabled (using context manager), should be + able to write bad data without IntegrityErrors. """ with transaction.atomic(): # Create an Article. - models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r) + models.Article.objects.create( + headline="Test article", + pub_date=datetime.datetime(2010, 9, 4), + reporter=self.r, + ) # Retrieve it from the DB a = models.Article.objects.get(headline="Test article") a.reporter_id = 30 @@ -873,7 +893,11 @@ class FkConstraintsTests(TransactionTestCase): """ with transaction.atomic(): # Create an Article. - models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r) + models.Article.objects.create( + headline="Test article", + pub_date=datetime.datetime(2010, 9, 4), + reporter=self.r, + ) # Retrieve it from the DB a = models.Article.objects.get(headline="Test article") a.reporter_id = 30 diff --git a/tests/cache/tests.py b/tests/cache/tests.py index 76becdd948..dca08ee081 100644 --- a/tests/cache/tests.py +++ b/tests/cache/tests.py @@ -1844,7 +1844,8 @@ class CacheMiddlewareTest(SimpleTestCase): self.assertEqual(as_view_decorator.cache_timeout, 30) # Timeout value for 'default' cache, i.e. 30 self.assertEqual(as_view_decorator.key_prefix, '') - self.assertEqual(as_view_decorator.cache_alias, 'default') # Value of DEFAULT_CACHE_ALIAS from django.core.cache + # Value of DEFAULT_CACHE_ALIAS from django.core.cache + self.assertEqual(as_view_decorator.cache_alias, 'default') # Next, test with custom values: as_view_decorator_with_custom = CacheMiddleware(cache_timeout=60, cache_alias='other', key_prefix='foo') diff --git a/tests/contenttypes_tests/tests.py b/tests/contenttypes_tests/tests.py index 0d0f9d30b8..dd14eaad55 100644 --- a/tests/contenttypes_tests/tests.py +++ b/tests/contenttypes_tests/tests.py @@ -164,7 +164,10 @@ class GenericForeignKeyTests(IsolatedModelsTestCase): expected = [ checks.Error( "'Model.content_type' is not a ForeignKey.", - hint="GenericForeignKeys must use a ForeignKey to 'contenttypes.ContentType' as the 'content_type' field.", + hint=( + "GenericForeignKeys must use a ForeignKey to " + "'contenttypes.ContentType' as the 'content_type' field." + ), obj=Model.content_object, id='contenttypes.E003', ) @@ -182,7 +185,10 @@ class GenericForeignKeyTests(IsolatedModelsTestCase): expected = [ checks.Error( "'Model.content_type' is not a ForeignKey to 'contenttypes.ContentType'.", - hint="GenericForeignKeys must use a ForeignKey to 'contenttypes.ContentType' as the 'content_type' field.", + hint=( + "GenericForeignKeys must use a ForeignKey to " + "'contenttypes.ContentType' as the 'content_type' field." + ), obj=Model.content_object, id='contenttypes.E004', ) diff --git a/tests/createsuperuser/tests.py b/tests/createsuperuser/tests.py index 08f2ec5322..d5c891c118 100644 --- a/tests/createsuperuser/tests.py +++ b/tests/createsuperuser/tests.py @@ -24,7 +24,10 @@ class MultiDBChangepasswordManagementCommandTestCase(TestCase): command.execute(username="joe", database='other', stdout=out) command_output = out.getvalue().strip() - self.assertEqual(command_output, "Changing password for user 'joe'\nPassword changed successfully for user 'joe'") + self.assertEqual( + command_output, + "Changing password for user 'joe'\nPassword changed successfully for user 'joe'" + ) self.assertTrue(models.User.objects.using('other').get(username="joe").check_password("not qwerty")) diff --git a/tests/custom_columns/tests.py b/tests/custom_columns/tests.py index b258aea710..dccb400daf 100644 --- a/tests/custom_columns/tests.py +++ b/tests/custom_columns/tests.py @@ -95,7 +95,8 @@ class CustomColumnsTests(TestCase): def test_filter_on_nonexistent_field(self): self.assertRaisesMessage( FieldError, - "Cannot resolve keyword 'firstname' into field. Choices are: Author_ID, article, first_name, last_name, primary_set", + "Cannot resolve keyword 'firstname' into field. Choices are: " + "Author_ID, article, first_name, last_name, primary_set", Author.objects.filter, firstname__exact='John' ) diff --git a/tests/db_typecasts/tests.py b/tests/db_typecasts/tests.py index d0e0db20d7..98748abee4 100644 --- a/tests/db_typecasts/tests.py +++ b/tests/db_typecasts/tests.py @@ -53,4 +53,8 @@ class DBTypeCasts(unittest.TestCase): for k, v in six.iteritems(TEST_CASES): for inpt, expected in v: got = getattr(typecasts, k)(inpt) - self.assertEqual(got, expected, "In %s: %r doesn't match %r. Got %r instead." % (k, inpt, expected, got)) + self.assertEqual( + got, + expected, + "In %s: %r doesn't match %r. Got %r instead." % (k, inpt, expected, got) + ) diff --git a/tests/expressions_case/tests.py b/tests/expressions_case/tests.py index 2b269b5893..3f310278c7 100644 --- a/tests/expressions_case/tests.py +++ b/tests/expressions_case/tests.py @@ -689,7 +689,15 @@ class CaseExpressionTests(TestCase): ) self.assertQuerysetEqual( CaseTestModel.objects.all().order_by('pk'), - [(1, Decimal('1.1')), (2, Decimal('2.2')), (3, None), (2, Decimal('2.2')), (3, None), (3, None), (4, None)], + [ + (1, Decimal('1.1')), + (2, Decimal('2.2')), + (3, None), + (2, Decimal('2.2')), + (3, None), + (3, None), + (4, None) + ], transform=attrgetter('integer', 'decimal') ) @@ -934,8 +942,13 @@ class CaseExpressionTests(TestCase): self.assertQuerysetEqual( CaseTestModel.objects.all().order_by('pk'), [ - (1, UUID('11111111111111111111111111111111')), (2, UUID('22222222222222222222222222222222')), (3, None), - (2, UUID('22222222222222222222222222222222')), (3, None), (3, None), (4, None) + (1, UUID('11111111111111111111111111111111')), + (2, UUID('22222222222222222222222222222222')), + (3, None), + (2, UUID('22222222222222222222222222222222')), + (3, None), + (3, None), + (4, None), ], transform=attrgetter('integer', 'uuid') ) diff --git a/tests/extra_regress/tests.py b/tests/extra_regress/tests.py index aba6e326e1..242487a060 100644 --- a/tests/extra_regress/tests.py +++ b/tests/extra_regress/tests.py @@ -185,100 +185,174 @@ class ExtraRegressTests(TestCase): obj.save() self.assertEqual( - list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values()), - [{'bar': 'second', 'third': 'third', 'second': 'second', 'whiz': 'third', 'foo': 'first', 'id': obj.pk, 'first': 'first'}] + list( + TestObject.objects + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + .values() + ), + [{ + 'bar': 'second', 'third': 'third', 'second': 'second', 'whiz': 'third', 'foo': 'first', + 'id': obj.pk, 'first': 'first' + }] ) # Extra clauses after an empty values clause are still included self.assertEqual( - list(TestObject.objects.values().extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third'))))), - [{'bar': 'second', 'third': 'third', 'second': 'second', 'whiz': 'third', 'foo': 'first', 'id': obj.pk, 'first': 'first'}] + list( + TestObject.objects + .values() + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + ), + [{ + 'bar': 'second', 'third': 'third', 'second': 'second', 'whiz': 'third', 'foo': 'first', + 'id': obj.pk, 'first': 'first' + }] ) # Extra columns are ignored if not mentioned in the values() clause self.assertEqual( - list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values('first', 'second')), + list( + TestObject.objects + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + .values('first', 'second') + ), [{'second': 'second', 'first': 'first'}] ) # Extra columns after a non-empty values() clause are ignored self.assertEqual( - list(TestObject.objects.values('first', 'second').extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third'))))), + list( + TestObject.objects + .values('first', 'second') + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + ), [{'second': 'second', 'first': 'first'}] ) # Extra columns can be partially returned self.assertEqual( - list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values('first', 'second', 'foo')), + list( + TestObject.objects + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + .values('first', 'second', 'foo') + ), [{'second': 'second', 'foo': 'first', 'first': 'first'}] ) # Also works if only extra columns are included self.assertEqual( - list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values('foo', 'whiz')), + list( + TestObject.objects + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + .values('foo', 'whiz') + ), [{'foo': 'first', 'whiz': 'third'}] ) # Values list works the same way # All columns are returned for an empty values_list() self.assertEqual( - list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list()), + list( + TestObject.objects + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + .values_list() + ), [('first', 'second', 'third', obj.pk, 'first', 'second', 'third')] ) # Extra columns after an empty values_list() are still included self.assertEqual( - list(TestObject.objects.values_list().extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third'))))), + list( + TestObject.objects + .values_list() + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + ), [('first', 'second', 'third', obj.pk, 'first', 'second', 'third')] ) # Extra columns ignored completely if not mentioned in values_list() self.assertEqual( - list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list('first', 'second')), + list( + TestObject.objects + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + .values_list('first', 'second') + ), [('first', 'second')] ) # Extra columns after a non-empty values_list() clause are ignored completely self.assertEqual( - list(TestObject.objects.values_list('first', 'second').extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third'))))), + list( + TestObject.objects + .values_list('first', 'second') + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + ), [('first', 'second')] ) self.assertEqual( - list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list('second', flat=True)), + list( + TestObject.objects + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + .values_list('second', flat=True) + ), ['second'] ) # Only the extra columns specified in the values_list() are returned self.assertEqual( - list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list('first', 'second', 'whiz')), + list( + TestObject.objects + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + .values_list('first', 'second', 'whiz') + ), [('first', 'second', 'third')] ) # ...also works if only extra columns are included self.assertEqual( - list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list('foo', 'whiz')), + list( + TestObject.objects + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + .values_list('foo', 'whiz') + ), [('first', 'third')] ) self.assertEqual( - list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list('whiz', flat=True)), + list( + TestObject.objects + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + .values_list('whiz', flat=True) + ), ['third'] ) # ... and values are returned in the order they are specified self.assertEqual( - list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list('whiz', 'foo')), + list( + TestObject.objects + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + .values_list('whiz', 'foo') + ), [('third', 'first')] ) self.assertEqual( - list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list('first', 'id')), + list( + TestObject.objects + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + .values_list('first', 'id') + ), [('first', obj.pk)] ) self.assertEqual( - list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list('whiz', 'first', 'bar', 'id')), + list( + TestObject.objects + .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) + .values_list('whiz', 'first', 'bar', 'id') + ), [('third', 'first', 'second', obj.pk)] ) diff --git a/tests/file_uploads/tests.py b/tests/file_uploads/tests.py index 2fe1499738..1d0d0ffee1 100644 --- a/tests/file_uploads/tests.py +++ b/tests/file_uploads/tests.py @@ -156,14 +156,18 @@ class FileUploadTests(TestCase): (#22971). """ payload = client.FakePayload() - payload.write('\r\n'.join([ - '--' + client.BOUNDARY, - 'Content-Disposition: form-data; name*=UTF-8\'\'file_unicode; filename*=UTF-8\'\'%s' % urlquote(UNICODE_FILENAME), - 'Content-Type: application/octet-stream', - '', - 'You got pwnd.\r\n', - '\r\n--' + client.BOUNDARY + '--\r\n' - ])) + payload.write( + '\r\n'.join([ + '--' + client.BOUNDARY, + 'Content-Disposition: form-data; name*=UTF-8\'\'file_unicode; filename*=UTF-8\'\'%s' % urlquote( + UNICODE_FILENAME + ), + 'Content-Type: application/octet-stream', + '', + 'You got pwnd.\r\n', + '\r\n--' + client.BOUNDARY + '--\r\n' + ]) + ) r = { 'CONTENT_LENGTH': len(payload), diff --git a/tests/fixtures/tests.py b/tests/fixtures/tests.py index a89b33aa65..f48a689f6f 100644 --- a/tests/fixtures/tests.py +++ b/tests/fixtures/tests.py @@ -89,32 +89,83 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase): ]) # Dump the current contents of the database as a JSON fixture - self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]') + self._dumpdata_assert( + ['fixtures'], + '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": ' + '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place ' + 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": ' + '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]' + ) # Try just dumping the contents of fixtures.Category - self._dumpdata_assert(['fixtures.Category'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}]') + self._dumpdata_assert( + ['fixtures.Category'], + '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", ' + '"title": "News Stories"}}]' + ) # ...and just fixtures.Article - self._dumpdata_assert(['fixtures.Article'], '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]') + self._dumpdata_assert( + ['fixtures.Article'], + '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", ' + '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": ' + '"Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]' + ) # ...and both - self._dumpdata_assert(['fixtures.Category', 'fixtures.Article'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]') + self._dumpdata_assert( + ['fixtures.Category', 'fixtures.Article'], + '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", ' + '"title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has ' + 'no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", ' + '"fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]' + ) # Specify a specific model twice - self._dumpdata_assert(['fixtures.Article', 'fixtures.Article'], '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]') + self._dumpdata_assert( + ['fixtures.Article', 'fixtures.Article'], + ( + '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", ' + '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": ' + '"Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]' + ) + ) # Specify a dump that specifies Article both explicitly and implicitly - self._dumpdata_assert(['fixtures.Article', 'fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]') + self._dumpdata_assert( + ['fixtures.Article', 'fixtures'], + '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": ' + '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place ' + 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": ' + '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]' + ) # Specify a dump that specifies Article both explicitly and implicitly, # but lists the app first (#22025). - self._dumpdata_assert(['fixtures', 'fixtures.Article'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]') + self._dumpdata_assert( + ['fixtures', 'fixtures.Article'], + '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": ' + '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place ' + 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": ' + '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]' + ) # Same again, but specify in the reverse order - self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]') + self._dumpdata_assert( + ['fixtures'], + '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": ' + '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no ' + 'place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields":' + ' {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]' + ) # Specify one model from one application, and an entire other application. - self._dumpdata_assert(['fixtures.Category', 'sites'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}]') + self._dumpdata_assert( + ['fixtures.Category', 'sites'], + '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": ' + '"News Stories"}}, {"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": ' + '"example.com"}}]' + ) # Load fixture 2. JSON file imported by default. Overwrites some existing objects management.call_command('loaddata', 'fixture2.json', verbosity=0) @@ -174,20 +225,106 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase): ]) # By default, you get raw keys on dumpdata - self._dumpdata_assert(['fixtures.book'], '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [3, 1]}}]') + self._dumpdata_assert( + ['fixtures.book'], + '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [3, 1]}}]' + ) # But you can get natural keys if you ask for them and they are available - self._dumpdata_assert(['fixtures.book'], '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [["Artist formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]', natural_foreign_keys=True) + self._dumpdata_assert( + ['fixtures.book'], + '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [["Artist ' + 'formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]', + natural_foreign_keys=True + ) # You can also omit the primary keys for models that we can get later with natural keys. - self._dumpdata_assert(['fixtures.person'], '[{"fields": {"name": "Django Reinhardt"}, "model": "fixtures.person"}, {"fields": {"name": "Stephane Grappelli"}, "model": "fixtures.person"}, {"fields": {"name": "Artist formerly known as \\"Prince\\""}, "model": "fixtures.person"}]', natural_primary_keys=True) + self._dumpdata_assert( + ['fixtures.person'], + '[{"fields": {"name": "Django Reinhardt"}, "model": "fixtures.person"}, {"fields": {"name": "Stephane ' + 'Grappelli"}, "model": "fixtures.person"}, {"fields": {"name": "Artist formerly known as ' + '\\"Prince\\""}, "model": "fixtures.person"}]', + natural_primary_keys=True + ) # Dump the current contents of the database as a JSON fixture - self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker on TV is great!", "pub_date": "2006-06-16T11:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}, {"pk": 4, "model": "fixtures.article", "fields": {"headline": "Django conquers world!", "pub_date": "2006-06-16T15:00:00"}}, {"pk": 5, "model": "fixtures.article", "fields": {"headline": "XML identified as leading cause of cancer", "pub_date": "2006-06-16T16:00:00"}}, {"pk": 1, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "copyright", "tagged_id": 3}}, {"pk": 2, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "legal", "tagged_id": 3}}, {"pk": 3, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "django", "tagged_id": 4}}, {"pk": 4, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "world domination", "tagged_id": 4}}, {"pk": 1, "model": "fixtures.person", "fields": {"name": "Django Reinhardt"}}, {"pk": 2, "model": "fixtures.person", "fields": {"name": "Stephane Grappelli"}}, {"pk": 3, "model": "fixtures.person", "fields": {"name": "Artist formerly known as \\"Prince\\""}}, {"pk": 1, "model": "fixtures.visa", "fields": {"person": ["Django Reinhardt"], "permissions": [["add_user", "auth", "user"], ["change_user", "auth", "user"], ["delete_user", "auth", "user"]]}}, {"pk": 2, "model": "fixtures.visa", "fields": {"person": ["Stephane Grappelli"], "permissions": [["add_user", "auth", "user"], ["delete_user", "auth", "user"]]}}, {"pk": 3, "model": "fixtures.visa", "fields": {"person": ["Artist formerly known as \\"Prince\\""], "permissions": [["change_user", "auth", "user"]]}}, {"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [["Artist formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]', natural_foreign_keys=True) + self._dumpdata_assert( + ['fixtures'], + '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": ' + '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker on TV is ' + 'great!", "pub_date": "2006-06-16T11:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": ' + '{"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}, {"pk": 4, ' + '"model": "fixtures.article", "fields": {"headline": "Django conquers world!", "pub_date": ' + '"2006-06-16T15:00:00"}}, {"pk": 5, "model": "fixtures.article", "fields": {"headline": "XML ' + 'identified as leading cause of cancer", "pub_date": "2006-06-16T16:00:00"}}, {"pk": 1, "model": ' + '"fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "copyright", "tagged_id": ' + '3}}, {"pk": 2, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": ' + '"legal", "tagged_id": 3}}, {"pk": 3, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", ' + '"article"], "name": "django", "tagged_id": 4}}, {"pk": 4, "model": "fixtures.tag", "fields": ' + '{"tagged_type": ["fixtures", "article"], "name": "world domination", "tagged_id": 4}}, {"pk": 1, ' + '"model": "fixtures.person", "fields": {"name": "Django Reinhardt"}}, {"pk": 2, "model": ' + '"fixtures.person", "fields": {"name": "Stephane Grappelli"}}, {"pk": 3, "model": "fixtures.person", ' + '"fields": {"name": "Artist formerly known as \\"Prince\\""}}, {"pk": 1, "model": "fixtures.visa", ' + '"fields": {"person": ["Django Reinhardt"], "permissions": [["add_user", "auth", "user"], ' + '["change_user", "auth", "user"], ["delete_user", "auth", "user"]]}}, {"pk": 2, "model": ' + '"fixtures.visa", "fields": {"person": ["Stephane Grappelli"], "permissions": [["add_user", "auth", ' + '"user"], ["delete_user", "auth", "user"]]}}, {"pk": 3, "model": "fixtures.visa", "fields": {"person":' + ' ["Artist formerly known as \\"Prince\\""], "permissions": [["change_user", "auth", "user"]]}}, ' + '{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [["Artist ' + 'formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]', + natural_foreign_keys=True + ) # Dump the current contents of the database as an XML fixture - self._dumpdata_assert(['fixtures'], """ -News StoriesLatest news storiesPoker on TV is great!2006-06-16T11:00:00Copyright is fine the way it is2006-06-16T14:00:00Django conquers world!2006-06-16T15:00:00XML identified as leading cause of cancer2006-06-16T16:00:00copyrightfixturesarticle3legalfixturesarticle3djangofixturesarticle4world dominationfixturesarticle4Django ReinhardtStephane GrappelliArtist formerly known as "Prince"Django Reinhardtadd_userauthuserchange_userauthuserdelete_userauthuserStephane Grappelliadd_userauthuserdelete_userauthuserArtist formerly known as "Prince"change_userauthuserMusic for all agesArtist formerly known as "Prince"Django Reinhardt""", format='xml', natural_foreign_keys=True) + self._dumpdata_assert( + ['fixtures'], + 'News StoriesLatest news storiesPoker on TV is great!2006-06-16T11:00:00Copyright is fine the way it ' + 'is2006-06-16T14:00:00Django conquers world!' + '2006-06-16T15:00:00XML identified as leading ' + 'cause of cancer2006-06-16T16:00:00' + 'copyright' + 'fixtures' + 'article3' + 'legal' + '' + 'fixturesarticle3djangofixturesarticle4' + 'world dominationfixturesarticle' + '4Django Reinhardt' + 'Stephane Grappelli' + '' + 'Artist formerly known as "Prince"Django Reinhardt' + 'add_user' + 'authuserchange_user' + 'authuserdelete_user' + 'authuserStephane' + ' Grappelli' + 'add_userauthuser' + 'delete_userauthuser' + 'Artist formerly known as "Prince"change_user' + 'authuserMusic for all agesArtist formerly known as ' + '"Prince"Django Reinhardt' + '', + format='xml', natural_foreign_keys=True + ) def test_dumpdata_with_excludes(self): # Load fixture1 which has a site, two articles, and a category @@ -203,20 +340,28 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase): # Excluding fixtures.Article/Book should leave fixtures.Category self._dumpdata_assert( ['sites', 'fixtures'], - '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, {"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}]', - exclude_list=['fixtures.Article', 'fixtures.Book']) + '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, ' + '{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": ' + '"News Stories"}}]', + exclude_list=['fixtures.Article', 'fixtures.Book'] + ) # Excluding fixtures and fixtures.Article/Book should be a no-op self._dumpdata_assert( ['sites', 'fixtures'], - '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, {"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}]', - exclude_list=['fixtures.Article', 'fixtures.Book']) + '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, ' + '{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": ' + '"News Stories"}}]', + exclude_list=['fixtures.Article', 'fixtures.Book'] + ) # Excluding sites and fixtures.Article/Book should only leave fixtures.Category self._dumpdata_assert( ['sites', 'fixtures'], - '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}]', - exclude_list=['fixtures.Article', 'fixtures.Book', 'sites']) + '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": ' + '"News Stories"}}]', + exclude_list=['fixtures.Article', 'fixtures.Book', 'sites'] + ) # Excluding a bogus app should throw an error with six.assertRaisesRegex(self, management.CommandError, @@ -239,23 +384,34 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase): self.assertQuerysetEqual(Spy.objects.all(), ['']) # Use the default manager - self._dumpdata_assert(['fixtures.Spy'], '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % spy1.pk) + self._dumpdata_assert( + ['fixtures.Spy'], + '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % spy1.pk + ) # Dump using Django's base manager. Should return all objects, # even those normally filtered by the manager - self._dumpdata_assert(['fixtures.Spy'], '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": true}}, {"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % (spy2.pk, spy1.pk), use_base_manager=True) + self._dumpdata_assert( + ['fixtures.Spy'], + '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": true}}, {"pk": %d, "model": ' + '"fixtures.spy", "fields": {"cover_blown": false}}]' % (spy2.pk, spy1.pk), + use_base_manager=True + ) def test_dumpdata_with_pks(self): management.call_command('loaddata', 'fixture1.json', verbosity=0) management.call_command('loaddata', 'fixture2.json', verbosity=0) self._dumpdata_assert( ['fixtures.Article'], - '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]', + '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", ' + '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": ' + '"Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]', primary_keys='2,3' ) self._dumpdata_assert( ['fixtures.Article'], - '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}]', + '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", ' + '"pub_date": "2006-06-16T12:00:00"}}]', primary_keys='2' ) @@ -263,7 +419,9 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase): "You can only use --pks option with one model"): self._dumpdata_assert( ['fixtures'], - '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]', + '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", ' + '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": ' + '{"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]', primary_keys='2,3' ) @@ -271,7 +429,9 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase): "You can only use --pks option with one model"): self._dumpdata_assert( '', - '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]', + '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", ' + '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": ' + '{"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]', primary_keys='2,3' ) @@ -279,14 +439,22 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase): "You can only use --pks option with one model"): self._dumpdata_assert( ['fixtures.Article', 'fixtures.category'], - '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]', + '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", ' + '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": ' + '{"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]', primary_keys='2,3' ) def test_dumpdata_with_file_output(self): management.call_command('loaddata', 'fixture1.json', verbosity=0) - self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]', - filename='dumpdata.json') + self._dumpdata_assert( + ['fixtures'], + '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": ' + '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place ' + 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": ' + '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]', + filename='dumpdata.json' + ) def test_dumpdata_progressbar(self): """ @@ -414,11 +582,42 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase): ], ordered=False) # Dump the current contents of the database as a JSON fixture - self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}, {"pk": 1, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "copyright", "tagged_id": 3}}, {"pk": 2, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "law", "tagged_id": 3}}, {"pk": 1, "model": "fixtures.person", "fields": {"name": "Django Reinhardt"}}, {"pk": 2, "model": "fixtures.person", "fields": {"name": "Stephane Grappelli"}}, {"pk": 3, "model": "fixtures.person", "fields": {"name": "Prince"}}]', natural_foreign_keys=True) + self._dumpdata_assert( + ['fixtures'], + '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": ' + '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place ' + 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": ' + '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}, {"pk": 1, "model": ' + '"fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "copyright", "tagged_id": ' + '3}}, {"pk": 2, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": ' + '"law", "tagged_id": 3}}, {"pk": 1, "model": "fixtures.person", "fields": {"name": "Django ' + 'Reinhardt"}}, {"pk": 2, "model": "fixtures.person", "fields": {"name": "Stephane Grappelli"}}, ' + '{"pk": 3, "model": "fixtures.person", "fields": {"name": "Prince"}}]', + natural_foreign_keys=True + ) # Dump the current contents of the database as an XML fixture - self._dumpdata_assert(['fixtures'], """ -News StoriesLatest news storiesPoker has no place on ESPN2006-06-16T12:00:00Time to reform copyright2006-06-16T13:00:00copyrightfixturesarticle3lawfixturesarticle3Django ReinhardtStephane GrappelliPrince""", format='xml', natural_foreign_keys=True) + self._dumpdata_assert( + ['fixtures'], + 'News StoriesLatest news storiesPoker has no place on ESPN' + '2006-06-16T12:00:00Time to reform copyright' + '2006-06-16T13:00:00copyrightfixtures' + 'article3' + 'lawfixtures' + 'article3' + 'Django Reinhardt' + 'Stephane ' + 'Grappelli' + 'Prince', + format='xml', natural_foreign_keys=True + ) class NonExistentFixtureTests(TestCase): @@ -476,7 +675,13 @@ class FixtureTransactionTests(DumpDataAssertMixin, TransactionTestCase): ]) # Dump the current contents of the database as a JSON fixture - self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]') + self._dumpdata_assert( + ['fixtures'], + '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": ' + '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place ' + 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": ' + '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]' + ) # Load fixture 4 (compressed), using format discovery management.call_command('loaddata', 'fixture4', verbosity=0) diff --git a/tests/fixtures_regress/tests.py b/tests/fixtures_regress/tests.py index e533be3bb6..02a841f5ef 100644 --- a/tests/fixtures_regress/tests.py +++ b/tests/fixtures_regress/tests.py @@ -239,7 +239,10 @@ class TestFixtures(TestCase): ) warning = warning_list.pop() self.assertEqual(warning.category, RuntimeWarning) - self.assertEqual(str(warning.message), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)") + self.assertEqual( + str(warning.message), + "No fixture data found for 'bad_fixture2'. (File format may be invalid.)" + ) def test_invalid_data_no_ext(self): """ @@ -256,7 +259,10 @@ class TestFixtures(TestCase): ) warning = warning_list.pop() self.assertEqual(warning.category, RuntimeWarning) - self.assertEqual(str(warning.message), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)") + self.assertEqual( + str(warning.message), + "No fixture data found for 'bad_fixture2'. (File format may be invalid.)" + ) def test_empty(self): """ @@ -272,7 +278,8 @@ class TestFixtures(TestCase): ) warning = warning_list.pop() self.assertEqual(warning.category, RuntimeWarning) - self.assertEqual(str(warning.message), "No fixture data found for 'empty'. (File format may be invalid.)") + self.assertEqual(str(warning.message), + "No fixture data found for 'empty'. (File format may be invalid.)") def test_error_message(self): """ @@ -289,7 +296,10 @@ class TestFixtures(TestCase): ) warning = warning_list.pop() self.assertEqual(warning.category, RuntimeWarning) - self.assertEqual(str(warning.message), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)") + self.assertEqual( + str(warning.message), + "No fixture data found for 'bad_fixture2'. (File format may be invalid.)" + ) def test_pg_sequence_resetting_checks(self): """ @@ -394,9 +404,18 @@ class TestFixtures(TestCase): data = re.sub('0{6,}[0-9]', '', data) animals_data = sorted([ - {"pk": 1, "model": "fixtures_regress.animal", "fields": {"count": 3, "weight": 1.2, "name": "Lion", "latin_name": "Panthera leo"}}, - {"pk": 10, "model": "fixtures_regress.animal", "fields": {"count": 42, "weight": 1.2, "name": "Emu", "latin_name": "Dromaius novaehollandiae"}}, - {"pk": animal.pk, "model": "fixtures_regress.animal", "fields": {"count": 2, "weight": 2.2, "name": "Platypus", "latin_name": "Ornithorhynchus anatinus"}}, + { + "pk": 1, "model": "fixtures_regress.animal", + "fields": {"count": 3, "weight": 1.2, "name": "Lion", "latin_name": "Panthera leo"} + }, + { + "pk": 10, "model": "fixtures_regress.animal", + "fields": {"count": 42, "weight": 1.2, "name": "Emu", "latin_name": "Dromaius novaehollandiae"} + }, + { + "pk": animal.pk, "model": "fixtures_regress.animal", + "fields": {"count": 2, "weight": 2.2, "name": "Platypus", "latin_name": "Ornithorhynchus anatinus"} + }, ], key=lambda x: x["pk"]) data = sorted(json.loads(data), key=lambda x: x["pk"]) @@ -636,7 +655,13 @@ class NaturalKeyFixtureTests(TestCase): ) self.assertJSONEqual( out.getvalue(), - """[{"fields": {"main": null, "name": "Amazon"}, "model": "fixtures_regress.store"}, {"fields": {"main": null, "name": "Borders"}, "model": "fixtures_regress.store"}, {"fields": {"name": "Neal Stephenson"}, "model": "fixtures_regress.person"}, {"pk": 1, "model": "fixtures_regress.book", "fields": {"stores": [["Amazon"], ["Borders"]], "name": "Cryptonomicon", "author": ["Neal Stephenson"]}}]""" + """ + [{"fields": {"main": null, "name": "Amazon"}, "model": "fixtures_regress.store"}, + {"fields": {"main": null, "name": "Borders"}, "model": "fixtures_regress.store"}, + {"fields": {"name": "Neal Stephenson"}, "model": "fixtures_regress.person"}, + {"pk": 1, "model": "fixtures_regress.book", "fields": {"stores": [["Amazon"], ["Borders"]], + "name": "Cryptonomicon", "author": ["Neal Stephenson"]}}] + """ ) def test_dependency_sorting(self): @@ -711,7 +736,8 @@ class NaturalKeyFixtureTests(TestCase): def test_dependency_sorting_tight_circular(self): self.assertRaisesMessage( RuntimeError, - """Can't resolve dependencies for fixtures_regress.Circle1, fixtures_regress.Circle2 in serialized app list.""", + "Can't resolve dependencies for fixtures_regress.Circle1, " + "fixtures_regress.Circle2 in serialized app list.", serializers.sort_dependencies, [('fixtures_regress', [Person, Circle2, Circle1, Store, Book])], ) @@ -719,7 +745,8 @@ class NaturalKeyFixtureTests(TestCase): def test_dependency_sorting_tight_circular_2(self): self.assertRaisesMessage( RuntimeError, - """Can't resolve dependencies for fixtures_regress.Circle1, fixtures_regress.Circle2 in serialized app list.""", + "Can't resolve dependencies for fixtures_regress.Circle1, " + "fixtures_regress.Circle2 in serialized app list.", serializers.sort_dependencies, [('fixtures_regress', [Circle1, Book, Circle2])], ) @@ -727,7 +754,8 @@ class NaturalKeyFixtureTests(TestCase): def test_dependency_self_referential(self): self.assertRaisesMessage( RuntimeError, - """Can't resolve dependencies for fixtures_regress.Circle3 in serialized app list.""", + "Can't resolve dependencies for fixtures_regress.Circle3 in " + "serialized app list.", serializers.sort_dependencies, [('fixtures_regress', [Book, Circle3])], ) @@ -735,7 +763,9 @@ class NaturalKeyFixtureTests(TestCase): def test_dependency_sorting_long(self): self.assertRaisesMessage( RuntimeError, - """Can't resolve dependencies for fixtures_regress.Circle1, fixtures_regress.Circle2, fixtures_regress.Circle3 in serialized app list.""", + "Can't resolve dependencies for fixtures_regress.Circle1, " + "fixtures_regress.Circle2, fixtures_regress.Circle3 in serialized " + "app list.", serializers.sort_dependencies, [('fixtures_regress', [Person, Circle2, Circle1, Circle3, Store, Book])], ) @@ -772,7 +802,9 @@ class NaturalKeyFixtureTests(TestCase): books = Book.objects.all() self.assertEqual( books.__repr__(), - """[, , ]""" + "[, " + ", " + "]" ) diff --git a/tests/forms_tests/tests/test_error_messages.py b/tests/forms_tests/tests/test_error_messages.py index d2a80051ce..0632107e1e 100644 --- a/tests/forms_tests/tests/test_error_messages.py +++ b/tests/forms_tests/tests/test_error_messages.py @@ -157,7 +157,11 @@ class FormsErrorMessagesTestCase(SimpleTestCase, AssertFormErrorsMixin): f = URLField(error_messages=e, max_length=17) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abc.c') - self.assertFormErrors(['"http://djangoproject.com" has more than 17 characters.'], f.clean, 'djangoproject.com') + self.assertFormErrors( + ['"http://djangoproject.com" has more than 17 characters.'], + f.clean, + 'djangoproject.com' + ) def test_booleanfield(self): e = { @@ -226,8 +230,14 @@ class FormsErrorMessagesTestCase(SimpleTestCase, AssertFormErrorsMixin): # This form should print errors the default way. form1 = TestForm({'first_name': 'John'}) - self.assertHTMLEqual(str(form1['last_name'].errors), '
        • This field is required.
        ') - self.assertHTMLEqual(str(form1.errors['__all__']), '
        • I like to be awkward.
        ') + self.assertHTMLEqual( + str(form1['last_name'].errors), + '
        • This field is required.
        ' + ) + self.assertHTMLEqual( + str(form1.errors['__all__']), + '
        • I like to be awkward.
        ' + ) # This one should wrap error groups in the customized way. form2 = TestForm({'first_name': 'John'}, error_class=CustomErrorList) diff --git a/tests/forms_tests/tests/test_fields.py b/tests/forms_tests/tests/test_fields.py index 6234f5c455..5e4b4269db 100644 --- a/tests/forms_tests/tests/test_fields.py +++ b/tests/forms_tests/tests/test_fields.py @@ -117,14 +117,18 @@ class FieldsTests(SimpleTestCase): f = CharField(max_length=10, required=False) self.assertEqual('12345', f.clean('12345')) self.assertEqual('1234567890', f.clean('1234567890')) - self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", f.clean, '1234567890a') + msg = "'Ensure this value has at most 10 characters (it has 11).'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean('1234567890a') self.assertEqual(f.max_length, 10) self.assertEqual(f.min_length, None) def test_charfield_4(self): f = CharField(min_length=10, required=False) self.assertEqual('', f.clean('')) - self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 5).'", f.clean, '12345') + msg = "'Ensure this value has at least 10 characters (it has 5).'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean('12345') self.assertEqual('1234567890', f.clean('1234567890')) self.assertEqual('1234567890a', f.clean('1234567890a')) self.assertEqual(f.max_length, None) @@ -133,7 +137,9 @@ class FieldsTests(SimpleTestCase): def test_charfield_5(self): f = CharField(min_length=10, required=True) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 5).'", f.clean, '12345') + msg = "'Ensure this value has at least 10 characters (it has 5).'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean('12345') self.assertEqual('1234567890', f.clean('1234567890')) self.assertEqual('1234567890a', f.clean('1234567890a')) self.assertEqual(f.max_length, None) @@ -327,7 +333,10 @@ class FieldsTests(SimpleTestCase): f = FloatField(max_value=1.5, min_value=0.5) self.assertWidgetRendersTo(f, '') self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'", f.clean, '1.6') - self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'", f.clean, '0.4') + self.assertRaisesMessage( + ValidationError, "'Ensure this value is greater than or equal to 0.5.'", + f.clean, '0.4' + ) self.assertEqual(1.5, f.clean('1.5')) self.assertEqual(0.5, f.clean('0.5')) self.assertEqual(f.max_value, 1.5) @@ -377,16 +386,34 @@ class FieldsTests(SimpleTestCase): self.assertEqual(f.clean(' 1.0'), Decimal("1.0")) self.assertEqual(f.clean(' 1.0 '), Decimal("1.0")) self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '1.0a') - self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '123.45') - self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '1.234') - self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 digits before the decimal point.'", f.clean, '123.4') + self.assertRaisesMessage( + ValidationError, "'Ensure that there are no more than 4 digits in total.'", + f.clean, '123.45' + ) + self.assertRaisesMessage( + ValidationError, "'Ensure that there are no more than 2 decimal places.'", + f.clean, '1.234' + ) + self.assertRaisesMessage( + ValidationError, "'Ensure that there are no more than 2 digits before the decimal point.'", + f.clean, '123.4' + ) self.assertEqual(f.clean('-12.34'), Decimal("-12.34")) - self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '-123.45') + self.assertRaisesMessage( + ValidationError, "'Ensure that there are no more than 4 digits in total.'", + f.clean, '-123.45' + ) self.assertEqual(f.clean('-.12'), Decimal("-0.12")) self.assertEqual(f.clean('-00.12'), Decimal("-0.12")) self.assertEqual(f.clean('-000.12'), Decimal("-0.12")) - self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '-000.123') - self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '-000.12345') + self.assertRaisesMessage( + ValidationError, "'Ensure that there are no more than 2 decimal places.'", + f.clean, '-000.123' + ) + self.assertRaisesMessage( + ValidationError, "'Ensure that there are no more than 4 digits in total.'", + f.clean, '-000.12345' + ) self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '--0.12') self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) @@ -407,7 +434,10 @@ class FieldsTests(SimpleTestCase): f = DecimalField(max_digits=4, decimal_places=2, max_value=Decimal('1.5'), min_value=Decimal('0.5')) self.assertWidgetRendersTo(f, '') self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'", f.clean, '1.6') - self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'", f.clean, '0.4') + self.assertRaisesMessage( + ValidationError, "'Ensure this value is greater than or equal to 0.5.'", + f.clean, '0.4' + ) self.assertEqual(f.clean('1.5'), Decimal("1.5")) self.assertEqual(f.clean('0.5'), Decimal("0.5")) self.assertEqual(f.clean('.5'), Decimal("0.5")) @@ -419,7 +449,10 @@ class FieldsTests(SimpleTestCase): def test_decimalfield_4(self): f = DecimalField(decimal_places=2) - self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '0.00000001') + self.assertRaisesMessage( + ValidationError, "'Ensure that there are no more than 2 decimal places.'", + f.clean, '0.00000001' + ) def test_decimalfield_5(self): f = DecimalField(max_digits=3) @@ -429,13 +462,19 @@ class FieldsTests(SimpleTestCase): self.assertEqual(f.clean('0000000.100'), Decimal("0.100")) # Only leading whole zeros "collapse" to one digit. self.assertEqual(f.clean('000000.02'), Decimal('0.02')) - self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 3 digits in total.'", f.clean, '000000.0002') + self.assertRaisesMessage( + ValidationError, "'Ensure that there are no more than 3 digits in total.'", + f.clean, '000000.0002' + ) self.assertEqual(f.clean('.002'), Decimal("0.002")) def test_decimalfield_6(self): f = DecimalField(max_digits=2, decimal_places=2) self.assertEqual(f.clean('.01'), Decimal(".01")) - self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 0 digits before the decimal point.'", f.clean, '1.1') + self.assertRaisesMessage( + ValidationError, "'Ensure that there are no more than 0 digits before the decimal point.'", + f.clean, '1.1' + ) def test_decimalfield_scientific(self): f = DecimalField(max_digits=2, decimal_places=2) @@ -588,8 +627,14 @@ class FieldsTests(SimpleTestCase): f = DateTimeField() self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) - self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))) - self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59, 200), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))) + self.assertEqual( + datetime.datetime(2006, 10, 25, 14, 30, 59), + f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59)) + ) + self.assertEqual( + datetime.datetime(2006, 10, 25, 14, 30, 59, 200), + f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200)) + ) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('2006-10-25 14:30:45.000200')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('2006-10-25 14:30:45.0002')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean('2006-10-25 14:30:45')) @@ -613,8 +658,14 @@ class FieldsTests(SimpleTestCase): f = DateTimeField(input_formats=['%Y %m %d %I:%M %p']) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) - self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))) - self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59, 200), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))) + self.assertEqual( + datetime.datetime(2006, 10, 25, 14, 30, 59), + f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59)) + ) + self.assertEqual( + datetime.datetime(2006, 10, 25, 14, 30, 59, 200), + f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200)) + ) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006 10 25 2:30 PM')) self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, '2006-10-25 14:30:45') @@ -717,11 +768,22 @@ class FieldsTests(SimpleTestCase): def test_regexfield_5(self): f = RegexField('^[0-9]+$', min_length=5, max_length=10) - self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 5 characters (it has 3).'", f.clean, '123') - six.assertRaisesRegex(self, ValidationError, "'Ensure this value has at least 5 characters \(it has 3\)\.', u?'Enter a valid value\.'", f.clean, 'abc') + self.assertRaisesMessage( + ValidationError, "'Ensure this value has at least 5 characters (it has 3).'", + f.clean, '123' + ) + six.assertRaisesRegex( + self, ValidationError, + "'Ensure this value has at least 5 characters \(it has 3\)\.'," + " u?'Enter a valid value\.'", + f.clean, 'abc' + ) self.assertEqual('12345', f.clean('12345')) self.assertEqual('1234567890', f.clean('1234567890')) - self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", f.clean, '12345678901') + self.assertRaisesMessage( + ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", + f.clean, '12345678901' + ) self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '12345a') def test_regexfield_6(self): @@ -769,9 +831,15 @@ class FieldsTests(SimpleTestCase): def test_emailfield_min_max_length(self): f = EmailField(min_length=10, max_length=15) self.assertWidgetRendersTo(f, '') - self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 9).'", f.clean, 'a@foo.com') + self.assertRaisesMessage( + ValidationError, "'Ensure this value has at least 10 characters (it has 9).'", + f.clean, 'a@foo.com' + ) self.assertEqual('alf@foo.com', f.clean('alf@foo.com')) - self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 15 characters (it has 20).'", f.clean, 'alf123456788@foo.com') + self.assertRaisesMessage( + ValidationError, "'Ensure this value has at most 15 characters (it has 20).'", + f.clean, 'alf123456788@foo.com' + ) # FileField ################################################################## @@ -783,19 +851,43 @@ class FieldsTests(SimpleTestCase): self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None, '') self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) - self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, SimpleUploadedFile('', b'')) - self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, SimpleUploadedFile('', b''), '') + self.assertRaisesMessage( + ValidationError, "'No file was submitted. Check the encoding type on the form.'", + f.clean, SimpleUploadedFile('', b'') + ) + self.assertRaisesMessage( + ValidationError, "'No file was submitted. Check the encoding type on the form.'", + f.clean, SimpleUploadedFile('', b''), '' + ) self.assertEqual('files/test3.pdf', f.clean(None, 'files/test3.pdf')) - self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, 'some content that is not a file') - self.assertRaisesMessage(ValidationError, "'The submitted file is empty.'", f.clean, SimpleUploadedFile('name', None)) - self.assertRaisesMessage(ValidationError, "'The submitted file is empty.'", f.clean, SimpleUploadedFile('name', b'')) + self.assertRaisesMessage( + ValidationError, "'No file was submitted. Check the encoding type on the form.'", + f.clean, 'some content that is not a file' + ) + self.assertRaisesMessage( + ValidationError, "'The submitted file is empty.'", + f.clean, SimpleUploadedFile('name', None) + ) + self.assertRaisesMessage( + ValidationError, "'The submitted file is empty.'", + f.clean, SimpleUploadedFile('name', b'') + ) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content')))) - self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))))) - self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content'), 'files/test4.pdf'))) + self.assertIsInstance( + f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))), + SimpleUploadedFile + ) + self.assertIsInstance( + f.clean(SimpleUploadedFile('name', b'Some File Content'), 'files/test4.pdf'), + SimpleUploadedFile + ) def test_filefield_2(self): f = FileField(max_length=5) - self.assertRaisesMessage(ValidationError, "'Ensure this filename has at most 5 characters (it has 18).'", f.clean, SimpleUploadedFile('test_maxlength.txt', b'hello world')) + self.assertRaisesMessage( + ValidationError, "'Ensure this filename has at most 5 characters (it has 18).'", + f.clean, SimpleUploadedFile('test_maxlength.txt', b'hello world') + ) self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf')) self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content')))) @@ -897,8 +989,14 @@ class FieldsTests(SimpleTestCase): self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://inv-.alid-.com') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://inv-.-alid.com') self.assertEqual('http://valid-----hyphens.com', f.clean('http://valid-----hyphens.com')) - self.assertEqual('http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah', f.clean('http://some.idn.xyzäöüßabc.domain.com:123/blah')) - self.assertEqual('http://www.example.com/s/http://code.djangoproject.com/ticket/13804', f.clean('www.example.com/s/http://code.djangoproject.com/ticket/13804')) + self.assertEqual( + 'http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah', + f.clean('http://some.idn.xyzäöüßabc.domain.com:123/blah') + ) + self.assertEqual( + 'http://www.example.com/s/http://code.djangoproject.com/ticket/13804', + f.clean('www.example.com/s/http://code.djangoproject.com/ticket/13804') + ) self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, '[a') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://[a') @@ -926,9 +1024,15 @@ class FieldsTests(SimpleTestCase): def test_urlfield_5(self): f = URLField(min_length=15, max_length=20) self.assertWidgetRendersTo(f, '') - self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 15 characters (it has 12).'", f.clean, 'http://f.com') + self.assertRaisesMessage( + ValidationError, "'Ensure this value has at least 15 characters (it has 12).'", + f.clean, 'http://f.com' + ) self.assertEqual('http://example.com', f.clean('http://example.com')) - self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 37).'", f.clean, 'http://abcdefghijklmnopqrstuvwxyz.com') + self.assertRaisesMessage( + ValidationError, "'Ensure this value has at most 20 characters (it has 37).'", + f.clean, 'http://abcdefghijklmnopqrstuvwxyz.com' + ) def test_urlfield_6(self): f = URLField(required=False) @@ -1033,7 +1137,10 @@ class FieldsTests(SimpleTestCase): self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertEqual('1', f.clean(1)) self.assertEqual('1', f.clean('1')) - self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, '3') + self.assertRaisesMessage( + ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", + f.clean, '3' + ) def test_choicefield_2(self): f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) @@ -1041,22 +1148,36 @@ class FieldsTests(SimpleTestCase): self.assertEqual('', f.clean(None)) self.assertEqual('1', f.clean(1)) self.assertEqual('1', f.clean('1')) - self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, '3') + self.assertRaisesMessage( + ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", + f.clean, '3' + ) def test_choicefield_3(self): f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')]) self.assertEqual('J', f.clean('J')) - self.assertRaisesMessage(ValidationError, "'Select a valid choice. John is not one of the available choices.'", f.clean, 'John') + self.assertRaisesMessage( + ValidationError, "'Select a valid choice. John is not one of the available choices.'", + f.clean, 'John' + ) def test_choicefield_4(self): - f = ChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other')]) + f = ChoiceField( + choices=[ + ('Numbers', (('1', 'One'), ('2', 'Two'))), + ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other'), + ] + ) self.assertEqual('1', f.clean(1)) self.assertEqual('1', f.clean('1')) self.assertEqual('3', f.clean(3)) self.assertEqual('3', f.clean('3')) self.assertEqual('5', f.clean(5)) self.assertEqual('5', f.clean('5')) - self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, '6') + self.assertRaisesMessage( + ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", + f.clean, '6' + ) def test_choicefield_callable(self): choices = lambda: [('J', 'John'), ('P', 'Paul')] @@ -1093,7 +1214,10 @@ class FieldsTests(SimpleTestCase): def test_typedchoicefield_1(self): f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual(1, f.clean('1')) - self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, '2') + self.assertRaisesMessage( + ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", + f.clean, '2' + ) def test_typedchoicefield_2(self): # Different coercion, same validation. @@ -1109,7 +1233,10 @@ class FieldsTests(SimpleTestCase): # Even more weirdness: if you have a valid choice but your coercion function # can't coerce, you'll still get a validation error. Don't do this! f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) - self.assertRaisesMessage(ValidationError, "'Select a valid choice. B is not one of the available choices.'", f.clean, 'B') + self.assertRaisesMessage( + ValidationError, "'Select a valid choice. B is not one of the available choices.'", + f.clean, 'B' + ) # Required fields require values self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') @@ -1140,11 +1267,14 @@ class FieldsTests(SimpleTestCase): f = TypedChoiceField(choices=[(1, "1"), (2, "2")], coerce=coerce_func, required=True) self.assertEqual(Decimal('1.2'), f.clean('2')) - self.assertRaisesMessage(ValidationError, - "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, - "'Select a valid choice. 3 is not one of the available choices.'", - f.clean, '3') + self.assertRaisesMessage( + ValidationError, "'This field is required.'", + f.clean, '' + ) + self.assertRaisesMessage( + ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", + f.clean, '3' + ) # NullBooleanField ############################################################ @@ -1168,7 +1298,11 @@ class FieldsTests(SimpleTestCase): hidden_nullbool1 = NullBooleanField(widget=HiddenInput, initial=True) hidden_nullbool2 = NullBooleanField(widget=HiddenInput, initial=False) f = HiddenNullBooleanForm() - self.assertHTMLEqual('', str(f)) + self.assertHTMLEqual( + '' + '', + str(f) + ) def test_nullbooleanfield_3(self): class HiddenNullBooleanForm(Form): @@ -1218,7 +1352,10 @@ class FieldsTests(SimpleTestCase): self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, []) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, ()) - self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, ['3']) + self.assertRaisesMessage( + ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", + f.clean, ['3'] + ) def test_multiplechoicefield_2(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) @@ -1232,18 +1369,29 @@ class FieldsTests(SimpleTestCase): self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') self.assertEqual([], f.clean([])) self.assertEqual([], f.clean(())) - self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, ['3']) + self.assertRaisesMessage( + ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", + f.clean, ['3'] + ) def test_multiplechoicefield_3(self): - f = MultipleChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other')]) + f = MultipleChoiceField( + choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other')] + ) self.assertEqual(['1'], f.clean([1])) self.assertEqual(['1'], f.clean(['1'])) self.assertEqual(['1', '5'], f.clean([1, 5])) self.assertEqual(['1', '5'], f.clean([1, '5'])) self.assertEqual(['1', '5'], f.clean(['1', 5])) self.assertEqual(['1', '5'], f.clean(['1', '5'])) - self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, ['6']) - self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, ['1', '6']) + self.assertRaisesMessage( + ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", + f.clean, ['6'] + ) + self.assertRaisesMessage( + ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", + f.clean, ['1', '6'] + ) def test_multiplechoicefield_changed(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two'), ('3', 'Three')]) @@ -1262,7 +1410,10 @@ class FieldsTests(SimpleTestCase): def test_typedmultiplechoicefield_1(self): f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual([1], f.clean(['1'])) - self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, ['2']) + self.assertRaisesMessage( + ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", + f.clean, ['2'] + ) def test_typedmultiplechoicefield_2(self): # Different coercion, same validation. @@ -1277,13 +1428,19 @@ class FieldsTests(SimpleTestCase): def test_typedmultiplechoicefield_4(self): f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual([1, -1], f.clean(['1', '-1'])) - self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, ['1', '2']) + self.assertRaisesMessage( + ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", + f.clean, ['1', '2'] + ) def test_typedmultiplechoicefield_5(self): # Even more weirdness: if you have a valid choice but your coercion function # can't coerce, you'll still get a validation error. Don't do this! f = TypedMultipleChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) - self.assertRaisesMessage(ValidationError, "'Select a valid choice. B is not one of the available choices.'", f.clean, ['B']) + self.assertRaisesMessage( + ValidationError, "'Select a valid choice. B is not one of the available choices.'", + f.clean, ['B'] + ) # Required fields require values self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, []) @@ -1324,7 +1481,10 @@ class FieldsTests(SimpleTestCase): def test_combofield_1(self): f = ComboField(fields=[CharField(max_length=20), EmailField()]) self.assertEqual('test@example.com', f.clean('test@example.com')) - self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", f.clean, 'longemailaddress@example.com') + self.assertRaisesMessage( + ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", + f.clean, 'longemailaddress@example.com' + ) self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'not an email') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) @@ -1332,7 +1492,10 @@ class FieldsTests(SimpleTestCase): def test_combofield_2(self): f = ComboField(fields=[CharField(max_length=20), EmailField()], required=False) self.assertEqual('test@example.com', f.clean('test@example.com')) - self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", f.clean, 'longemailaddress@example.com') + self.assertRaisesMessage( + ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", + f.clean, 'longemailaddress@example.com' + ) self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'not an email') self.assertEqual('', f.clean('')) self.assertEqual('', f.clean(None)) @@ -1362,7 +1525,10 @@ class FieldsTests(SimpleTestCase): for exp, got in zip(expected, fix_os_paths(f.choices)): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0])) - self.assertRaisesMessage(ValidationError, "'Select a valid choice. fields.py is not one of the available choices.'", f.clean, 'fields.py') + self.assertRaisesMessage( + ValidationError, "'Select a valid choice. fields.py is not one of the available choices.'", + f.clean, 'fields.py' + ) assert fix_os_paths(f.clean(path + 'fields.py')).endswith('/django/forms/fields.py') def test_filepathfield_3(self): @@ -1437,24 +1603,36 @@ class FieldsTests(SimpleTestCase): from django.forms.widgets import SplitDateTimeWidget f = SplitDateTimeField() self.assertIsInstance(f.widget, SplitDateTimeWidget) - self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)])) + self.assertEqual( + datetime.datetime(2006, 1, 10, 7, 30), + f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)]) + ) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') - six.assertRaisesRegex(self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there']) + six.assertRaisesRegex( + self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", + f.clean, ['hello', 'there'] + ) self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there']) self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30']) def test_splitdatetimefield_2(self): f = SplitDateTimeField(required=False) - self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)])) + self.assertEqual( + datetime.datetime(2006, 1, 10, 7, 30), + f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)]) + ) self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean(['2006-01-10', '07:30'])) self.assertIsNone(f.clean(None)) self.assertIsNone(f.clean('')) self.assertIsNone(f.clean([''])) self.assertIsNone(f.clean(['', ''])) self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') - six.assertRaisesRegex(self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there']) + six.assertRaisesRegex( + self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", + f.clean, ['hello', 'there'] + ) self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there']) self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30']) self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', '']) @@ -1489,7 +1667,10 @@ class FieldsTests(SimpleTestCase): self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a') self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '12345:2:3:4') self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3::4') - self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, 'foo::223:6cff:fe8a:2e8a') + self.assertRaisesMessage( + ValidationError, "'This is not a valid IPv6 address.'", + f.clean, 'foo::223:6cff:fe8a:2e8a' + ) self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3:4:5:6:7:8') self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1:2') @@ -1518,7 +1699,10 @@ class FieldsTests(SimpleTestCase): self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a') self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '12345:2:3:4') self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3::4') - self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, 'foo::223:6cff:fe8a:2e8a') + self.assertRaisesMessage( + ValidationError, "'This is not a valid IPv6 address.'", + f.clean, 'foo::223:6cff:fe8a:2e8a' + ) self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3:4:5:6:7:8') self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1:2') @@ -1535,7 +1719,10 @@ class FieldsTests(SimpleTestCase): self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a') self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '12345:2:3:4') self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3::4') - self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, 'foo::223:6cff:fe8a:2e8a') + self.assertRaisesMessage( + ValidationError, "'This is not a valid IPv6 address.'", + f.clean, 'foo::223:6cff:fe8a:2e8a' + ) self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3:4:5:6:7:8') self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1:2') diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py index d8cdabae2d..ac96d775a2 100644 --- a/tests/forms_tests/tests/test_forms.py +++ b/tests/forms_tests/tests/test_forms.py @@ -58,9 +58,18 @@ class FormsTestCase(SimpleTestCase): self.assertEqual(p.cleaned_data["first_name"], 'John') self.assertEqual(p.cleaned_data["last_name"], 'Lennon') self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) - self.assertHTMLEqual(str(p['first_name']), '') - self.assertHTMLEqual(str(p['last_name']), '') - self.assertHTMLEqual(str(p['birthday']), '') + self.assertHTMLEqual( + str(p['first_name']), + '' + ) + self.assertHTMLEqual( + str(p['last_name']), + '' + ) + self.assertHTMLEqual( + str(p['birthday']), + '' + ) nonexistenterror = "Key u?'nonexistentfield' not found in 'Person'" with six.assertRaisesRegex(self, KeyError, nonexistenterror): @@ -72,9 +81,12 @@ class FormsTestCase(SimpleTestCase): for boundfield in p: form_output.append(str(boundfield)) - self.assertHTMLEqual('\n'.join(form_output), """ + self.assertHTMLEqual( + '\n'.join(form_output), + """ -""") +""" + ) form_output = [] @@ -86,9 +98,15 @@ class FormsTestCase(SimpleTestCase): ['Last name', 'Lennon'], ['Birthday', '1940-10-9'] ]) - self.assertHTMLEqual(str(p), """ - -""") + self.assertHTMLEqual( + str(p), + """ + + + + +""" + ) def test_empty_dict(self): # Empty dictionaries are valid, too. @@ -99,21 +117,54 @@ class FormsTestCase(SimpleTestCase): self.assertEqual(p.errors['birthday'], ['This field is required.']) self.assertFalse(p.is_valid()) self.assertEqual(p.cleaned_data, {}) - self.assertHTMLEqual(str(p), """
        • This field is required.
        -
        • This field is required.
        -
        • This field is required.
        """) - self.assertHTMLEqual(p.as_table(), """
        • This field is required.
        -
        • This field is required.
        -
        • This field is required.
        """) - self.assertHTMLEqual(p.as_ul(), """
        • This field is required.
      • -
        • This field is required.
      • -
        • This field is required.
      • """) - self.assertHTMLEqual(p.as_p(), """
        • This field is required.
        -

        + self.assertHTMLEqual( + str(p), + """
        • This field is required.
        -

        + + +
        • This field is required.
        + +
        • This field is required.
        -

        """) +""" + ) + self.assertHTMLEqual( + p.as_table(), + """ +
        • This field is required.
        + + +
        • This field is required.
        + + +
        • This field is required.
        +""" + ) + self.assertHTMLEqual( + p.as_ul(), + """
        • This field is required.
        + +
      • +
        • This field is required.
        + +
      • +
        • This field is required.
        + +
      • """ + ) + self.assertHTMLEqual( + p.as_p(), + """
        • This field is required.
        +

        +

        +
        • This field is required.
        +

        +

        +
        • This field is required.
        +

        +

        """ + ) def test_unbound_form(self): # If you don't pass any values to the Form's __init__(), or if you pass None, @@ -128,34 +179,96 @@ class FormsTestCase(SimpleTestCase): self.fail('Attempts to access cleaned_data when validation fails should fail.') except AttributeError: pass - self.assertHTMLEqual(str(p), """ - -""") - self.assertHTMLEqual(p.as_table(), """ - -""") - self.assertHTMLEqual(p.as_ul(), """
      • -
      • -
      • """) - self.assertHTMLEqual(p.as_p(), """

        -

        -

        """) + self.assertHTMLEqual( + str(p), + """ + + + + +""" + ) + self.assertHTMLEqual( + p.as_table(), + """ + + + + +""" + ) + self.assertHTMLEqual( + p.as_ul(), + """
      • +
      • +
      • +
      • +
      • +
      • """ + ) + self.assertHTMLEqual( + p.as_p(), + """

        +

        +

        +

        +

        +

        """ + ) def test_unicode_values(self): # Unicode values are handled properly. - p = Person({'first_name': 'John', 'last_name': '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9'}) - self.assertHTMLEqual(p.as_table(), '\n\n') - self.assertHTMLEqual(p.as_ul(), '
      • \n
      • \n
      • ') - self.assertHTMLEqual(p.as_p(), '

        \n

        \n

        ') + p = Person({ + 'first_name': 'John', + 'last_name': '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', + 'birthday': '1940-10-9' + }) + self.assertHTMLEqual( + p.as_table(), + '' + '\n' + '' + '\n' + '' + '' + ) + self.assertHTMLEqual( + p.as_ul(), + '
      • ' + '
      • \n' + '
      • ' + '
      • \n' + '
      • ' + '
      • ' + ) + self.assertHTMLEqual( + p.as_p(), + '

        ' + '

        \n' + '

        ' + '

        \n' + '

        ' + '

        ' + ) p = Person({'last_name': 'Lennon'}) self.assertEqual(p.errors['first_name'], ['This field is required.']) self.assertEqual(p.errors['birthday'], ['This field is required.']) self.assertFalse(p.is_valid()) - self.assertDictEqual(p.errors, {'birthday': ['This field is required.'], 'first_name': ['This field is required.']}) + self.assertDictEqual( + p.errors, + {'birthday': ['This field is required.'], 'first_name': ['This field is required.']} + ) self.assertEqual(p.cleaned_data, {'last_name': 'Lennon'}) self.assertEqual(p['first_name'].errors, ['This field is required.']) - self.assertHTMLEqual(p['first_name'].errors.as_ul(), '
        • This field is required.
        ') + self.assertHTMLEqual( + p['first_name'].errors.as_ul(), + '
        • This field is required.
        ' + ) self.assertEqual(p['first_name'].errors.as_text(), '* This field is required.') p = Person() @@ -168,7 +281,13 @@ class FormsTestCase(SimpleTestCase): # Form, even if you pass extra data when you define the Form. In this # example, we pass a bunch of extra fields to the form constructor, # but cleaned_data contains only the form's fields. - data = {'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9', 'extra1': 'hello', 'extra2': 'hello'} + data = { + 'first_name': 'John', + 'last_name': 'Lennon', + 'birthday': '1940-10-9', + 'extra1': 'hello', + 'extra2': 'hello', + } p = Person(data) self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data['first_name'], 'John') @@ -212,47 +331,84 @@ class FormsTestCase(SimpleTestCase): # into which the field's name will be inserted. It will also put a
      """) +
    """ + ) # When RadioSelect is used with auto_id, and the whole form is printed using # either as_table() or as_ul(), the label for the RadioSelect will point to the # ID of the *first* radio button. - self.assertHTMLEqual(f.as_table(), """ + self.assertHTMLEqual( + f.as_table(), + """
    • -
    """) - self.assertHTMLEqual(f.as_ul(), """
  • +""" + ) + self.assertHTMLEqual( + f.as_ul(), + """
    • -
  • """) - self.assertHTMLEqual(f.as_p(), """

    +""" + ) + self.assertHTMLEqual( + f.as_p(), + """

    • -

    """) +

    """ + ) # Test iterating on individual radios in a template t = Template('{% for radio in form.language %}
    {{ radio }}
    {% endfor %}') - self.assertHTMLEqual(t.render(Context({'form': f})), """
    """ + ) def test_form_with_iterable_boundfield(self): class BeatleForm(Form): - name = ChoiceField(choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')], widget=RadioSelect) + name = ChoiceField( + choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')], + widget=RadioSelect, + ) f = BeatleForm(auto_id=False) - self.assertHTMLEqual('\n'.join(str(bf) for bf in f['name']), """ + self.assertHTMLEqual( + '\n'.join(str(bf) for bf in f['name']), + """ -""") - self.assertHTMLEqual('\n'.join('
    %s
    ' % bf for bf in f['name']), """
    +""" + ) + self.assertHTMLEqual( + '\n'.join('
    %s
    ' % bf for bf in f['name']), + """
    -
    """) +
    """ + ) def test_form_with_noniterable_boundfield(self): # You can iterate over any BoundField, not just those with widget=RadioSelect. @@ -552,14 +738,25 @@ class FormsTestCase(SimpleTestCase): f = MessageForm({'when_0': '1992-01-01', 'when_1': '01:01'}) self.assertTrue(f.is_valid()) - self.assertHTMLEqual(str(f['when']), '') - self.assertHTMLEqual(f['when'].as_hidden(), '') + self.assertHTMLEqual( + str(f['when']), + '' + '' + ) + self.assertHTMLEqual( + f['when'].as_hidden(), + '' + '' + ) def test_mulitple_choice_checkbox(self): # MultipleChoiceField can also be used with the CheckboxSelectMultiple widget. class SongForm(Form): name = CharField() - composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple) + composers = MultipleChoiceField( + choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], + widget=CheckboxSelectMultiple, + ) f = SongForm(auto_id=False) self.assertHTMLEqual(str(f['composers']), """
      @@ -589,20 +786,31 @@ class FormsTestCase(SimpleTestCase): # zero-based index. class SongForm(Form): name = CharField() - composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple) + composers = MultipleChoiceField( + choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], + widget=CheckboxSelectMultiple, + ) f = SongForm(auto_id='%s_id') - self.assertHTMLEqual(str(f['composers']), """
        -
      • -
      • -
      """) + self.assertHTMLEqual( + str(f['composers']), + """
        +
      • +
      • +
      """ + ) def test_multiple_choice_list_data(self): # Data for a MultipleChoiceField should be a list. QueryDict and # MultiValueDict conveniently work with this. class SongForm(Form): name = CharField() - composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple) + composers = MultipleChoiceField( + choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], + widget=CheckboxSelectMultiple, + ) data = {'name': 'Yesterday', 'composers': ['J', 'P']} f = SongForm(data) @@ -619,16 +827,26 @@ class FormsTestCase(SimpleTestCase): def test_multiple_hidden(self): class SongForm(Form): name = CharField() - composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple) + composers = MultipleChoiceField( + choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], + widget=CheckboxSelectMultiple, + ) # The MultipleHiddenInput widget renders multiple values as hidden fields. class SongFormHidden(Form): name = CharField() - composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=MultipleHiddenInput) + composers = MultipleChoiceField( + choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], + widget=MultipleHiddenInput, + ) f = SongFormHidden(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])), auto_id=False) - self.assertHTMLEqual(f.as_ul(), """
    • Name: -
    • """) + self.assertHTMLEqual( + f.as_ul(), + """
    • Name: + +
    • """ + ) # When using CheckboxSelectMultiple, the framework expects a list of input and # returns a list of input. @@ -653,17 +871,39 @@ class FormsTestCase(SimpleTestCase): raise ValidationError("Something's wrong with '%s'" % self.cleaned_data['special_name']) def clean_special_safe_name(self): - raise ValidationError(mark_safe("'%s' is a safe string" % self.cleaned_data['special_safe_name'])) + raise ValidationError( + mark_safe("'%s' is a safe string" % self.cleaned_data['special_safe_name']) + ) - f = EscapingForm({'special_name': "Nothing to escape", 'special_safe_name': "Nothing to escape"}, auto_id=False) - self.assertHTMLEqual(f.as_table(), """<em>Special</em> Field:
      • Something's wrong with 'Nothing to escape'
      -Special Field:
      • 'Nothing to escape' is a safe string
      """) + f = EscapingForm({ + 'special_name': + "Nothing to escape", + 'special_safe_name': "Nothing to escape", + }, auto_id=False) + self.assertHTMLEqual( + f.as_table(), + """<em>Special</em> Field: +
      • Something's wrong with 'Nothing to escape'
      + +Special Field: +
      • 'Nothing to escape' is a safe string
      +""" + ) f = EscapingForm({ 'special_name': "Should escape < & > and ", 'special_safe_name': "Do not escape" }, auto_id=False) - self.assertHTMLEqual(f.as_table(), """<em>Special</em> Field:
      • Something's wrong with 'Should escape < & > and <script>alert('xss')</script>'
      -Special Field:
      • 'Do not escape' is a safe string
      """) + self.assertHTMLEqual( + f.as_table(), + """<em>Special</em> Field: +
      • Something's wrong with 'Should escape < & > and +<script>alert('xss')</script>'
      + +Special Field: +
      • 'Do not escape' is a safe string
      +""" + ) def test_validating_multiple_fields(self): # There are a couple of ways to do multiple-field validation. If you want the @@ -679,7 +919,8 @@ class FormsTestCase(SimpleTestCase): password2 = CharField(widget=PasswordInput) def clean_password2(self): - if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: + if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') + and self.cleaned_data['password1'] != self.cleaned_data['password2']): raise ValidationError('Please make sure your passwords match.') return self.cleaned_data['password2'] @@ -717,7 +958,8 @@ class FormsTestCase(SimpleTestCase): def clean(self): # Test raising a ValidationError as NON_FIELD_ERRORS. - if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: + if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') + and self.cleaned_data['password1'] != self.cleaned_data['password2']): raise ValidationError('Please make sure your passwords match.') # Test raising ValidationError that targets multiple fields. @@ -743,23 +985,38 @@ class FormsTestCase(SimpleTestCase): self.assertEqual(f.errors, {}) f = UserRegistration({}, auto_id=False) - self.assertHTMLEqual(f.as_table(), """Username:
      • This field is required.
      -Password1:
      • This field is required.
      -Password2:
      • This field is required.
      """) + self.assertHTMLEqual( + f.as_table(), + """Username: +
      • This field is required.
      + +Password1:
      • This field is required.
      + +Password2:
      • This field is required.
      +""" + ) self.assertEqual(f.errors['username'], ['This field is required.']) self.assertEqual(f.errors['password1'], ['This field is required.']) self.assertEqual(f.errors['password2'], ['This field is required.']) f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) self.assertEqual(f.errors['__all__'], ['Please make sure your passwords match.']) - self.assertHTMLEqual(f.as_table(), """
      • Please make sure your passwords match.
      + self.assertHTMLEqual( + f.as_table(), + """ +
      • Please make sure your passwords match.
      Username: Password1: -Password2:""") - self.assertHTMLEqual(f.as_ul(), """
      • Please make sure your passwords match.
    • +Password2:""" + ) + self.assertHTMLEqual( + f.as_ul(), + """
      • +
      • Please make sure your passwords match.
    • Username:
    • Password1:
    • -
    • Password2:
    • """) +
    • Password2:
    • """ + ) f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False) self.assertEqual(f.errors, {}) @@ -767,11 +1024,19 @@ class FormsTestCase(SimpleTestCase): self.assertEqual(f.cleaned_data['password1'], 'foo') self.assertEqual(f.cleaned_data['password2'], 'foo') - f = UserRegistration({'username': 'adrian', 'password1': 'FORBIDDEN_VALUE', 'password2': 'FORBIDDEN_VALUE'}, auto_id=False) + f = UserRegistration({ + 'username': 'adrian', + 'password1': 'FORBIDDEN_VALUE', + 'password2': 'FORBIDDEN_VALUE', + }, auto_id=False) self.assertEqual(f.errors['password1'], ['Forbidden value.']) self.assertEqual(f.errors['password2'], ['Forbidden value.']) - f = UserRegistration({'username': 'adrian', 'password1': 'FORBIDDEN_VALUE2', 'password2': 'FORBIDDEN_VALUE2'}, auto_id=False) + f = UserRegistration({ + 'username': 'adrian', + 'password1': 'FORBIDDEN_VALUE2', + 'password2': 'FORBIDDEN_VALUE2', + }, auto_id=False) self.assertEqual(f.errors['__all__'], ['Non-field error 1.', 'Non-field error 2.']) self.assertEqual(f.errors['password1'], ['Forbidden value 2.']) self.assertEqual(f.errors['password2'], ['Forbidden value 2.']) @@ -872,9 +1137,12 @@ class FormsTestCase(SimpleTestCase): self.fields['birthday'] = DateField() p = Person(auto_id=False) - self.assertHTMLEqual(p.as_table(), """First name: + self.assertHTMLEqual( + p.as_table(), + """First name: Last name: -Birthday:""") +Birthday:""" + ) # Instances of a dynamic Form do not persist fields from one Form instance to # the next. @@ -887,12 +1155,18 @@ class FormsTestCase(SimpleTestCase): field_list = [('field1', CharField()), ('field2', CharField())] my_form = MyForm(field_list=field_list) - self.assertHTMLEqual(my_form.as_table(), """Field1: -Field2:""") + self.assertHTMLEqual( + my_form.as_table(), + """Field1: +Field2:""" + ) field_list = [('field3', CharField()), ('field4', CharField())] my_form = MyForm(field_list=field_list) - self.assertHTMLEqual(my_form.as_table(), """Field3: -Field4:""") + self.assertHTMLEqual( + my_form.as_table(), + """Field3: +Field4:""" + ) class MyForm(Form): default_field_1 = CharField() @@ -906,16 +1180,22 @@ class FormsTestCase(SimpleTestCase): field_list = [('field1', CharField()), ('field2', CharField())] my_form = MyForm(field_list=field_list) - self.assertHTMLEqual(my_form.as_table(), """Default field 1: + self.assertHTMLEqual( + my_form.as_table(), + """Default field 1: Default field 2: Field1: -Field2:""") +Field2:""" + ) field_list = [('field3', CharField()), ('field4', CharField())] my_form = MyForm(field_list=field_list) - self.assertHTMLEqual(my_form.as_table(), """Default field 1: + self.assertHTMLEqual( + my_form.as_table(), + """Default field 1: Default field 2: Field3: -Field4:""") +Field4:""" + ) # Similarly, changes to field attributes do not persist from one Form instance # to the next. @@ -937,7 +1217,11 @@ class FormsTestCase(SimpleTestCase): self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {})) f = Person(names_required=True) self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (True, True)) - self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({'class': 'required'}, {'class': 'required'})) + self.assertEqual( + f['first_name'].field.widget.attrs, + f['last_name'].field.widget.attrs, + ({'class': 'reuired'}, {'class': 'required'}) + ) f = Person(names_required=False) self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False)) self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {})) @@ -1006,45 +1290,87 @@ class FormsTestCase(SimpleTestCase): birthday = DateField() p = Person(auto_id=False) - self.assertHTMLEqual(p.as_table(), """First name: + self.assertHTMLEqual( + p.as_table(), + """First name: Last name: -Birthday:""") - self.assertHTMLEqual(p.as_ul(), """
    • First name:
    • +Birthday:""" + ) + self.assertHTMLEqual( + p.as_ul(), + """
    • First name:
    • Last name:
    • -
    • Birthday:
    • """) - self.assertHTMLEqual(p.as_p(), """

      First name:

      +
    • Birthday:
    • """ + ) + self.assertHTMLEqual( + p.as_p(), """

      First name:

      Last name:

      -

      Birthday:

      """) +

      Birthday:

      """ + ) # With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label. p = Person(auto_id='id_%s') - self.assertHTMLEqual(p.as_table(), """ - -""") - self.assertHTMLEqual(p.as_ul(), """
    • -
    • -
    • """) - self.assertHTMLEqual(p.as_p(), """

      -

      -

      """) + self.assertHTMLEqual( + p.as_table(), + """ + + + + + +""" + ) + self.assertHTMLEqual( + p.as_ul(), + """
    • +
    • +
    • +
    • +
    • + +
    • """ + ) + self.assertHTMLEqual( + p.as_p(), + """

      +

      +

      +

      +

      + +

      """ + ) # If a field with a HiddenInput has errors, the as_table() and as_ul() output # will include the error message(s) with the text "(Hidden field [fieldname]) " # prepended. This message is displayed at the top of the output, regardless of # its field's order in the form. p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}, auto_id=False) - self.assertHTMLEqual(p.as_table(), """
      • (Hidden field hidden_text) This field is required.
      + self.assertHTMLEqual( + p.as_table(), + """ +
      • (Hidden field hidden_text) This field is required.
      First name: Last name: -Birthday:""") - self.assertHTMLEqual(p.as_ul(), """
      • (Hidden field hidden_text) This field is required.
    • +Birthday: +""" + ) + self.assertHTMLEqual( + p.as_ul(), + """
      • (Hidden field hidden_text) This field is required.
    • First name:
    • Last name:
    • -
    • Birthday:
    • """) - self.assertHTMLEqual(p.as_p(), """
      • (Hidden field hidden_text) This field is required.
      +
    • Birthday: +
    • """ + ) + self.assertHTMLEqual( + p.as_p(), + """
      • (Hidden field hidden_text) This field is required.

      First name:

      Last name:

      -

      Birthday:

      """) +

      Birthday:

      """ + ) # A corner case: It's possible for a form to have only HiddenInputs. class TestForm(Form): @@ -1145,7 +1471,8 @@ class FormsTestCase(SimpleTestCase): address = CharField() # no max_length defined here p = UserRegistration(auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Username:
    • + self.assertHTMLEqual(p.as_ul(), + """
    • Username:
    • Password:
    • Realname:
    • Address:
    • """) @@ -1158,7 +1485,8 @@ class FormsTestCase(SimpleTestCase): password = CharField(max_length=10, widget=PasswordInput) p = UserRegistration(auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Username:
    • + self.assertHTMLEqual(p.as_ul(), + """
    • Username:
    • Password:
    • """) def test_specifying_labels(self): @@ -1171,7 +1499,8 @@ class FormsTestCase(SimpleTestCase): password2 = CharField(widget=PasswordInput, label='Contraseña (de nuevo)') p = UserRegistration(auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Your username:
    • + self.assertHTMLEqual(p.as_ul(), + """
    • Your username:
    • Password1:
    • Contraseña (de nuevo):
    • """) @@ -1184,16 +1513,22 @@ class FormsTestCase(SimpleTestCase): q4 = CharField(label='Answer this question!') q5 = CharField(label='The last question. Period.') - self.assertHTMLEqual(Questions(auto_id=False).as_p(), """

      The first question:

      + self.assertHTMLEqual( + Questions(auto_id=False).as_p(), + """

      The first question:

      What is your name?

      The answer to life is:

      Answer this question!

      -

      The last question. Period.

      """) - self.assertHTMLEqual(Questions().as_p(), """

      +

      The last question. Period.

      """ + ) + self.assertHTMLEqual( + Questions().as_p(), + """

      -

      """) +

      """ + ) # If a label is set to the empty string for a field, that field won't get a label. class UserRegistration(Form): @@ -1204,8 +1539,11 @@ class FormsTestCase(SimpleTestCase): self.assertHTMLEqual(p.as_ul(), """
    • Password:
    • """) p = UserRegistration(auto_id='id_%s') - self.assertHTMLEqual(p.as_ul(), """
    • -
    • """) + self.assertHTMLEqual( + p.as_ul(), + """
    • +
    • """ + ) # If label is None, Django will auto-create the label from the field name. This # is default behavior. @@ -1214,11 +1552,16 @@ class FormsTestCase(SimpleTestCase): password = CharField(widget=PasswordInput) p = UserRegistration(auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Username:
    • + self.assertHTMLEqual(p.as_ul(), + """
    • Username:
    • Password:
    • """) p = UserRegistration(auto_id='id_%s') - self.assertHTMLEqual(p.as_ul(), """
    • -
    • """) + self.assertHTMLEqual( + p.as_ul(), + """
    • +
    • +
    • """ + ) def test_label_suffix(self): # You can specify the 'label_suffix' argument to a Form class to modify the @@ -1247,7 +1590,12 @@ class FormsTestCase(SimpleTestCase):
    • Secret answer =
    • """) f = FavoriteForm(auto_id=False, label_suffix='\u2192') - self.assertHTMLEqual(f.as_ul(), '
    • Favorite color?
    • \n
    • Favorite animal\u2192
    • \n
    • Secret answer =
    • ') + self.assertHTMLEqual( + f.as_ul(), + '
    • Favorite color?
    • \n' + '
    • Favorite animal\u2192
    • \n' + '
    • Secret answer =
    • ' + ) def test_initial_data(self): # You can specify initial data for a field by using the 'initial' argument to a @@ -1261,19 +1609,36 @@ class FormsTestCase(SimpleTestCase): # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration(auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Username:
    • -
    • Password:
    • """) + self.assertHTMLEqual( + p.as_ul(), + """
    • Username:
    • +
    • Password:
    • """ + ) # Here, we're submitting data, so the initial value will *not* be displayed. p = UserRegistration({}, auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
      • This field is required.
      Username:
    • -
      • This field is required.
      Password:
    • """) + self.assertHTMLEqual( + p.as_ul(), + """
      • This field is required.
      +Username:
    • +
      • This field is required.
      +Password:
    • """ + ) p = UserRegistration({'username': ''}, auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
      • This field is required.
      Username:
    • -
      • This field is required.
      Password:
    • """) + self.assertHTMLEqual( + p.as_ul(), + """
      • This field is required.
      +Username:
    • +
      • This field is required.
      +Password:
    • """ + ) p = UserRegistration({'username': 'foo'}, auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Username:
    • -
      • This field is required.
      Password:
    • """) + self.assertHTMLEqual( + p.as_ul(), + """
    • Username:
    • +
      • This field is required.
      +Password:
    • """ + ) # An 'initial' value is *not* used as a fallback if data is not provided. In this # example, we don't provide a value for 'username', and the form raises a @@ -1294,22 +1659,41 @@ class FormsTestCase(SimpleTestCase): # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration(initial={'username': 'django'}, auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Username:
    • -
    • Password:
    • """) + self.assertHTMLEqual( + p.as_ul(), + """
    • Username:
    • +
    • Password:
    • """ + ) p = UserRegistration(initial={'username': 'stephane'}, auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Username:
    • -
    • Password:
    • """) + self.assertHTMLEqual( + p.as_ul(), + """
    • Username:
    • +
    • Password:
    • """ + ) # The 'initial' parameter is meaningless if you pass data. p = UserRegistration({}, initial={'username': 'django'}, auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
      • This field is required.
      Username:
    • -
      • This field is required.
      Password:
    • """) + self.assertHTMLEqual( + p.as_ul(), + """
      • This field is required.
      +Username:
    • +
      • This field is required.
      +Password:
    • """ + ) p = UserRegistration({'username': ''}, initial={'username': 'django'}, auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
      • This field is required.
      Username:
    • -
      • This field is required.
      Password:
    • """) + self.assertHTMLEqual( + p.as_ul(), + """
      • This field is required.
      +Username:
    • +
      • This field is required.
      +Password:
    • """ + ) p = UserRegistration({'username': 'foo'}, initial={'username': 'django'}, auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Username:
    • -
      • This field is required.
      Password:
    • """) + self.assertHTMLEqual( + p.as_ul(), """
    • Username:
    • +
      • This field is required.
      +Password:
    • """ + ) # A dynamic 'initial' value is *not* used as a fallback if data is not provided. # In this example, we don't provide a value for 'username', and the form raises a @@ -1325,8 +1709,11 @@ class FormsTestCase(SimpleTestCase): password = CharField(widget=PasswordInput) p = UserRegistration(initial={'username': 'babik'}, auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Username:
    • -
    • Password:
    • """) + self.assertHTMLEqual( + p.as_ul(), + """
    • Username:
    • +
    • Password:
    • """ + ) def test_callable_initial_data(self): # The previous technique dealt with raw values as initial data, but it's also @@ -1351,39 +1738,60 @@ class FormsTestCase(SimpleTestCase): # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration(initial={'username': initial_django, 'options': initial_options}, auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Username:
    • + self.assertHTMLEqual( + p.as_ul(), + """
    • Username:
    • Password:
    • Options:
    • """) +""" + ) # The 'initial' parameter is meaningless if you pass data. p = UserRegistration({}, initial={'username': initial_django, 'options': initial_options}, auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
      • This field is required.
      Username:
    • -
      • This field is required.
      Password:
    • -
      • This field is required.
      Options:
    • +
      • This field is required.
      +Password:
    • +
      • This field is required.
      +Options:
    • """) +""" + ) p = UserRegistration({'username': ''}, initial={'username': initial_django}, auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
      • This field is required.
      Username:
    • -
      • This field is required.
      Password:
    • -
      • This field is required.
      Options:
    • +
      • This field is required.
      +Password:
    • +
      • This field is required.
      +Options:
    • """) - p = UserRegistration({'username': 'foo', 'options': ['f', 'b']}, initial={'username': initial_django}, auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Username:
    • -
      • This field is required.
      Password:
    • +""" + ) + p = UserRegistration( + {'username': 'foo', 'options': ['f', 'b']}, initial={'username': initial_django}, auto_id=False + ) + self.assertHTMLEqual( + p.as_ul(), + """
    • Username:
    • +
      • This field is required.
      +Password:
    • Options:
    • """) +""" + ) # A callable 'initial' value is *not* used as a fallback if data is not provided. # In this example, we don't provide a value for 'username', and the form raises a @@ -1397,24 +1805,33 @@ class FormsTestCase(SimpleTestCase): class UserRegistration(Form): username = CharField(max_length=10, initial=initial_django) password = CharField(widget=PasswordInput) - options = MultipleChoiceField(choices=[('f', 'foo'), ('b', 'bar'), ('w', 'whiz')], initial=initial_other_options) + options = MultipleChoiceField( + choices=[('f', 'foo'), ('b', 'bar'), ('w', 'whiz')], + initial=initial_other_options, + ) p = UserRegistration(auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Username:
    • + self.assertHTMLEqual( + p.as_ul(), + """
    • Username:
    • Password:
    • Options:
    • """) +""" + ) p = UserRegistration(initial={'username': initial_stephane, 'options': initial_options}, auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Username:
    • + self.assertHTMLEqual( + p.as_ul(), + """
    • Username:
    • Password:
    • Options:
    • """) +""" + ) def test_changed_data(self): class Person(Form): @@ -1528,17 +1945,37 @@ class FormsTestCase(SimpleTestCase): password = CharField(widget=PasswordInput, help_text='Wählen Sie mit Bedacht.') p = UserRegistration(auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Username: e.g., user@example.com
    • -
    • Password: Wählen Sie mit Bedacht.
    • """) - self.assertHTMLEqual(p.as_p(), """

      Username: e.g., user@example.com

      -

      Password: Wählen Sie mit Bedacht.

      """) - self.assertHTMLEqual(p.as_table(), """Username:
      e.g., user@example.com -Password:
      Wählen Sie mit Bedacht.""") + self.assertHTMLEqual( + p.as_ul(), + """
    • Username: +e.g., user@example.com
    • +
    • Password: +Wählen Sie mit Bedacht.
    • """ + ) + self.assertHTMLEqual( + p.as_p(), + """

      Username: +e.g., user@example.com

      +

      Password: +Wählen Sie mit Bedacht.

      """ + ) + self.assertHTMLEqual( + p.as_table(), + """Username:
      +e.g., user@example.com +Password:
      +Wählen Sie mit Bedacht.""" + ) # The help text is displayed whether or not data is provided for the form. p = UserRegistration({'username': 'foo'}, auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Username: e.g., user@example.com
    • -
      • This field is required.
      Password: Wählen Sie mit Bedacht.
    • """) + self.assertHTMLEqual( + p.as_ul(), + """
    • Username: +e.g., user@example.com
    • +
      • This field is required.
      Password: +Wählen Sie mit Bedacht.
    • """ + ) # help_text is not displayed for hidden fields. It can be used for documentation # purposes, though. @@ -1548,8 +1985,13 @@ class FormsTestCase(SimpleTestCase): next = CharField(widget=HiddenInput, initial='/', help_text='Redirect destination') p = UserRegistration(auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • Username: e.g., user@example.com
    • -
    • Password:
    • """) + self.assertHTMLEqual( + p.as_ul(), + """
    • Username: +e.g., user@example.com
    • +
    • Password: +
    • """ + ) def test_subclassing_forms(self): # You can subclass a Form to add fields. The resulting form subclass will have @@ -1564,14 +2006,20 @@ class FormsTestCase(SimpleTestCase): instrument = CharField() p = Person(auto_id=False) - self.assertHTMLEqual(p.as_ul(), """
    • First name:
    • + self.assertHTMLEqual( + p.as_ul(), + """
    • First name:
    • Last name:
    • -
    • Birthday:
    • """) +
    • Birthday:
    • """ + ) m = Musician(auto_id=False) - self.assertHTMLEqual(m.as_ul(), """
    • First name:
    • + self.assertHTMLEqual( + m.as_ul(), + """
    • First name:
    • Last name:
    • Birthday:
    • -
    • Instrument:
    • """) +
    • Instrument:
    • """ + ) # Yes, you can subclass multiple forms. The fields are added in the order in # which the parent classes are listed. @@ -1612,12 +2060,27 @@ class FormsTestCase(SimpleTestCase): 'person1-birthday': '1940-10-9' } p = Person(data, prefix='person1') - self.assertHTMLEqual(p.as_ul(), """
    • -
    • -
    • """) - self.assertHTMLEqual(str(p['first_name']), '') - self.assertHTMLEqual(str(p['last_name']), '') - self.assertHTMLEqual(str(p['birthday']), '') + self.assertHTMLEqual( + p.as_ul(), + """
    • +
    • +
    • +
    • +
    • +
    • """ + ) + self.assertHTMLEqual( + str(p['first_name']), + '' + ) + self.assertHTMLEqual( + str(p['last_name']), + '' + ) + self.assertHTMLEqual( + str(p['birthday']), + '' + ) self.assertEqual(p.errors, {}) self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data['first_name'], 'John') @@ -1688,9 +2151,15 @@ class FormsTestCase(SimpleTestCase): return '%s-prefix-%s' % (self.prefix, field_name) if self.prefix else field_name p = Person(prefix='foo') - self.assertHTMLEqual(p.as_ul(), """
    • -
    • -
    • """) + self.assertHTMLEqual( + p.as_ul(), + """
    • +
    • +
    • +
    • +
    • +
    • """ + ) data = { 'foo-prefix-first_name': 'John', 'foo-prefix-last_name': 'Lennon', @@ -1768,19 +2237,36 @@ class FormsTestCase(SimpleTestCase): self.assertHTMLEqual(f.as_table(), 'File1:') f = FileForm(data={}, files={}, auto_id=False) - self.assertHTMLEqual(f.as_table(), 'File1:
      • This field is required.
      ') + self.assertHTMLEqual( + f.as_table(), + 'File1:' + '
      • This field is required.
      ' + '' + ) f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', b'')}, auto_id=False) - self.assertHTMLEqual(f.as_table(), 'File1:
      • The submitted file is empty.
      ') + self.assertHTMLEqual( + f.as_table(), + 'File1:' + '
      • The submitted file is empty.
      ' + '' + ) f = FileForm(data={}, files={'file1': 'something that is not a file'}, auto_id=False) - self.assertHTMLEqual(f.as_table(), 'File1:
      • No file was submitted. Check the encoding type on the form.
      ') + self.assertHTMLEqual( + f.as_table(), + 'File1:' + '
      • No file was submitted. Check the ' + 'encoding type on the form.
      ' + '' + ) f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', b'some content')}, auto_id=False) self.assertHTMLEqual(f.as_table(), 'File1:') self.assertTrue(f.is_valid()) - f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))}, auto_id=False) + file1 = SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8')) + f = FileForm(data={}, files={'file1': file1}, auto_id=False) self.assertHTMLEqual(f.as_table(), 'File1:') def test_basic_processing_in_view(self): @@ -1790,7 +2276,8 @@ class FormsTestCase(SimpleTestCase): password2 = CharField(widget=PasswordInput) def clean(self): - if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: + if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') + and self.cleaned_data['password1'] != self.cleaned_data['password2']): raise ValidationError('Please make sure your passwords match.') return self.cleaned_data @@ -1804,7 +2291,10 @@ class FormsTestCase(SimpleTestCase): if form.is_valid(): return 'VALID: %r' % sorted(six.iteritems(form.cleaned_data)) - t = Template('
      \n\n{{ form }}\n
      \n\n
      ') + t = Template( + '
      \n' + '\n{{ form }}\n
      \n\n
      ' + ) return t.render(Context({'form': form})) # Case 1: GET (an empty form, with no errors).) @@ -1817,18 +2307,27 @@ class FormsTestCase(SimpleTestCase): """) # Case 2: POST with erroneous data (a redisplayed form, with errors).) - self.assertHTMLEqual(my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'}), """
      + self.assertHTMLEqual( + my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'}), + """ - +
      • Please make sure your passwords match.
      Username:
      • Ensure this value has at most 10 characters (it has 23).
      Username:
        +
      • Ensure this value has at most 10 characters (it has 23).
      +
      Password1:
      Password2:
      -
      """) +""" + ) # Case 3: POST with valid data (the success message).) - self.assertEqual(my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}), - str_prefix("VALID: [('password1', %(_)s'secret'), ('password2', %(_)s'secret'), ('username', %(_)s'adrian')]")) + self.assertEqual( + my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}), + str_prefix( + "VALID: [('password1', %(_)s'secret'), ('password2', %(_)s'secret'), ('username', %(_)s'adrian')]" + ) + ) def test_templates_with_forms(self): class UserRegistration(Form): @@ -1837,7 +2336,8 @@ class FormsTestCase(SimpleTestCase): password2 = CharField(widget=PasswordInput) def clean(self): - if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: + if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') + and self.cleaned_data['password1'] != self.cleaned_data['password2']): raise ValidationError('Please make sure your passwords match.') return self.cleaned_data @@ -1859,12 +2359,17 @@ class FormsTestCase(SimpleTestCase):

      """) - self.assertHTMLEqual(t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)})), """
      + self.assertHTMLEqual( + t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)})), + """

      -
      • This field is required.

      -
      • This field is required.

      +
      • This field is required.

      +

      +
      • This field is required.
      +

      -
      """) +""" + ) # Use form.[field].label to output a field's label. You can specify the label for # a field by using the 'label' argument to a Field class. If you don't specify @@ -1914,13 +2419,20 @@ class FormsTestCase(SimpleTestCase):

      {{ form.password2.label_tag }} {{ form.password2 }}

      ''') - self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """
      -

      Username:
      Good luck picking a username that doesn't already exist.

      + self.assertHTMLEqual( + t.render(Context({'form': UserRegistration(auto_id=False)})), + """ +

      Username:
      +Good luck picking a username that doesn't already exist.

      Password1:

      Password2:

      -
      """) - self.assertEqual(Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})), '') +""" + ) + self.assertEqual( + Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})), + '' + ) # To display the errors that aren't associated with a particular field -- e.g., # the errors caused by Form.clean() -- use {{ form.non_field_errors }} in the @@ -1932,12 +2444,17 @@ class FormsTestCase(SimpleTestCase): {{ form.password2.errors.as_ul }}

      ''') - self.assertHTMLEqual(t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})), """
      + self.assertHTMLEqual( + t.render(Context({ + 'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) + })), + """

      -
      """) +""" + ) t = Template('''
      {{ form.non_field_errors }} {{ form.username.errors.as_ul }}

      @@ -1945,13 +2462,18 @@ class FormsTestCase(SimpleTestCase): {{ form.password2.errors.as_ul }}

      ''') - self.assertHTMLEqual(t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})), """
      + self.assertHTMLEqual( + t.render(Context({ + 'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) + })), + """
      • Please make sure your passwords match.

      -
      """) +""" + ) def test_empty_permitted(self): # Sometimes (pretty much in formsets) we want to allow a form to pass validation @@ -2013,7 +2535,12 @@ class FormsTestCase(SimpleTestCase): class MyForm(Form): field1 = CharField(max_length=50, show_hidden_initial=True) - self.assertHTMLEqual(MyForm().as_table(), '') + self.assertHTMLEqual( + MyForm().as_table(), + '' + '' + '' + ) def test_error_html_required_html_classes(self): class Person(Form): @@ -2026,34 +2553,55 @@ class FormsTestCase(SimpleTestCase): p.error_css_class = 'error' p.required_css_class = 'required' - self.assertHTMLEqual(p.as_ul(), """
      • This field is required.
    • + self.assertHTMLEqual( + p.as_ul(), + """
      • This field is required.
      +
    • -
      • This field is required.
    • """) +
      • This field is required.
      +
    • """ + ) - self.assertHTMLEqual(p.as_p(), """
      • This field is required.
      -

      -

      +

      +

      • This field is required.
      -

      """) +

      +

      """ + ) - self.assertHTMLEqual(p.as_table(), """
      • This field is required.
      - + + - -
      • This field is required.
      """) + + + +
      • This field is required.
      +""" + ) def test_label_has_required_css_class(self): """ @@ -2066,8 +2614,10 @@ class FormsTestCase(SimpleTestCase): f = SomeForm({'field': 'test'}) self.assertHTMLEqual(f['field'].label_tag(), '') - self.assertHTMLEqual(f['field'].label_tag(attrs={'class': 'foo'}), - '') + self.assertHTMLEqual( + f['field'].label_tag(attrs={'class': 'foo'}), + '' + ) self.assertHTMLEqual(f['field2'].label_tag(), '') def test_label_split_datetime_not_displayed(self): @@ -2075,7 +2625,11 @@ class FormsTestCase(SimpleTestCase): happened_at = SplitDateTimeField(widget=SplitHiddenDateTimeWidget) form = EventForm() - self.assertHTMLEqual(form.as_ul(), '') + self.assertHTMLEqual( + form.as_ul(), + '' + '' + ) def test_multivalue_field_validation(self): def bad_names(value): @@ -2543,17 +3097,26 @@ class FormsTestCase(SimpleTestCase): p = Person({'first_name': 'John'}) self.assertHTMLEqual( p.as_ul(), - """
      • (Hidden field last_name) This field is required.
    • """ + """
      • +
      • (Hidden field last_name) This field is required.
    • + + +
    • """ ) self.assertHTMLEqual( p.as_p(), """
      • (Hidden field last_name) This field is required.
      -

      """ +

      + +

      """ ) self.assertHTMLEqual( p.as_table(), - """
      • (Hidden field last_name) This field is required.
      -""" + """
        +
      • (Hidden field last_name) This field is required.
      + + +""" ) def test_error_list_with_non_field_errors_has_correct_class(self): @@ -2571,8 +3134,12 @@ class FormsTestCase(SimpleTestCase): ) self.assertHTMLEqual( p.as_ul(), - """
      • Generic validation error
    • -
    • """ + """
    • +
      • Generic validation error
    • +
    • +
    • +
    • +
    • """ ) self.assertHTMLEqual( p.non_field_errors().as_text(), @@ -2581,14 +3148,18 @@ class FormsTestCase(SimpleTestCase): self.assertHTMLEqual( p.as_p(), """
      • Generic validation error
      -

      -

      """ +

      +

      +

      +

      """ ) self.assertHTMLEqual( p.as_table(), """
      • Generic validation error
      - -""" + + + +""" ) def test_errorlist_override(self): diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py index 0fea84a782..e3fb1e8005 100644 --- a/tests/forms_tests/tests/test_formsets.py +++ b/tests/forms_tests/tests/test_formsets.py @@ -101,9 +101,15 @@ class FormsFormsetTestCase(SimpleTestCase): # for adding data. By default, it displays 1 blank form. It can display more, # but we'll look at how to do so later. formset = self.make_choiceformset() - self.assertHTMLEqual(str(formset), """ + self.assertHTMLEqual( + str(formset), + """ + + + Choice: -Votes:""") +Votes:""" + ) # We treat FormSet pretty much like we would treat a normal Form. FormSet has an # is_valid method, and a cleaned_data or errors attribute depending on whether all @@ -186,10 +192,13 @@ class FormsFormsetTestCase(SimpleTestCase): for form in formset.forms: form_output.append(form.as_ul()) - self.assertHTMLEqual('\n'.join(form_output), """
    • Choice:
    • + self.assertHTMLEqual( + '\n'.join(form_output), + """
    • Choice:
    • Votes:
    • Choice:
    • -
    • Votes:
    • """) +
    • Votes:
    • """ + ) # Let's simulate what would happen if we submitted this form. formset = self.make_choiceformset([('Calexico', '100'), ('', '')], initial_forms=1) @@ -212,7 +221,10 @@ class FormsFormsetTestCase(SimpleTestCase): # handle that case later. formset = self.make_choiceformset([('', ''), ('', '')], initial_forms=1) self.assertFalse(formset.is_valid()) - self.assertEqual(formset.errors, [{'votes': ['This field is required.'], 'choice': ['This field is required.']}, {}]) + self.assertEqual( + formset.errors, + [{'votes': ['This field is required.'], 'choice': ['This field is required.']}, {}] + ) def test_displaying_more_than_one_blank_form(self): # Displaying more than 1 blank form ########################################### @@ -226,12 +238,15 @@ class FormsFormsetTestCase(SimpleTestCase): for form in formset.forms: form_output.append(form.as_ul()) - self.assertHTMLEqual('\n'.join(form_output), """
    • Choice:
    • + self.assertHTMLEqual( + '\n'.join(form_output), + """
    • Choice:
    • Votes:
    • Choice:
    • Votes:
    • Choice:
    • -
    • Votes:
    • """) +
    • Votes:
    • """ + ) # Since we displayed every form as blank, we will also accept them back as blank. # This may seem a little strange, but later we will show how to require a minimum @@ -269,10 +284,13 @@ class FormsFormsetTestCase(SimpleTestCase): self.assertFalse(formset.forms[0].empty_permitted) self.assertTrue(formset.forms[1].empty_permitted) - self.assertHTMLEqual('\n'.join(form_output), """
    • Choice:
    • + self.assertHTMLEqual( + '\n'.join(form_output), + """
    • Choice:
    • Votes:
    • Choice:
    • -
    • Votes:
    • """) +
    • Votes:
    • """ + ) def test_min_num_displaying_more_than_one_blank_form_with_zero_extra(self): # We can also display more than 1 empty form passing min_num argument @@ -284,12 +302,15 @@ class FormsFormsetTestCase(SimpleTestCase): for form in formset.forms: form_output.append(form.as_ul()) - self.assertHTMLEqual('\n'.join(form_output), """
    • Choice:
    • + self.assertHTMLEqual( + '\n'.join(form_output), + """
    • Choice:
    • Votes:
    • Choice:
    • Votes:
    • Choice:
    • -
    • Votes:
    • """) +
    • Votes:
    • """ + ) def test_single_form_completed(self): # We can just fill out one of the forms. @@ -388,20 +409,26 @@ class FormsFormsetTestCase(SimpleTestCase): for form in formset.forms: form_output.append(form.as_ul()) - self.assertHTMLEqual('\n'.join(form_output), """
    • Choice:
    • + self.assertHTMLEqual( + '\n'.join(form_output), + """
    • Choice:
    • Votes:
    • Choice:
    • Votes:
    • Choice:
    • Votes:
    • Choice:
    • -
    • Votes:
    • """) +
    • Votes:
    • """ + ) # Make sure retrieving an empty form works, and it shows up in the form list self.assertTrue(formset.empty_form.empty_permitted) - self.assertHTMLEqual(formset.empty_form.as_ul(), """
    • Choice:
    • -
    • Votes:
    • """) + self.assertHTMLEqual( + formset.empty_form.as_ul(), + """
    • Choice:
    • +
    • Votes:
    • """ + ) def test_formset_with_deletion(self): # FormSets with deletion ###################################################### @@ -418,7 +445,9 @@ class FormsFormsetTestCase(SimpleTestCase): for form in formset.forms: form_output.append(form.as_ul()) - self.assertHTMLEqual('\n'.join(form_output), """
    • Choice:
    • + self.assertHTMLEqual( + '\n'.join(form_output), + """
    • Choice:
    • Votes:
    • Delete:
    • Choice:
    • @@ -426,7 +455,8 @@ class FormsFormsetTestCase(SimpleTestCase):
    • Delete:
    • Choice:
    • Votes:
    • -
    • Delete:
    • """) +
    • Delete:
    • """ + ) # To delete something, we just need to set that form's special delete field to # 'on'. Let's go ahead and delete Fergie. @@ -449,8 +479,18 @@ class FormsFormsetTestCase(SimpleTestCase): formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) - self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'DELETE': False, 'choice': 'Calexico'}, {'votes': 900, 'DELETE': True, 'choice': 'Fergie'}, {}]) - self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'choice': 'Fergie'}]) + self.assertEqual( + [form.cleaned_data for form in formset.forms], + [ + {'votes': 100, 'DELETE': False, 'choice': 'Calexico'}, + {'votes': 900, 'DELETE': True, 'choice': 'Fergie'}, + {}, + ] + ) + self.assertEqual( + [form.cleaned_data for form in formset.deleted_forms], + [{'votes': 900, 'DELETE': True, 'choice': 'Fergie'}] + ) # If we fill a form with something and then we check the can_delete checkbox for # that form, that form's errors should not make the entire formset invalid since @@ -517,7 +557,9 @@ class FormsFormsetTestCase(SimpleTestCase): for form in formset.forms: form_output.append(form.as_ul()) - self.assertHTMLEqual('\n'.join(form_output), """
    • Choice:
    • + self.assertHTMLEqual( + '\n'.join(form_output), + """
    • Choice:
    • Votes:
    • Order:
    • Choice:
    • @@ -525,7 +567,8 @@ class FormsFormsetTestCase(SimpleTestCase):
    • Order:
    • Choice:
    • Votes:
    • -
    • Order:
    • """) +
    • Order:
    • """ + ) data = { 'choices-TOTAL_FORMS': '3', # the number of forms rendered @@ -631,7 +674,9 @@ class FormsFormsetTestCase(SimpleTestCase): for form in formset.forms: form_output.append(form.as_ul()) - self.assertHTMLEqual('\n'.join(form_output), """
    • Choice:
    • + self.assertHTMLEqual( + '\n'.join(form_output), + """
    • Choice:
    • Votes:
    • Order:
    • Delete:
    • @@ -646,7 +691,8 @@ class FormsFormsetTestCase(SimpleTestCase):
    • Choice:
    • Votes:
    • Order:
    • -
    • Delete:
    • """) +
    • Delete:
    • """ + ) # Let's delete Fergie, and put The Decemberists ahead of Calexico. @@ -684,7 +730,10 @@ class FormsFormsetTestCase(SimpleTestCase): {'votes': 500, 'DELETE': False, 'ORDER': 0, 'choice': 'The Decemberists'}, {'votes': 100, 'DELETE': False, 'ORDER': 1, 'choice': 'Calexico'}, ]) - self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'ORDER': 2, 'choice': 'Fergie'}]) + self.assertEqual( + [form.cleaned_data for form in formset.deleted_forms], + [{'votes': 900, 'DELETE': True, 'ORDER': 2, 'choice': 'Fergie'}] + ) def test_invalid_deleted_form_with_ordering(self): # Should be able to get ordered forms from a valid formset even if a @@ -761,9 +810,15 @@ class FormsFormsetTestCase(SimpleTestCase): for form in formset.forms: form_output.append(str(form)) - self.assertHTMLEqual('\n'.join(form_output), """ - -""") + self.assertHTMLEqual( + '\n'.join(form_output), + """ + + + + +""" + ) # If max_num is 0 then no form is rendered at all. LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=0) @@ -782,8 +837,13 @@ class FormsFormsetTestCase(SimpleTestCase): for form in formset.forms: form_output.append(str(form)) - self.assertHTMLEqual('\n'.join(form_output), """ -""") + self.assertHTMLEqual( + '\n'.join(form_output), + """ + + +""" + ) # Ensure that max_num has no effect when extra is less than max_num. @@ -794,7 +854,11 @@ class FormsFormsetTestCase(SimpleTestCase): for form in formset.forms: form_output.append(str(form)) - self.assertHTMLEqual('\n'.join(form_output), """""") + self.assertHTMLEqual( + '\n'.join(form_output), + """ +""" + ) def test_max_num_with_initial_data(self): # max_num with initial data @@ -813,8 +877,13 @@ class FormsFormsetTestCase(SimpleTestCase): for form in formset.forms: form_output.append(str(form)) - self.assertHTMLEqual('\n'.join(form_output), """ -""") + self.assertHTMLEqual( + '\n'.join(form_output), + """ + + +""" + ) def test_max_num_zero(self): # If max_num is 0 then no form is rendered at all, regardless of extra, @@ -842,8 +911,13 @@ class FormsFormsetTestCase(SimpleTestCase): for form in formset.forms: form_output.append(str(form)) - self.assertEqual('\n'.join(form_output), """ -""") + self.assertHTMLEqual( + '\n'.join(form_output), + """ + + +""" + ) def test_more_initial_than_max_num(self): # More initial forms than max_num now results in all initial forms @@ -861,9 +935,15 @@ class FormsFormsetTestCase(SimpleTestCase): for form in formset.forms: form_output.append(str(form)) - self.assertHTMLEqual('\n'.join(form_output), """ - -""") + self.assertHTMLEqual( + '\n'.join(form_output), + """ + + + + +""" + ) # One form from initial and extra=3 with max_num=2 should result in the one # initial form and one extra. @@ -877,8 +957,13 @@ class FormsFormsetTestCase(SimpleTestCase): for form in formset.forms: form_output.append(str(form)) - self.assertHTMLEqual('\n'.join(form_output), """ -""") + self.assertHTMLEqual( + '\n'.join(form_output), + """ + + +""" + ) def test_regression_6926(self): # Regression test for #6926 ################################################## @@ -1157,21 +1242,39 @@ ChoiceFormSet = formset_factory(Choice) class FormsetAsFooTests(SimpleTestCase): def test_as_table(self): formset = ChoiceFormSet(data, auto_id=False, prefix='choices') - self.assertHTMLEqual(formset.as_table(), """ + self.assertHTMLEqual( + formset.as_table(), + """ + + + Choice: -Votes:""") +Votes:""" + ) def test_as_p(self): formset = ChoiceFormSet(data, auto_id=False, prefix='choices') - self.assertHTMLEqual(formset.as_p(), """ + self.assertHTMLEqual( + formset.as_p(), + """ + + +

      Choice:

      -

      Votes:

      """) +

      Votes:

      """ + ) def test_as_ul(self): formset = ChoiceFormSet(data, auto_id=False, prefix='choices') - self.assertHTMLEqual(formset.as_ul(), """ + self.assertHTMLEqual( + formset.as_ul(), + """ + + +
    • Choice:
    • -
    • Votes:
    • """) +
    • Votes:
    • """ + ) # Regression test for #11418 ################################################# @@ -1241,8 +1344,14 @@ class TestEmptyFormSet(SimpleTestCase): def test_empty_formset_is_valid(self): """Test that an empty formset still calls clean()""" EmptyFsetWontValidateFormset = formset_factory(FavoriteDrinkForm, extra=0, formset=EmptyFsetWontValidate) - formset = EmptyFsetWontValidateFormset(data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '0'}, prefix="form") - formset2 = EmptyFsetWontValidateFormset(data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '1', 'form-0-name': 'bah'}, prefix="form") + formset = EmptyFsetWontValidateFormset( + data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '0'}, + prefix="form", + ) + formset2 = EmptyFsetWontValidateFormset( + data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '1', 'form-0-name': 'bah'}, + prefix="form", + ) self.assertFalse(formset.is_valid()) self.assertFalse(formset2.is_valid()) diff --git a/tests/forms_tests/tests/test_media.py b/tests/forms_tests/tests/test_media.py index 4ec5f6ab7e..f48983779c 100644 --- a/tests/forms_tests/tests/test_media.py +++ b/tests/forms_tests/tests/test_media.py @@ -14,12 +14,18 @@ class FormsMediaTestCase(SimpleTestCase): def test_construction(self): # Check construction of media objects - m = Media(css={'all': ('path/to/css1', '/path/to/css2')}, js=('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')) - self.assertEqual(str(m), """ + m = Media( + css={'all': ('path/to/css1', '/path/to/css2')}, + js=('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'), + ) + self.assertEqual( + str(m), + """ -""") +""" + ) class Foo: css = { @@ -28,11 +34,14 @@ class FormsMediaTestCase(SimpleTestCase): js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') m3 = Media(Foo) - self.assertEqual(str(m3), """ + self.assertEqual( + str(m3), + """ -""") +""" + ) # A widget can exist without a media definition class MyWidget(TextInput): @@ -57,19 +66,27 @@ class FormsMediaTestCase(SimpleTestCase): js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') w1 = MyWidget1() - self.assertEqual(str(w1.media), """ + self.assertEqual( + str(w1.media), + """ -""") +""" + ) # Media objects can be interrogated by media type - self.assertEqual(str(w1.media['css']), """ + self.assertEqual( + str(w1.media['css']), + """ """) - self.assertEqual(str(w1.media['js']), """ + self.assertEqual( + str(w1.media['js']), + """ -""") +""" + ) def test_combine_media(self): # Media objects can be combined. Any given media resource will appear only @@ -98,20 +115,26 @@ class FormsMediaTestCase(SimpleTestCase): w1 = MyWidget1() w2 = MyWidget2() w3 = MyWidget3() - self.assertEqual(str(w1.media + w2.media + w3.media), """ + self.assertEqual( + str(w1.media + w2.media + w3.media), + """ -""") +""" + ) # Check that media addition hasn't affected the original objects - self.assertEqual(str(w1.media), """ + self.assertEqual( + str(w1.media), + """ -""") +""" + ) # Regression check for #12879: specifying the same CSS or JS file # multiple times in a single Media instance should result in that file @@ -122,8 +145,11 @@ class FormsMediaTestCase(SimpleTestCase): js = ('/path/to/js1', '/path/to/js1') w4 = MyWidget4() - self.assertEqual(str(w4.media), """ -""") + self.assertEqual( + str(w4.media), + """ +""" + ) def test_media_property(self): ############################################################### @@ -147,10 +173,13 @@ class FormsMediaTestCase(SimpleTestCase): media = property(_media) w5 = MyWidget5() - self.assertEqual(str(w5.media), """ + self.assertEqual( + str(w5.media), + """ -""") +""" + ) def test_media_property_parent_references(self): # Media properties can reference the media of their parents, @@ -168,13 +197,16 @@ class FormsMediaTestCase(SimpleTestCase): media = property(_media) w6 = MyWidget6() - self.assertEqual(str(w6.media), """ + self.assertEqual( + str(w6.media), + """ -""") +""" + ) def test_media_inheritance(self): ############################################################### @@ -193,11 +225,14 @@ class FormsMediaTestCase(SimpleTestCase): pass w7 = MyWidget7() - self.assertEqual(str(w7.media), """ + self.assertEqual( + str(w7.media), + """ -""") +""" + ) # If a widget extends another but defines media, it extends the parent widget's media by default class MyWidget8(MyWidget1): @@ -208,13 +243,16 @@ class FormsMediaTestCase(SimpleTestCase): js = ('/path/to/js1', '/path/to/js4') w8 = MyWidget8() - self.assertEqual(str(w8.media), """ + self.assertEqual( + str(w8.media), + """ -""") +""" + ) def test_media_inheritance_from_property(self): # If a widget extends another but defines media, it extends the parents widget's media, @@ -239,10 +277,13 @@ class FormsMediaTestCase(SimpleTestCase): js = ('/other/js',) w9 = MyWidget9() - self.assertEqual(str(w9.media), """ + self.assertEqual( + str(w9.media), + """ -""") +""" + ) # A widget can disable media inheritance by specifying 'extend=False' class MyWidget10(MyWidget1): @@ -277,13 +318,16 @@ class FormsMediaTestCase(SimpleTestCase): js = ('/path/to/js1', '/path/to/js4') w11 = MyWidget11() - self.assertEqual(str(w11.media), """ + self.assertEqual( + str(w11.media), + """ -""") +""" + ) def test_media_inheritance_single_type(self): # A widget can enable inheritance of one media type by specifying extend as a tuple @@ -303,11 +347,14 @@ class FormsMediaTestCase(SimpleTestCase): js = ('/path/to/js1', '/path/to/js4') w12 = MyWidget12() - self.assertEqual(str(w12.media), """ + self.assertEqual( + str(w12.media), + """ -""") +""" + ) def test_multi_media(self): ############################################################### @@ -325,12 +372,15 @@ class FormsMediaTestCase(SimpleTestCase): js = ('/path/to/js1', '/path/to/js4') multimedia = MultimediaWidget() - self.assertEqual(str(multimedia.media), """ + self.assertEqual( + str(multimedia.media), + """ -""") +""" + ) def test_multi_widget(self): ############################################################### @@ -366,13 +416,16 @@ class FormsMediaTestCase(SimpleTestCase): super(MyMultiWidget, self).__init__(widgets, attrs) mymulti = MyMultiWidget() - self.assertEqual(str(mymulti.media), """ + self.assertEqual( + str(mymulti.media), + """ -""") +""" + ) def test_form_media(self): ############################################################### @@ -405,25 +458,31 @@ class FormsMediaTestCase(SimpleTestCase): field1 = CharField(max_length=20, widget=MyWidget1()) field2 = CharField(max_length=20, widget=MyWidget2()) f1 = MyForm() - self.assertEqual(str(f1.media), """ + self.assertEqual( + str(f1.media), + """ -""") +""" + ) # Form media can be combined to produce a single media definition. class AnotherForm(Form): field3 = CharField(max_length=20, widget=MyWidget3()) f2 = AnotherForm() - self.assertEqual(str(f1.media + f2.media), """ + self.assertEqual( + str(f1.media + f2.media), + """ -""") +""" + ) # Forms can also define media, following the same rules as widgets. class FormWithMedia(Form): @@ -436,7 +495,9 @@ class FormsMediaTestCase(SimpleTestCase): 'all': ('/some/form/css',) } f3 = FormWithMedia() - self.assertEqual(str(f3.media), """ + self.assertEqual( + str(f3.media), + """ @@ -444,17 +505,23 @@ class FormsMediaTestCase(SimpleTestCase): -""") +""" + ) # Media works in templates - self.assertEqual(Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})), """ + self.assertEqual( + Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})), + """ - +""" + """ -""") +""" + ) def test_html_safe(self): media = Media(css={'all': ['/path/to/css']}, js=['/path/to/js']) @@ -471,12 +538,18 @@ class StaticFormsMediaTestCase(SimpleTestCase): def test_construction(self): # Check construction of media objects - m = Media(css={'all': ('path/to/css1', '/path/to/css2')}, js=('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')) - self.assertEqual(str(m), """ + m = Media( + css={'all': ('path/to/css1', '/path/to/css2')}, + js=('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'), + ) + self.assertEqual( + str(m), + """ -""") +""" + ) class Foo: css = { @@ -485,11 +558,14 @@ class StaticFormsMediaTestCase(SimpleTestCase): js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') m3 = Media(Foo) - self.assertEqual(str(m3), """ + self.assertEqual( + str(m3), + """ -""") +""" + ) # A widget can exist without a media definition class MyWidget(TextInput): @@ -514,19 +590,28 @@ class StaticFormsMediaTestCase(SimpleTestCase): js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') w1 = MyWidget1() - self.assertEqual(str(w1.media), """ + self.assertEqual( + str(w1.media), + """ -""") +""" + ) # Media objects can be interrogated by media type - self.assertEqual(str(w1.media['css']), """ -""") + self.assertEqual( + str(w1.media['css']), + """ +""" + ) - self.assertEqual(str(w1.media['js']), """ + self.assertEqual( + str(w1.media['js']), + """ -""") +""" + ) def test_combine_media(self): # Media objects can be combined. Any given media resource will appear only @@ -555,20 +640,26 @@ class StaticFormsMediaTestCase(SimpleTestCase): w1 = MyWidget1() w2 = MyWidget2() w3 = MyWidget3() - self.assertEqual(str(w1.media + w2.media + w3.media), """ + self.assertEqual( + str(w1.media + w2.media + w3.media), + """ -""") +""" + ) # Check that media addition hasn't affected the original objects - self.assertEqual(str(w1.media), """ + self.assertEqual( + str(w1.media), + """ -""") +""" + ) # Regression check for #12879: specifying the same CSS or JS file # multiple times in a single Media instance should result in that file @@ -625,13 +716,16 @@ class StaticFormsMediaTestCase(SimpleTestCase): media = property(_media) w6 = MyWidget6() - self.assertEqual(str(w6.media), """ + self.assertEqual( + str(w6.media), + """ -""") +""" + ) def test_media_inheritance(self): ############################################################### @@ -650,11 +744,14 @@ class StaticFormsMediaTestCase(SimpleTestCase): pass w7 = MyWidget7() - self.assertEqual(str(w7.media), """ + self.assertEqual( + str(w7.media), + """ -""") +""" + ) # If a widget extends another but defines media, it extends the parent widget's media by default class MyWidget8(MyWidget1): @@ -665,13 +762,16 @@ class StaticFormsMediaTestCase(SimpleTestCase): js = ('/path/to/js1', '/path/to/js4') w8 = MyWidget8() - self.assertEqual(str(w8.media), """ + self.assertEqual( + str(w8.media), + """ -""") +""" + ) def test_media_inheritance_from_property(self): # If a widget extends another but defines media, it extends the parents widget's media, @@ -696,10 +796,13 @@ class StaticFormsMediaTestCase(SimpleTestCase): js = ('/other/js',) w9 = MyWidget9() - self.assertEqual(str(w9.media), """ + self.assertEqual( + str(w9.media), + """ -""") +""" + ) # A widget can disable media inheritance by specifying 'extend=False' class MyWidget10(MyWidget1): @@ -734,13 +837,16 @@ class StaticFormsMediaTestCase(SimpleTestCase): js = ('/path/to/js1', '/path/to/js4') w11 = MyWidget11() - self.assertEqual(str(w11.media), """ + self.assertEqual( + str(w11.media), + """ -""") +""" + ) def test_media_inheritance_single_type(self): # A widget can enable inheritance of one media type by specifying extend as a tuple @@ -760,11 +866,14 @@ class StaticFormsMediaTestCase(SimpleTestCase): js = ('/path/to/js1', '/path/to/js4') w12 = MyWidget12() - self.assertEqual(str(w12.media), """ + self.assertEqual( + str(w12.media), + """ -""") +""" + ) def test_multi_media(self): ############################################################### @@ -782,12 +891,15 @@ class StaticFormsMediaTestCase(SimpleTestCase): js = ('/path/to/js1', '/path/to/js4') multimedia = MultimediaWidget() - self.assertEqual(str(multimedia.media), """ + self.assertEqual( + str(multimedia.media), + """ -""") +""" + ) def test_multi_widget(self): ############################################################### @@ -823,13 +935,16 @@ class StaticFormsMediaTestCase(SimpleTestCase): super(MyMultiWidget, self).__init__(widgets, attrs) mymulti = MyMultiWidget() - self.assertEqual(str(mymulti.media), """ + self.assertEqual( + str(mymulti.media), + """ -""") +""" + ) def test_form_media(self): ############################################################### @@ -862,25 +977,31 @@ class StaticFormsMediaTestCase(SimpleTestCase): field1 = CharField(max_length=20, widget=MyWidget1()) field2 = CharField(max_length=20, widget=MyWidget2()) f1 = MyForm() - self.assertEqual(str(f1.media), """ + self.assertEqual( + str(f1.media), + """ -""") +""" + ) # Form media can be combined to produce a single media definition. class AnotherForm(Form): field3 = CharField(max_length=20, widget=MyWidget3()) f2 = AnotherForm() - self.assertEqual(str(f1.media + f2.media), """ + self.assertEqual( + str(f1.media + f2.media), + """ -""") +""" + ) # Forms can also define media, following the same rules as widgets. class FormWithMedia(Form): @@ -893,7 +1014,9 @@ class StaticFormsMediaTestCase(SimpleTestCase): 'all': ('/some/form/css',) } f3 = FormWithMedia() - self.assertEqual(str(f3.media), """ + self.assertEqual( + str(f3.media), + """ @@ -901,14 +1024,19 @@ class StaticFormsMediaTestCase(SimpleTestCase): -""") +""" + ) # Media works in templates - self.assertEqual(Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})), """ + self.assertEqual( + Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})), + """ - +""" + """ -""") +""" + ) diff --git a/tests/forms_tests/tests/test_regressions.py b/tests/forms_tests/tests/test_regressions.py index d2f86e1db9..10e5b3f983 100644 --- a/tests/forms_tests/tests/test_regressions.py +++ b/tests/forms_tests/tests/test_regressions.py @@ -22,7 +22,11 @@ class FormsRegressionsTestCase(TestCase): f1 = CharField(max_length=10, widget=TextInput(attrs=extra_attrs)) f2 = CharField(widget=TextInput(attrs=extra_attrs)) - self.assertHTMLEqual(TestForm(auto_id=False).as_p(), '

      F1:

      \n

      F2:

      ') + self.assertHTMLEqual( + TestForm(auto_id=False).as_p(), + '

      F1:

      \n' + '

      F2:

      ' + ) def test_regression_3600(self): # Tests for form i18n # @@ -32,19 +36,35 @@ class FormsRegressionsTestCase(TestCase): username = CharField(max_length=10, label=ugettext_lazy('username')) f = SomeForm() - self.assertHTMLEqual(f.as_p(), '

      ') + self.assertHTMLEqual( + f.as_p(), + '

      ' + '

      ' + ) # Translations are done at rendering time, so multi-lingual apps can define forms) with translation.override('de'): - self.assertHTMLEqual(f.as_p(), '

      ') + self.assertHTMLEqual( + f.as_p(), + '

      ' + '

      ' + ) with translation.override('pl'): - self.assertHTMLEqual(f.as_p(), '

      ') + self.assertHTMLEqual( + f.as_p(), + '

      ' + '

      ' + ) def test_regression_5216(self): # There was some problems with form translations in #5216 class SomeForm(Form): field_1 = CharField(max_length=10, label=ugettext_lazy('field_1')) - field_2 = CharField(max_length=10, label=ugettext_lazy('field_2'), widget=TextInput(attrs={'id': 'field_2_id'})) + field_2 = CharField( + max_length=10, + label=ugettext_lazy('field_2'), + widget=TextInput(attrs={'id': 'field_2_id'}), + ) f = SomeForm() self.assertHTMLEqual(f['field_1'].label_tag(), '') @@ -57,12 +77,38 @@ class FormsRegressionsTestCase(TestCase): somechoice = ChoiceField(choices=GENDERS, widget=RadioSelect(), label='\xc5\xf8\xdf') f = SomeForm() - self.assertHTMLEqual(f.as_p(), '

        \n
      • \n
      • \n
      • \n

      ') + self.assertHTMLEqual( + f.as_p(), + '

      ' + '

        \n' + '
      • \n' + '
      • \n
      • \n

      ' + ) # Translated error messages used to be buggy. with translation.override('ru'): f = SomeForm({}) - self.assertHTMLEqual(f.as_p(), '
      • \u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.
      \n

        \n
      • \n
      • \n
      • \n

      ') + self.assertHTMLEqual( + f.as_p(), + '
      • ' + '\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c' + '\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.
      \n' + '

      ' + '

        \n
      • \n' + '
      • \n
      • \n

      ' + ) # Deep copying translated text shouldn't raise an error) class CopyForm(Form): @@ -95,8 +141,18 @@ class FormsRegressionsTestCase(TestCase): data = IntegerField(widget=HiddenInput) f = HiddenForm({}) - self.assertHTMLEqual(f.as_p(), '
      • (Hidden field data) This field is required.
      \n

      ') - self.assertHTMLEqual(f.as_table(), '
      • (Hidden field data) This field is required.
      ') + self.assertHTMLEqual( + f.as_p(), + '
        ' + '
      • (Hidden field data) This field is required.
      \n

      ' + '

      ' + ) + self.assertHTMLEqual( + f.as_table(), + '
        ' + '
      • (Hidden field data) This field is required.
      ' + '' + ) def test_xss_error_messages(self): ################################################### @@ -114,13 +170,23 @@ class FormsRegressionsTestCase(TestCase): field = ChoiceField(choices=[('one', 'One')]) f = SomeForm({'field': '''') + self.assertHTMLEqual( + six.text_type(f.media), + ''' +''' + ) def test_choices_type(self): # Choices on CharField and IntegerField @@ -2251,8 +2307,13 @@ class OtherModelFormTests(TestCase): self.assertEqual(list(CategoryForm.base_fields), ['description', 'url']) - self.assertHTMLEqual(six.text_type(CategoryForm()), ''' -''') + self.assertHTMLEqual( + six.text_type(CategoryForm()), + ''' + + +''' + ) # to_field_name should also work on ModelMultipleChoiceField ################## field = forms.ModelMultipleChoiceField(Inventory.objects.all(), to_field_name='barcode') @@ -2267,8 +2328,11 @@ class OtherModelFormTests(TestCase): def test_model_field_that_returns_none_to_exclude_itself_with_explicit_fields(self): self.assertEqual(list(CustomFieldForExclusionForm.base_fields), ['name']) - self.assertHTMLEqual(six.text_type(CustomFieldForExclusionForm()), - '''''') + self.assertHTMLEqual( + six.text_type(CustomFieldForExclusionForm()), + ''' +''' + ) def test_iterable_model_m2m(self): class ColourfulItemForm(forms.ModelForm): @@ -2298,19 +2362,20 @@ class OtherModelFormTests(TestCase): today_str = str(datetime.date.today()) self.assertHTMLEqual( form.as_p(), - """

      -

      - -

      -

      -

      -

      - + """ +

      +

      + +

      +

      +

      +

      + """.format(today_str) ) empty_data = { diff --git a/tests/model_formsets/tests.py b/tests/model_formsets/tests.py index 07476ebbc3..b39054c7e4 100644 --- a/tests/model_formsets/tests.py +++ b/tests/model_formsets/tests.py @@ -151,12 +151,24 @@ class ModelFormsetTest(TestCase): formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 3) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      ') - self.assertHTMLEqual(formset.forms[1].as_p(), - '

      ') - self.assertHTMLEqual(formset.forms[2].as_p(), - '

      ') + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '' + '

      ' + ) + self.assertHTMLEqual( + formset.forms[1].as_p(), + '

      ' + '' + '

      ' + ) + self.assertHTMLEqual( + formset.forms[2].as_p(), + '

      ' + ' ' + '

      ' + ) data = { 'form-TOTAL_FORMS': '3', # the number of forms rendered @@ -189,12 +201,24 @@ class ModelFormsetTest(TestCase): formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 3) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      ' % author2.id) - self.assertHTMLEqual(formset.forms[1].as_p(), - '

      ' % author1.id) - self.assertHTMLEqual(formset.forms[2].as_p(), - '

      ') + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '' + '

      ' % author2.id + ) + self.assertHTMLEqual( + formset.forms[1].as_p(), + '

      ' + '' + '

      ' % author1.id + ) + self.assertHTMLEqual( + formset.forms[2].as_p(), + '

      ' + '' + '

      ' + ) data = { 'form-TOTAL_FORMS': '3', # the number of forms rendered @@ -227,18 +251,41 @@ class ModelFormsetTest(TestCase): formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 4) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      \n' - '

      ' % author2.id) - self.assertHTMLEqual(formset.forms[1].as_p(), - '

      \n' - '

      ' % author1.id) - self.assertHTMLEqual(formset.forms[2].as_p(), - '

      \n' - '

      ' % author3.id) - self.assertHTMLEqual(formset.forms[3].as_p(), - '

      \n' - '

      ') + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '

      ' + '

      ' + '' + '

      ' % author2.id + ) + self.assertHTMLEqual( + formset.forms[1].as_p(), + '

      ' + '

      ' + '

      ' + '' + '

      ' % author1.id + ) + self.assertHTMLEqual( + formset.forms[2].as_p(), + '

      ' + '

      ' + '

      ' + '' + '

      ' % author3.id + ) + self.assertHTMLEqual( + formset.forms[3].as_p(), + '

      ' + '

      ' + '

      ' + '' + '

      ' + ) data = { 'form-TOTAL_FORMS': '4', # the number of forms rendered @@ -480,9 +527,14 @@ class ModelFormsetTest(TestCase): BetterAuthorFormSet = modelformset_factory(BetterAuthor, fields="__all__") formset = BetterAuthorFormSet() self.assertEqual(len(formset.forms), 1) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      \n' - '

      ') + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '

      ' + '

      ' + '' + '

      ' + ) data = { 'form-TOTAL_FORMS': '1', # the number of forms rendered @@ -503,12 +555,22 @@ class ModelFormsetTest(TestCase): formset = BetterAuthorFormSet() self.assertEqual(len(formset.forms), 2) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      \n' - '

      ' % hemingway_id) - self.assertHTMLEqual(formset.forms[1].as_p(), - '

      \n' - '

      ') + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '

      ' + '

      ' + '' + '

      ' % hemingway_id + ) + self.assertHTMLEqual( + formset.forms[1].as_p(), + '

      ' + '

      ' + '

      ' + '' + '

      ' + ) data = { 'form-TOTAL_FORMS': '2', # the number of forms rendered @@ -535,12 +597,27 @@ class ModelFormsetTest(TestCase): formset = AuthorBooksFormSet(instance=author) self.assertEqual(len(formset.forms), 3) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      ' % author.id) - self.assertHTMLEqual(formset.forms[1].as_p(), - '

      ' % author.id) - self.assertHTMLEqual(formset.forms[2].as_p(), - '

      ' % author.id) + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '

      ' % author.id + ) + self.assertHTMLEqual( + formset.forms[1].as_p(), + '

      ' + '' + '' + '

      ' % author.id + ) + self.assertHTMLEqual( + formset.forms[2].as_p(), + '

      ' + '' + '' + '

      ' % author.id + ) data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered @@ -569,12 +646,30 @@ class ModelFormsetTest(TestCase): formset = AuthorBooksFormSet(instance=author) self.assertEqual(len(formset.forms), 3) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      ' % (author.id, book1.id)) - self.assertHTMLEqual(formset.forms[1].as_p(), - '

      ' % author.id) - self.assertHTMLEqual(formset.forms[2].as_p(), - '

      ' % author.id) + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '' + '' + '

      ' % ( + author.id, book1.id, + ) + ) + self.assertHTMLEqual( + formset.forms[1].as_p(), + '

      ' + '' + '' + '

      ' % author.id + ) + self.assertHTMLEqual( + formset.forms[2].as_p(), + '

      ' + '' + '' + '

      ' % author.id + ) data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered @@ -633,24 +728,45 @@ class ModelFormsetTest(TestCase): formset = AuthorBooksFormSet(prefix="test") self.assertEqual(len(formset.forms), 2) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      ') - self.assertHTMLEqual(formset.forms[1].as_p(), - '

      ') + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '' + '' + '

      ' + ) + + self.assertHTMLEqual( + formset.forms[1].as_p(), + '

      ' + '' + '' + '

      ' + ) def test_inline_formsets_with_custom_pk(self): # Test inline formsets where the inline-edited object has a custom # primary key that is not the fk to the parent object. self.maxDiff = 1024 - AuthorBooksFormSet2 = inlineformset_factory(Author, BookWithCustomPK, can_delete=False, extra=1, fields="__all__") + AuthorBooksFormSet2 = inlineformset_factory( + Author, BookWithCustomPK, can_delete=False, extra=1, fields="__all__" + ) author = Author.objects.create(pk=1, name='Charles Baudelaire') formset = AuthorBooksFormSet2(instance=author) self.assertEqual(len(formset.forms), 1) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      \n' - '

      ') + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '

      ' + '

      ' + '' + '

      ' + ) data = { 'bookwithcustompk_set-TOTAL_FORMS': '1', # the number of forms rendered @@ -680,9 +796,19 @@ class ModelFormsetTest(TestCase): formset = AuthorBooksFormSet3(instance=author) self.assertEqual(len(formset.forms), 1) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      \n' - '

      ') + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '

      ' + '

      ' + '' + '' + '

      ' + ) data = { 'alternatebook_set-TOTAL_FORMS': '1', # the number of forms rendered @@ -706,7 +832,9 @@ class ModelFormsetTest(TestCase): # Test inline formsets where the inline-edited object has a # unique_together constraint with a nullable member - AuthorBooksFormSet4 = inlineformset_factory(Author, BookWithOptionalAltEditor, can_delete=False, extra=2, fields="__all__") + AuthorBooksFormSet4 = inlineformset_factory( + Author, BookWithOptionalAltEditor, can_delete=False, extra=2, fields="__all__" + ) author = Author.objects.create(pk=1, name='Charles Baudelaire') data = { @@ -771,16 +899,44 @@ class ModelFormsetTest(TestCase): custom_qs = Book.objects.order_by('-title') formset = AuthorBooksFormSet(instance=author, queryset=custom_qs) self.assertEqual(len(formset.forms), 5) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      ') - self.assertHTMLEqual(formset.forms[1].as_p(), - '

      ') - self.assertHTMLEqual(formset.forms[2].as_p(), - '

      ') - self.assertHTMLEqual(formset.forms[3].as_p(), - '

      ') - self.assertHTMLEqual(formset.forms[4].as_p(), - '

      ') + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '' + '' + '

      ' + ) + self.assertHTMLEqual( + formset.forms[1].as_p(), + '

      ' + '' + '' + '

      ' + ) + self.assertHTMLEqual( + formset.forms[2].as_p(), + '

      ' + '' + '' + '

      ' + ) + self.assertHTMLEqual( + formset.forms[3].as_p(), + '

      ' + '' + '' + '

      ' + ) + self.assertHTMLEqual( + formset.forms[4].as_p(), + '

      ' + '' + '' + '

      ' + ) data = { 'book_set-TOTAL_FORMS': '5', # the number of forms rendered @@ -800,12 +956,28 @@ class ModelFormsetTest(TestCase): custom_qs = Book.objects.filter(title__startswith='F') formset = AuthorBooksFormSet(instance=author, queryset=custom_qs) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      ') - self.assertHTMLEqual(formset.forms[1].as_p(), - '

      ') - self.assertHTMLEqual(formset.forms[2].as_p(), - '

      ') + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '' + '' + '

      ' + ) + self.assertHTMLEqual( + formset.forms[1].as_p(), + '

      ' + '' + '' + '

      ' + ) + self.assertHTMLEqual( + formset.forms[2].as_p(), + '

      ' + '' + '' + '

      ' + ) data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered @@ -863,9 +1035,13 @@ class ModelFormsetTest(TestCase): CustomPrimaryKeyFormSet = modelformset_factory(CustomPrimaryKey, fields="__all__") formset = CustomPrimaryKeyFormSet() self.assertEqual(len(formset.forms), 1) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      \n' - '

      ') + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '

      ' + '

      ' + ) # Custom primary keys with ForeignKey, OneToOneField and AutoField ############ @@ -874,10 +1050,20 @@ class ModelFormsetTest(TestCase): FormSet = inlineformset_factory(Place, Owner, extra=2, can_delete=False, fields="__all__") formset = FormSet(instance=place) self.assertEqual(len(formset.forms), 2) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      ') - self.assertHTMLEqual(formset.forms[1].as_p(), - '

      ') + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '' + '' + '

      ' + ) + self.assertHTMLEqual( + formset.forms[1].as_p(), + '

      ' + '' + '' + '

      ' + ) data = { 'owner_set-TOTAL_FORMS': '2', @@ -898,13 +1084,28 @@ class ModelFormsetTest(TestCase): formset = FormSet(instance=place) self.assertEqual(len(formset.forms), 3) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      ' - % owner1.auto_id) - self.assertHTMLEqual(formset.forms[1].as_p(), - '

      ') - self.assertHTMLEqual(formset.forms[2].as_p(), - '

      ') + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '' + '' + '

      ' + % owner1.auto_id + ) + self.assertHTMLEqual( + formset.forms[1].as_p(), + '

      ' + '' + '' + '

      ' + ) + self.assertHTMLEqual( + formset.forms[2].as_p(), + '

      ' + '' + '' + '

      ' + ) data = { 'owner_set-TOTAL_FORMS': '3', @@ -929,14 +1130,18 @@ class ModelFormsetTest(TestCase): FormSet = modelformset_factory(OwnerProfile, fields="__all__") formset = FormSet() - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      \n' - '

      ' - % (owner1.auto_id, owner2.auto_id)) + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '

      ' + '

      ' + '

      ' + % (owner1.auto_id, owner2.auto_id) + ) owner1 = Owner.objects.get(name='Joe Perry') FormSet = inlineformset_factory(Owner, OwnerProfile, max_num=1, can_delete=False, fields="__all__") @@ -944,9 +1149,13 @@ class ModelFormsetTest(TestCase): formset = FormSet(instance=owner1) self.assertEqual(len(formset.forms), 1) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      ' - % owner1.auto_id) + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '' + '

      ' + % owner1.auto_id + ) data = { 'ownerprofile-TOTAL_FORMS': '1', @@ -965,9 +1174,13 @@ class ModelFormsetTest(TestCase): formset = FormSet(instance=owner1) self.assertEqual(len(formset.forms), 1) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      ' - % owner1.auto_id) + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '' + '

      ' + % owner1.auto_id + ) data = { 'ownerprofile-TOTAL_FORMS': '1', @@ -994,9 +1207,15 @@ class ModelFormsetTest(TestCase): formset = FormSet(instance=place) self.assertEqual(len(formset.forms), 1) - self.assertHTMLEqual(formset.forms[0].as_p(), - '

      \n' - '

      ') + self.assertHTMLEqual( + formset.forms[0].as_p(), + '

      ' + '

      ' + '

      ' + '' + '' + '

      ' + ) def test_foreign_keys_in_parents(self): self.assertEqual(type(_get_foreign_key(Restaurant, Owner)), models.ForeignKey) @@ -1147,9 +1366,17 @@ class ModelFormsetTest(TestCase): now = form.fields['date_joined'].initial() result = form.as_p() result = re.sub(r'[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]+)?', '__DATETIME__', result) - self.assertHTMLEqual(result, - '

      \n' - '

      ' + self.assertHTMLEqual( + result, + '

      ' + '' + '

      ' + '

      ' + '' + '' + '

      ' % person.id) # test for validation with callable defaults. Validations rely on hidden fields @@ -1192,7 +1419,14 @@ class ModelFormsetTest(TestCase): super(MembershipForm, self).__init__(**kwargs) self.fields['date_joined'].widget = forms.SplitDateTimeWidget() - FormSet = inlineformset_factory(Person, Membership, form=MembershipForm, can_delete=False, extra=1, fields="__all__") + FormSet = inlineformset_factory( + Person, + Membership, + form=MembershipForm, + can_delete=False, + extra=1, + fields="__all__", + ) data = { 'membership_set-TOTAL_FORMS': '1', 'membership_set-INITIAL_FORMS': '0', diff --git a/tests/model_formsets_regress/tests.py b/tests/model_formsets_regress/tests.py index bc42fd489c..1885ca7852 100644 --- a/tests/model_formsets_regress/tests.py +++ b/tests/model_formsets_regress/tests.py @@ -202,7 +202,10 @@ class InlineFormsetTests(TestCase): FormSet(instance=None) def test_empty_fields_on_modelformset(self): - "No fields passed to modelformset_factory should result in no fields on returned forms except for the id. See #14119." + """ + No fields passed to modelformset_factory() should result in no fields + on returned forms except for the id (#14119). + """ UserFormSet = modelformset_factory(User, fields=()) formset = UserFormSet() for form in formset.forms: diff --git a/tests/model_meta/tests.py b/tests/model_meta/tests.py index b1ac639c40..6a881624c8 100644 --- a/tests/model_meta/tests.py +++ b/tests/model_meta/tests.py @@ -248,13 +248,12 @@ class RelationTreeTests(SimpleTestCase): self.assertEqual( 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+', 'BasePerson_friends_abstract+', - 'BasePerson_friends_abstract+', 'BasePerson_friends_base+', 'BasePerson_friends_base+', - 'BasePerson_m2m_abstract+', 'BasePerson_m2m_base+', 'Relating_basepeople+', - 'Relating_basepeople_hidden+', 'followers_abstract', - 'followers_base', 'friends_abstract_rel_+', 'friends_base_rel_+', - 'person', 'relating_basepeople', 'relating_baseperson', + '+', '_relating_basepeople_hidden_+', 'BasePerson_following_abstract+', + 'BasePerson_following_abstract+', 'BasePerson_following_base+', 'BasePerson_following_base+', + 'BasePerson_friends_abstract+', 'BasePerson_friends_abstract+', 'BasePerson_friends_base+', + 'BasePerson_friends_base+', 'BasePerson_m2m_abstract+', 'BasePerson_m2m_base+', 'Relating_basepeople+', + 'Relating_basepeople_hidden+', 'followers_abstract', 'followers_base', 'friends_abstract_rel_+', + 'friends_base_rel_+', 'person', 'relating_basepeople', 'relating_baseperson', ]) ) self.assertEqual([field.related_query_name() for field in AbstractPerson._meta._relation_tree], []) diff --git a/tests/modeladmin/models.py b/tests/modeladmin/models.py index 8f69b42874..54291354bc 100644 --- a/tests/modeladmin/models.py +++ b/tests/modeladmin/models.py @@ -37,7 +37,8 @@ class ValidationTestModel(models.Model): is_active = models.BooleanField(default=False) pub_date = models.DateTimeField() band = models.ForeignKey(Band, models.CASCADE) - no = models.IntegerField(verbose_name="Number", blank=True, null=True) # This field is intentionally 2 characters long. See #16080. + # This field is intentionally 2 characters long (#16080). + no = models.IntegerField(verbose_name="Number", blank=True, null=True) def decade_published_in(self): return self.pub_date.strftime('%Y')[:3] + "0's" diff --git a/tests/modeladmin/tests.py b/tests/modeladmin/tests.py index beeb493560..eb99764398 100644 --- a/tests/modeladmin/tests.py +++ b/tests/modeladmin/tests.py @@ -1029,9 +1029,11 @@ class ListDisplayLinksCheckTests(CheckTestCase): list_display_links = ('non_existent_field',) self.assertIsInvalid( - ValidationTestModelAdmin, ValidationTestModel, - "The value of 'list_display_links[0]' refers to 'non_existent_field', which is not defined in 'list_display'.", - 'admin.E111') + ValidationTestModelAdmin, ValidationTestModel, ( + "The value of 'list_display_links[0]' refers to " + "'non_existent_field', which is not defined in 'list_display'." + ), 'admin.E111' + ) def test_missing_in_list_display(self): class ValidationTestModelAdmin(ModelAdmin): @@ -1244,9 +1246,10 @@ class OrderingCheckTests(CheckTestCase): self.assertIsInvalid( ValidationTestModelAdmin, - ValidationTestModel, - "The value of 'ordering[0]' refers to 'non_existent_field', which is not an attribute of 'modeladmin.ValidationTestModel'.", - 'admin.E033', + ValidationTestModel, ( + "The value of 'ordering[0]' refers to 'non_existent_field', " + "which is not an attribute of 'modeladmin.ValidationTestModel'." + ), 'admin.E033' ) def test_random_marker_not_alone(self): diff --git a/tests/multiple_database/tests.py b/tests/multiple_database/tests.py index 4354217d57..fd7748e9f9 100644 --- a/tests/multiple_database/tests.py +++ b/tests/multiple_database/tests.py @@ -188,15 +188,23 @@ class QueryTestCase(TestCase): self.assertEqual(Book.authors.through.objects.using('other').count(), 1) # Check that queries work across m2m joins - self.assertEqual(list(Book.objects.using('default').filter(authors__name='Marty Alchin').values_list('title', flat=True)), - ['Pro Django']) - self.assertEqual(list(Book.objects.using('other').filter(authors__name='Marty Alchin').values_list('title', flat=True)), - []) + self.assertEqual( + list(Book.objects.using('default').filter(authors__name='Marty Alchin').values_list('title', flat=True)), + ['Pro Django'] + ) + self.assertEqual( + list(Book.objects.using('other').filter(authors__name='Marty Alchin').values_list('title', flat=True)), + [] + ) - self.assertEqual(list(Book.objects.using('default').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), - []) - self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), - ['Dive into Python']) + self.assertEqual( + list(Book.objects.using('default').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), + [] + ) + self.assertEqual( + list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), + ['Dive into Python'] + ) # Reget the objects to clear caches dive = Book.objects.using('other').get(title="Dive into Python") @@ -222,35 +230,53 @@ class QueryTestCase(TestCase): # Add a second author john = Person.objects.using('other').create(name="John Smith") - self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)), - []) + self.assertEqual( + list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)), + [] + ) dive.authors.add(john) - self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), - ['Dive into Python']) - self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)), - ['Dive into Python']) + self.assertEqual( + list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), + ['Dive into Python'] + ) + self.assertEqual( + list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)), + ['Dive into Python'] + ) # Remove the second author dive.authors.remove(john) - self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), - ['Dive into Python']) - self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)), - []) + self.assertEqual( + list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), + ['Dive into Python'] + ) + self.assertEqual( + list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)), + [] + ) # Clear all authors dive.authors.clear() - self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), - []) - self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)), - []) + self.assertEqual( + list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), + [] + ) + self.assertEqual( + list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)), + [] + ) # Create an author through the m2m interface dive.authors.create(name='Jane Brown') - self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), - []) - self.assertEqual(list(Book.objects.using('other').filter(authors__name='Jane Brown').values_list('title', flat=True)), - ['Dive into Python']) + self.assertEqual( + list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), + [] + ) + self.assertEqual( + list(Book.objects.using('other').filter(authors__name='Jane Brown').values_list('title', flat=True)), + ['Dive into Python'] + ) def test_m2m_reverse_operations(self): "M2M reverse manipulations are all constrained to a single DB" @@ -269,31 +295,53 @@ class QueryTestCase(TestCase): # Add a books to the m2m mark.book_set.add(grease) - self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)), - ['Mark Pilgrim']) - self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)), - ['Mark Pilgrim']) + self.assertEqual( + list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)), + ['Mark Pilgrim'] + ) + self.assertEqual( + list( + Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True) + ), + ['Mark Pilgrim'] + ) # Remove a book from the m2m mark.book_set.remove(grease) - self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)), - ['Mark Pilgrim']) - self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)), - []) + self.assertEqual( + list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)), + ['Mark Pilgrim'] + ) + self.assertEqual( + list( + Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True) + ), + [] + ) # Clear the books associated with mark mark.book_set.clear() - self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)), - []) - self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)), - []) + self.assertEqual( + list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)), + [] + ) + self.assertEqual( + list( + Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True) + ), + [] + ) # Create a book through the m2m interface mark.book_set.create(title="Dive into HTML5", published=datetime.date(2020, 1, 1)) - self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)), - []) - self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into HTML5').values_list('name', flat=True)), - ['Mark Pilgrim']) + self.assertEqual( + list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)), + [] + ) + self.assertEqual( + list(Person.objects.using('other').filter(book__title='Dive into HTML5').values_list('name', flat=True)), + ['Mark Pilgrim'] + ) def test_m2m_cross_database_protection(self): "Operations that involve sharing M2M objects across databases raise an error" @@ -421,15 +469,27 @@ class QueryTestCase(TestCase): self.assertEqual(dive.editor.name, "Chris Mills") # Check that queries work across foreign key joins - self.assertEqual(list(Person.objects.using('default').filter(edited__title='Pro Django').values_list('name', flat=True)), - ['George Vilches']) - self.assertEqual(list(Person.objects.using('other').filter(edited__title='Pro Django').values_list('name', flat=True)), - []) + self.assertEqual( + list(Person.objects.using('default').filter(edited__title='Pro Django').values_list('name', flat=True)), + ['George Vilches'] + ) + self.assertEqual( + list(Person.objects.using('other').filter(edited__title='Pro Django').values_list('name', flat=True)), + [] + ) - self.assertEqual(list(Person.objects.using('default').filter(edited__title='Dive into Python').values_list('name', flat=True)), - []) - self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)), - ['Chris Mills']) + self.assertEqual( + list( + Person.objects.using('default').filter(edited__title='Dive into Python').values_list('name', flat=True) + ), + [] + ) + self.assertEqual( + list( + Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True) + ), + ['Chris Mills'] + ) # Reget the objects to clear caches chris = Person.objects.using('other').get(name="Chris Mills") @@ -452,37 +512,65 @@ class QueryTestCase(TestCase): # Add a second book edited by chris html5 = Book.objects.using('other').create(title="Dive into HTML5", published=datetime.date(2010, 3, 15)) - self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), - []) + self.assertEqual( + list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), + [] + ) chris.edited.add(html5) - self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), - ['Chris Mills']) - self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)), - ['Chris Mills']) + self.assertEqual( + list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), + ['Chris Mills'] + ) + self.assertEqual( + list( + Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True) + ), + ['Chris Mills'] + ) # Remove the second editor chris.edited.remove(html5) - self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), - []) - self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)), - ['Chris Mills']) + self.assertEqual( + list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), + [] + ) + self.assertEqual( + list( + Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True) + ), + ['Chris Mills'] + ) # Clear all edited books chris.edited.clear() - self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), - []) - self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)), - []) + self.assertEqual( + list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), + [] + ) + self.assertEqual( + list( + Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True) + ), + [] + ) # Create an author through the m2m interface chris.edited.create(title='Dive into Water', published=datetime.date(2010, 3, 15)) - self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), - []) - self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Water').values_list('name', flat=True)), - ['Chris Mills']) - self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)), - []) + self.assertEqual( + list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), + [] + ) + self.assertEqual( + list(Person.objects.using('other').filter(edited__title='Dive into Water').values_list('name', flat=True)), + ['Chris Mills'] + ) + self.assertEqual( + list( + Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True) + ), + [] + ) def test_foreign_key_cross_database_protection(self): "Operations that involve sharing FK objects across databases raise an error" @@ -556,15 +644,35 @@ class QueryTestCase(TestCase): self.assertEqual(bob.userprofile.flavor, "crunchy frog") # Check that queries work across joins - self.assertEqual(list(User.objects.using('default').filter(userprofile__flavor='chocolate').values_list('username', flat=True)), - ['alice']) - self.assertEqual(list(User.objects.using('other').filter(userprofile__flavor='chocolate').values_list('username', flat=True)), - []) + self.assertEqual( + list( + User.objects.using('default') + .filter(userprofile__flavor='chocolate').values_list('username', flat=True) + ), + ['alice'] + ) + self.assertEqual( + list( + User.objects.using('other') + .filter(userprofile__flavor='chocolate').values_list('username', flat=True) + ), + [] + ) - self.assertEqual(list(User.objects.using('default').filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)), - []) - self.assertEqual(list(User.objects.using('other').filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)), - ['bob']) + self.assertEqual( + list( + User.objects.using('default') + .filter(userprofile__flavor='crunchy frog').values_list('username', flat=True) + ), + [] + ) + self.assertEqual( + list( + User.objects.using('other') + .filter(userprofile__flavor='crunchy frog').values_list('username', flat=True) + ), + ['bob'] + ) # Reget the objects to clear caches alice_profile = UserProfile.objects.using('default').get(flavor='chocolate') @@ -683,38 +791,58 @@ class QueryTestCase(TestCase): review1 = Review.objects.using('other').create(source="Python Weekly", content_object=dive) review2 = Review.objects.using('other').create(source="Python Monthly", content_object=temp) - self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), - []) - self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), - ['Python Weekly']) + self.assertEqual( + list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), + [] + ) + self.assertEqual( + list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), + ['Python Weekly'] + ) # Add a second review dive.reviews.add(review2) - self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), - []) - self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), - ['Python Monthly', 'Python Weekly']) + self.assertEqual( + list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), + [] + ) + self.assertEqual( + list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), + ['Python Monthly', 'Python Weekly'] + ) # Remove the second author dive.reviews.remove(review1) - self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), - []) - self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), - ['Python Monthly']) + self.assertEqual( + list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), + [] + ) + self.assertEqual( + list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), + ['Python Monthly'] + ) # Clear all reviews dive.reviews.clear() - self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), - []) - self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), - []) + self.assertEqual( + list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), + [] + ) + self.assertEqual( + list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), + [] + ) # Create an author through the generic interface dive.reviews.create(source='Python Daily') - self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), - []) - self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), - ['Python Daily']) + self.assertEqual( + list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), + [] + ) + self.assertEqual( + list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), + ['Python Daily'] + ) def test_generic_key_cross_database_protection(self): "Operations that involve sharing generic key objects across databases raise an error" @@ -750,17 +878,25 @@ class QueryTestCase(TestCase): review3.content_object = dive self.assertEqual(review3._state.db, 'other') # ... but it isn't saved yet - self.assertEqual(list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)), - ['Python Monthly']) - self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), - ['Python Weekly']) + self.assertEqual( + list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)), + ['Python Monthly'] + ) + self.assertEqual( + list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), + ['Python Weekly'] + ) # When saved, John goes to 'other' review3.save() - self.assertEqual(list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)), - ['Python Monthly']) - self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), - ['Python Daily', 'Python Weekly']) + self.assertEqual( + list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)), + ['Python Monthly'] + ) + self.assertEqual( + list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), + ['Python Daily', 'Python Weekly'] + ) def test_generic_key_deletion(self): "Cascaded deletions of Generic Key relations issue queries on the right database" @@ -1178,7 +1314,10 @@ class RouterTestCase(TestCase): self.assertEqual(cheesecake._state.db, 'default') # Same goes for get_or_create, regardless of whether getting or creating - cheesecake, created = mark.edited.get_or_create(title='Dive into Cheesecake', published=datetime.date(2010, 3, 15)) + cheesecake, created = mark.edited.get_or_create( + title='Dive into Cheesecake', + published=datetime.date(2010, 3, 15), + ) self.assertEqual(cheesecake._state.db, 'default') puddles, created = mark.edited.get_or_create(title='Dive into Puddles', published=datetime.date(2010, 3, 15)) @@ -1589,7 +1728,10 @@ class FixtureTestCase(TestCase): @override_settings(DATABASE_ROUTERS=[AntiPetRouter()]) def test_pseudo_empty_fixtures(self): - "A fixture can contain entries, but lead to nothing in the database; this shouldn't raise an error (ref #14068)" + """ + A fixture can contain entries, but lead to nothing in the database; + this shouldn't raise an error (#14068). + """ new_io = StringIO() management.call_command('loaddata', 'pets', stdout=new_io, stderr=new_io) command_output = new_io.getvalue().strip() diff --git a/tests/nested_foreign_keys/tests.py b/tests/nested_foreign_keys/tests.py index 80c09810a4..34a3703e68 100644 --- a/tests/nested_foreign_keys/tests.py +++ b/tests/nested_foreign_keys/tests.py @@ -140,7 +140,10 @@ class DeeplyNestedForeignKeysTests(TestCase): self.assertEqual(len(Event.objects.values()), 2) self.assertEqual(len(Event.objects.values('screening__movie__director__pk')), 2) self.assertEqual(len(Event.objects.values('screening__movie__director__name')), 2) - self.assertEqual(len(Event.objects.values('screening__movie__director__pk', 'screening__movie__director__name')), 2) + self.assertEqual( + len(Event.objects.values('screening__movie__director__pk', 'screening__movie__director__name')), + 2 + ) self.assertEqual(len(Event.objects.values('screening__movie__pk', 'screening__movie__director__pk')), 2) self.assertEqual(len(Event.objects.values('screening__movie__pk', 'screening__movie__director__name')), 2) self.assertEqual(len(Event.objects.values('screening__movie__title', 'screening__movie__director__pk')), 2) @@ -160,7 +163,10 @@ class DeeplyNestedForeignKeysTests(TestCase): self.assertEqual(len(Package.objects.values()), 2) self.assertEqual(len(Package.objects.values('screening__movie__director__pk')), 2) self.assertEqual(len(Package.objects.values('screening__movie__director__name')), 2) - self.assertEqual(len(Package.objects.values('screening__movie__director__pk', 'screening__movie__director__name')), 2) + self.assertEqual( + len(Package.objects.values('screening__movie__director__pk', 'screening__movie__director__name')), + 2 + ) self.assertEqual(len(Package.objects.values('screening__movie__pk', 'screening__movie__director__pk')), 2) self.assertEqual(len(Package.objects.values('screening__movie__pk', 'screening__movie__director__name')), 2) self.assertEqual(len(Package.objects.values('screening__movie__title', 'screening__movie__director__pk')), 2) diff --git a/tests/or_lookups/tests.py b/tests/or_lookups/tests.py index 6cd1b539c7..55afed3fc4 100644 --- a/tests/or_lookups/tests.py +++ b/tests/or_lookups/tests.py @@ -24,7 +24,10 @@ class OrLookupsTests(TestCase): def test_filter_or(self): self.assertQuerysetEqual( - Article.objects.filter(headline__startswith='Hello') | Article.objects.filter(headline__startswith='Goodbye'), [ + ( + Article.objects.filter(headline__startswith='Hello') + | Article.objects.filter(headline__startswith='Goodbye') + ), [ 'Hello', 'Goodbye', 'Hello and goodbye' diff --git a/tests/postgres_tests/array_index_migrations/0001_initial.py b/tests/postgres_tests/array_index_migrations/0001_initial.py index 8c7688ad44..10c1780a46 100644 --- a/tests/postgres_tests/array_index_migrations/0001_initial.py +++ b/tests/postgres_tests/array_index_migrations/0001_initial.py @@ -15,7 +15,9 @@ class Migration(migrations.Migration): name='CharTextArrayIndexModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), - ('char', django.contrib.postgres.fields.ArrayField(models.CharField(max_length=10), db_index=True, size=100)), + ('char', django.contrib.postgres.fields.ArrayField( + models.CharField(max_length=10), db_index=True, size=100) + ), ('char2', models.CharField(max_length=11, db_index=True)), ('text', django.contrib.postgres.fields.ArrayField(models.TextField(), db_index=True)), ], diff --git a/tests/postgres_tests/test_array.py b/tests/postgres_tests/test_array.py index 09ae4e8546..fbc15bb2ac 100644 --- a/tests/postgres_tests/test_array.py +++ b/tests/postgres_tests/test_array.py @@ -341,7 +341,9 @@ class TestMigrations(TransactionTestCase): class TestSerialization(PostgreSQLTestCase): - test_data = '[{"fields": {"field": "[\\"1\\", \\"2\\"]"}, "model": "postgres_tests.integerarraymodel", "pk": null}]' + test_data = ( + '[{"fields": {"field": "[\\"1\\", \\"2\\"]"}, "model": "postgres_tests.integerarraymodel", "pk": null}]' + ) def test_dumping(self): instance = IntegerArrayModel(field=[1, 2]) @@ -360,7 +362,10 @@ class TestValidation(PostgreSQLTestCase): with self.assertRaises(exceptions.ValidationError) as cm: field.clean([1, None], None) self.assertEqual(cm.exception.code, 'item_invalid') - self.assertEqual(cm.exception.message % cm.exception.params, 'Item 1 in the array did not validate: This field cannot be null.') + self.assertEqual( + cm.exception.message % cm.exception.params, + 'Item 1 in the array did not validate: This field cannot be null.' + ) def test_blank_true(self): field = ArrayField(models.IntegerField(blank=True, null=True)) @@ -388,7 +393,10 @@ class TestValidation(PostgreSQLTestCase): with self.assertRaises(exceptions.ValidationError) as cm: field.clean([0], None) self.assertEqual(cm.exception.code, 'item_invalid') - self.assertEqual(cm.exception.messages[0], 'Item 0 in the array did not validate: Ensure this value is greater than or equal to 1.') + self.assertEqual( + cm.exception.messages[0], + 'Item 0 in the array did not validate: Ensure this value is greater than or equal to 1.' + ) class TestSimpleFormField(PostgreSQLTestCase): diff --git a/tests/postgres_tests/test_ranges.py b/tests/postgres_tests/test_ranges.py index 7d7fb33c4d..bde949d218 100644 --- a/tests/postgres_tests/test_ranges.py +++ b/tests/postgres_tests/test_ranges.py @@ -627,5 +627,6 @@ class TestWidget(PostgreSQLTestCase): ) self.assertHTMLEqual( f.widget.render('datetimerange', dt_range), - '' + '' + '' ) diff --git a/tests/prefetch_related/tests.py b/tests/prefetch_related/tests.py index d9e7488d42..0a864e93ae 100644 --- a/tests/prefetch_related/tests.py +++ b/tests/prefetch_related/tests.py @@ -313,7 +313,10 @@ class CustomPrefetchTests(TestCase): # Ambiguous: Lookup houses_lst doesn't yet exist when performing houses_lst__rooms. with self.assertRaises(AttributeError): self.traverse_qs( - Person.objects.prefetch_related('houses_lst__rooms', Prefetch('houses', queryset=House.objects.all(), to_attr='houses_lst')), + Person.objects.prefetch_related( + 'houses_lst__rooms', + Prefetch('houses', queryset=House.objects.all(), to_attr='houses_lst') + ), [['houses', 'rooms']] ) @@ -324,7 +327,10 @@ class CustomPrefetchTests(TestCase): ) self.traverse_qs( - Person.objects.prefetch_related('houses__rooms', Prefetch('houses', queryset=House.objects.all(), to_attr='houses_lst')), + Person.objects.prefetch_related( + 'houses__rooms', + Prefetch('houses', queryset=House.objects.all(), to_attr='houses_lst') + ), [['houses', 'rooms']] ) @@ -537,8 +543,15 @@ class CustomPrefetchTests(TestCase): # Test queryset filtering. with self.assertNumQueries(2): - lst2 = list(Person.objects.prefetch_related( - Prefetch('houses', queryset=House.objects.filter(pk__in=[self.house1.pk, self.house3.pk]), to_attr='houses_lst'))) + lst2 = list( + Person.objects.prefetch_related( + Prefetch( + 'houses', + queryset=House.objects.filter(pk__in=[self.house1.pk, self.house3.pk]), + to_attr='houses_lst', + ) + ) + ) self.assertEqual(len(lst2[0].houses_lst), 1) self.assertEqual(lst2[0].houses_lst[0], self.house1) self.assertEqual(len(lst2[1].houses_lst), 1) @@ -596,10 +609,14 @@ class CustomPrefetchTests(TestCase): rooms = Room.objects.all().prefetch_related(Prefetch('house', queryset=houses.all(), to_attr='house_attr')) lst2 = self.traverse_qs(rooms, [['house_attr', 'owner']]) self.assertEqual(lst1, lst2) - room = Room.objects.all().prefetch_related(Prefetch('house', queryset=houses.filter(address='DoesNotExist'))).first() + room = Room.objects.all().prefetch_related( + Prefetch('house', queryset=houses.filter(address='DoesNotExist')) + ).first() with self.assertRaises(ObjectDoesNotExist): getattr(room, 'house') - room = Room.objects.all().prefetch_related(Prefetch('house', queryset=houses.filter(address='DoesNotExist'), to_attr='house_attr')).first() + room = Room.objects.all().prefetch_related( + Prefetch('house', queryset=houses.filter(address='DoesNotExist'), to_attr='house_attr') + ).first() self.assertIsNone(room.house_attr) rooms = Room.objects.all().prefetch_related(Prefetch('house', queryset=House.objects.only('name'))) with self.assertNumQueries(2): @@ -617,13 +634,21 @@ class CustomPrefetchTests(TestCase): lst2 = self.traverse_qs(rooms, [['main_room_of', 'owner']]) self.assertEqual(lst1, lst2) with self.assertNumQueries(2): - rooms = list(Room.objects.all().prefetch_related(Prefetch('main_room_of', queryset=houses.all(), to_attr='main_room_of_attr'))) + rooms = list( + Room.objects.all().prefetch_related( + Prefetch('main_room_of', queryset=houses.all(), to_attr='main_room_of_attr') + ) + ) lst2 = self.traverse_qs(rooms, [['main_room_of_attr', 'owner']]) self.assertEqual(lst1, lst2) - room = Room.objects.filter(main_room_of__isnull=False).prefetch_related(Prefetch('main_room_of', queryset=houses.filter(address='DoesNotExist'))).first() + room = Room.objects.filter(main_room_of__isnull=False).prefetch_related( + Prefetch('main_room_of', queryset=houses.filter(address='DoesNotExist')) + ).first() with self.assertRaises(ObjectDoesNotExist): getattr(room, 'main_room_of') - room = Room.objects.filter(main_room_of__isnull=False).prefetch_related(Prefetch('main_room_of', queryset=houses.filter(address='DoesNotExist'), to_attr='main_room_of_attr')).first() + room = Room.objects.filter(main_room_of__isnull=False).prefetch_related( + Prefetch('main_room_of', queryset=houses.filter(address='DoesNotExist'), to_attr='main_room_of_attr') + ).first() self.assertIsNone(room.main_room_of_attr) def test_nested_prefetch_related_are_not_overwritten(self): diff --git a/tests/queries/tests.py b/tests/queries/tests.py index 23c9891079..05d9ca24a6 100644 --- a/tests/queries/tests.py +++ b/tests/queries/tests.py @@ -227,11 +227,25 @@ class Queries1Tests(BaseQuerysetTest): 4 ) self.assertEqual( - Item.objects.exclude(name='two').extra(select={'foo': '%s'}, select_params=(1,)).values('creator', 'name', 'foo').distinct().count(), + ( + Item.objects + .exclude(name='two') + .extra(select={'foo': '%s'}, select_params=(1,)) + .values('creator', 'name', 'foo') + .distinct() + .count() + ), 4 ) self.assertEqual( - Item.objects.exclude(name='two').extra(select={'foo': '%s'}, select_params=(1,)).values('creator', 'name').distinct().count(), + ( + Item.objects + .exclude(name='two') + .extra(select={'foo': '%s'}, select_params=(1,)) + .values('creator', 'name') + .distinct() + .count() + ), 4 ) xx.delete() @@ -355,7 +369,10 @@ class Queries1Tests(BaseQuerysetTest): # involve one "left outer" join (Author -> Item is 0-to-many). qs = Author.objects.filter(id=self.a1.id).filter(Q(extra__note=self.n1) | Q(item__note=self.n3)) self.assertEqual( - len([x for x in qs.query.alias_map.values() if x.join_type == LOUTER and qs.query.alias_refcount[x.table_alias]]), + len([ + x for x in qs.query.alias_map.values() + if x.join_type == LOUTER and qs.query.alias_refcount[x.table_alias] + ]), 1 ) @@ -568,7 +585,13 @@ class Queries1Tests(BaseQuerysetTest): self.assertEqual(d, {'a': 'one', 'b': 'two'}) # Order by the number of tags attached to an item. - l = Item.objects.extra(select={'count': 'select count(*) from queries_item_tags where queries_item_tags.item_id = queries_item.id'}).order_by('-count') + l = ( + Item.objects + .extra(select={ + 'count': 'select count(*) from queries_item_tags where queries_item_tags.item_id = queries_item.id' + }) + .order_by('-count') + ) self.assertEqual([o.count for o in l], [2, 2, 1, 0]) def test_ticket6154(self): @@ -704,7 +727,9 @@ class Queries1Tests(BaseQuerysetTest): def test_ticket7277(self): self.assertQuerysetEqual( - self.n1.annotation_set.filter(Q(tag=self.t5) | Q(tag__children=self.t5) | Q(tag__children__children=self.t5)), + self.n1.annotation_set.filter( + Q(tag=self.t5) | Q(tag__children=self.t5) | Q(tag__children__children=self.t5) + ), [''] ) @@ -1376,12 +1401,19 @@ class Queries4Tests(BaseQuerysetTest): self.assertEqual(str(q1.query), str(q2.query)) q1 = Item.objects.filter(Q(creator=self.a1) | Q(creator__report__name='r1')).order_by() - q2 = Item.objects.filter(Q(creator=self.a1)).order_by() | Item.objects.filter(Q(creator__report__name='r1')).order_by() + q2 = ( + Item.objects + .filter(Q(creator=self.a1)).order_by() | Item.objects.filter(Q(creator__report__name='r1')) + .order_by() + ) self.assertQuerysetEqual(q1, [""]) self.assertEqual(str(q1.query), str(q2.query)) q1 = Item.objects.filter(Q(creator__report__name='e1') | Q(creator=self.a1)).order_by() - q2 = Item.objects.filter(Q(creator__report__name='e1')).order_by() | Item.objects.filter(Q(creator=self.a1)).order_by() + q2 = ( + Item.objects.filter(Q(creator__report__name='e1')).order_by() + | Item.objects.filter(Q(creator=self.a1)).order_by() + ) self.assertQuerysetEqual(q1, [""]) self.assertEqual(str(q1.query), str(q2.query)) @@ -2621,7 +2653,10 @@ class DefaultValuesInsertTest(TestCase): try: DumbCategory.objects.create() except TypeError: - self.fail("Creation of an instance of a model with only the PK field shouldn't error out after bulk insert refactoring (#17056)") + self.fail( + "Creation of an instance of a model with only the PK field " + "shouldn't error out after bulk insert refactoring (#17056)" + ) class ExcludeTests(TestCase): @@ -3524,7 +3559,10 @@ class RelatedLookupTypeTests(TestCase): # child objects self.assertQuerysetEqual(ObjectB.objects.filter(objecta__in=[self.coa]), []) self.assertQuerysetEqual(ObjectB.objects.filter(objecta__in=[self.poa, self.coa]).order_by('name'), out_b) - self.assertQuerysetEqual(ObjectB.objects.filter(objecta__in=iter([self.poa, self.coa])).order_by('name'), out_b) + self.assertQuerysetEqual( + ObjectB.objects.filter(objecta__in=iter([self.poa, self.coa])).order_by('name'), + out_b + ) # parent objects self.assertQuerysetEqual(ObjectC.objects.exclude(childobjecta=self.oa), out_c) diff --git a/tests/raw_query/tests.py b/tests/raw_query/tests.py index 94f21f9a71..2f80c23f32 100644 --- a/tests/raw_query/tests.py +++ b/tests/raw_query/tests.py @@ -16,10 +16,26 @@ class RawQueryTests(TestCase): cls.a2 = Author.objects.create(first_name='Jill', last_name='Doe', dob=date(1920, 4, 2)) cls.a3 = Author.objects.create(first_name='Bob', last_name='Smith', dob=date(1986, 1, 25)) cls.a4 = Author.objects.create(first_name='Bill', last_name='Jones', dob=date(1932, 5, 10)) - cls.b1 = Book.objects.create(title='The awesome book', author=cls.a1, paperback=False, opening_line='It was a bright cold day in April and the clocks were striking thirteen.') - cls.b2 = Book.objects.create(title='The horrible book', author=cls.a1, paperback=True, opening_line='On an evening in the latter part of May a middle-aged man was walking homeward from Shaston to the village of Marlott, in the adjoining Vale of Blakemore, or Blackmoor.') - cls.b3 = Book.objects.create(title='Another awesome book', author=cls.a1, paperback=False, opening_line='A squat grey building of only thirty-four stories.') - cls.b4 = Book.objects.create(title='Some other book', author=cls.a3, paperback=True, opening_line='It was the day my grandmother exploded.') + cls.b1 = Book.objects.create( + title='The awesome book', author=cls.a1, paperback=False, + opening_line='It was a bright cold day in April and the clocks were striking thirteen.', + ) + cls.b2 = Book.objects.create( + title='The horrible book', author=cls.a1, paperback=True, + opening_line=( + 'On an evening in the latter part of May a middle-aged man ' + 'was walking homeward from Shaston to the village of Marlott, ' + 'in the adjoining Vale of Blakemore, or Blackmoor.' + ), + ) + cls.b3 = Book.objects.create( + title='Another awesome book', author=cls.a1, paperback=False, + opening_line='A squat grey building of only thirty-four stories.', + ) + cls.b4 = Book.objects.create( + title='Some other book', author=cls.a3, paperback=True, + opening_line='It was the day my grandmother exploded.', + ) cls.c1 = Coffee.objects.create(brand='dunkin doughnuts') cls.c2 = Coffee.objects.create(brand='starbucks') cls.r1 = Reviewer.objects.create() @@ -211,7 +227,12 @@ class RawQueryTests(TestCase): pass def test_annotations(self): - query = "SELECT a.*, count(b.id) as book_count FROM raw_query_author a LEFT JOIN raw_query_book b ON a.id = b.author_id GROUP BY a.id, a.first_name, a.last_name, a.dob ORDER BY a.id" + query = ( + "SELECT a.*, count(b.id) as book_count " + "FROM raw_query_author a " + "LEFT JOIN raw_query_book b ON a.id = b.author_id " + "GROUP BY a.id, a.first_name, a.last_name, a.dob ORDER BY a.id" + ) expected_annotations = ( ('book_count', 3), ('book_count', 0), diff --git a/tests/requests/tests.py b/tests/requests/tests.py index 3a3d7e7733..0b6254d0bb 100644 --- a/tests/requests/tests.py +++ b/tests/requests/tests.py @@ -88,10 +88,20 @@ class RequestsTests(SimpleTestCase): Refs #20169. """ # With trailing slash - request = WSGIRequest({'PATH_INFO': '/somepath/', 'SCRIPT_NAME': '/PREFIX/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) + request = WSGIRequest({ + 'PATH_INFO': '/somepath/', + 'SCRIPT_NAME': '/PREFIX/', + 'REQUEST_METHOD': 'get', + 'wsgi.input': BytesIO(b''), + }) self.assertEqual(request.path, '/PREFIX/somepath/') # Without trailing slash - request = WSGIRequest({'PATH_INFO': '/somepath/', 'SCRIPT_NAME': '/PREFIX', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) + request = WSGIRequest({ + 'PATH_INFO': '/somepath/', + 'SCRIPT_NAME': '/PREFIX', + 'REQUEST_METHOD': 'get', + 'wsgi.input': BytesIO(b''), + }) self.assertEqual(request.path, '/PREFIX/somepath/') def test_wsgirequest_with_force_script_name(self): @@ -101,7 +111,12 @@ class RequestsTests(SimpleTestCase): Refs #20169. """ with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX/'): - request = WSGIRequest({'PATH_INFO': '/somepath/', 'SCRIPT_NAME': '/PREFIX/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) + request = WSGIRequest({ + 'PATH_INFO': '/somepath/', + 'SCRIPT_NAME': '/PREFIX/', + 'REQUEST_METHOD': 'get', + 'wsgi.input': BytesIO(b''), + }) self.assertEqual(request.path, '/FORCED_PREFIX/somepath/') def test_wsgirequest_path_with_force_script_name_trailing_slash(self): diff --git a/tests/schema/tests.py b/tests/schema/tests.py index 384772bbb5..a63e3fa79d 100644 --- a/tests/schema/tests.py +++ b/tests/schema/tests.py @@ -336,7 +336,10 @@ class SchemaTests(TransactionTestCase): columns = self.column_classes(Author) # BooleanField are stored as TINYINT(1) on MySQL. field_type = columns['awesome'][0] - self.assertEqual(field_type, connection.features.introspected_boolean_field_type(new_field, created_separately=True)) + self.assertEqual( + field_type, + connection.features.introspected_boolean_field_type(new_field, created_separately=True) + ) def test_add_field_default_transform(self): """ @@ -1097,7 +1100,9 @@ class SchemaTests(TransactionTestCase): editor.create_model(TagM2MTest) editor.create_model(UniqueTest) # Ensure the M2M exists and points to TagM2MTest - constraints = self.get_constraints(LocalBookWithM2M._meta.get_field("tags").remote_field.through._meta.db_table) + constraints = self.get_constraints( + LocalBookWithM2M._meta.get_field("tags").remote_field.through._meta.db_table + ) if connection.features.supports_foreign_keys: for name, details in constraints.items(): if details['columns'] == ["tagm2mtest_id"] and details['foreign_key']: @@ -1113,7 +1118,10 @@ class SchemaTests(TransactionTestCase): with connection.schema_editor() as editor: editor.alter_field(LocalBookWithM2M, old_field, new_field) # Ensure old M2M is gone - self.assertRaises(DatabaseError, self.column_classes, LocalBookWithM2M._meta.get_field("tags").remote_field.through) + self.assertRaises( + DatabaseError, + self.column_classes, LocalBookWithM2M._meta.get_field("tags").remote_field.through + ) # Ensure the new M2M exists and points to UniqueTest constraints = self.get_constraints(new_field.remote_field.through._meta.db_table) if connection.features.supports_foreign_keys: diff --git a/tests/select_related/tests.py b/tests/select_related/tests.py index 53353a7715..b8acd586a6 100644 --- a/tests/select_related/tests.py +++ b/tests/select_related/tests.py @@ -53,7 +53,11 @@ class SelectRelatedTests(TestCase): extra queries """ with self.assertNumQueries(1): - person = Species.objects.select_related('genus__family__order__klass__phylum__kingdom__domain').get(name="sapiens") + person = ( + Species.objects + .select_related('genus__family__order__klass__phylum__kingdom__domain') + .get(name="sapiens") + ) domain = person.genus.family.order.klass.phylum.kingdom.domain self.assertEqual(domain.name, 'Eukaryota') diff --git a/tests/select_related_regress/tests.py b/tests/select_related_regress/tests.py index d014123beb..e575697cb1 100644 --- a/tests/select_related_regress/tests.py +++ b/tests/select_related_regress/tests.py @@ -39,7 +39,12 @@ class SelectRelatedRegressTests(TestCase): self.assertEqual([(c.id, six.text_type(c.start), six.text_type(c.end)) for c in connections], [(c1.id, 'router/4', 'switch/7'), (c2.id, 'switch/7', 'server/1')]) - connections = Connection.objects.filter(start__device__building=b, end__device__building=b).select_related().order_by('id') + connections = ( + Connection.objects + .filter(start__device__building=b, end__device__building=b) + .select_related() + .order_by('id') + ) self.assertEqual([(c.id, six.text_type(c.start), six.text_type(c.end)) for c in connections], [(c1.id, 'router/4', 'switch/7'), (c2.id, 'switch/7', 'server/1')]) diff --git a/tests/serializers/tests.py b/tests/serializers/tests.py index f6ebcba23a..8c5555d35d 100644 --- a/tests/serializers/tests.py +++ b/tests/serializers/tests.py @@ -352,7 +352,7 @@ class XmlSerializerTestCase(SerializersTestBase, TestCase): -""" +""" # NOQA @staticmethod def _comparison_value(value): diff --git a/tests/sites_framework/tests.py b/tests/sites_framework/tests.py index 681bfe5b03..ca516388cf 100644 --- a/tests/sites_framework/tests.py +++ b/tests/sites_framework/tests.py @@ -36,7 +36,10 @@ class SitesFrameworkTestCase(TestCase): self.assertEqual(SyndicatedArticle.on_site.all().get(), article) def test_custom_named_field(self): - article = CustomArticle.objects.create(title="Tantalizing News!", places_this_article_should_appear_id=settings.SITE_ID) + article = CustomArticle.objects.create( + title="Tantalizing News!", + places_this_article_should_appear_id=settings.SITE_ID, + ) self.assertEqual(CustomArticle.on_site.all().get(), article) def test_invalid_name(self): diff --git a/tests/syndication_tests/tests.py b/tests/syndication_tests/tests.py index 9922efc8b3..78c8708f9e 100644 --- a/tests/syndication_tests/tests.py +++ b/tests/syndication_tests/tests.py @@ -58,7 +58,10 @@ class FeedTestCase(TestCase): elem.getElementsByTagName(k)[0].firstChild.wholeText, v) def assertCategories(self, elem, expected): - self.assertEqual(set(i.firstChild.wholeText for i in elem.childNodes if i.nodeName == 'category'), set(expected)) + self.assertEqual( + set(i.firstChild.wholeText for i in elem.childNodes if i.nodeName == 'category'), + set(expected) + ) ###################################### # Feed view @@ -101,7 +104,12 @@ class SyndicationFeedTest(FeedTestCase): d = Entry.objects.latest('published').published last_build_date = rfc2822_date(timezone.make_aware(d, TZ)) - self.assertChildNodes(chan, ['title', 'link', 'description', 'language', 'lastBuildDate', 'item', 'atom:link', 'ttl', 'copyright', 'category']) + self.assertChildNodes( + chan, [ + 'title', 'link', 'description', 'language', 'lastBuildDate', + 'item', 'atom:link', 'ttl', 'copyright', 'category', + ] + ) self.assertChildNodeContent(chan, { 'title': 'My blog', 'description': 'A more thorough description of my blog.', @@ -197,7 +205,12 @@ class SyndicationFeedTest(FeedTestCase): chan_elem = feed.getElementsByTagName('channel') self.assertEqual(len(chan_elem), 1) chan = chan_elem[0] - self.assertChildNodes(chan, ['title', 'link', 'description', 'language', 'lastBuildDate', 'item', 'atom:link', 'ttl', 'copyright', 'category']) + self.assertChildNodes( + chan, [ + 'title', 'link', 'description', 'language', 'lastBuildDate', + 'item', 'atom:link', 'ttl', 'copyright', 'category', + ] + ) # Ensure the content of the channel is correct self.assertChildNodeContent(chan, { @@ -232,7 +245,10 @@ class SyndicationFeedTest(FeedTestCase): self.assertEqual(feed.nodeName, 'feed') self.assertEqual(feed.getAttribute('xmlns'), 'http://www.w3.org/2005/Atom') - self.assertChildNodes(feed, ['title', 'subtitle', 'link', 'id', 'updated', 'entry', 'rights', 'category', 'author']) + self.assertChildNodes( + feed, + ['title', 'subtitle', 'link', 'id', 'updated', 'entry', 'rights', 'category', 'author'] + ) for link in feed.getElementsByTagName('link'): if link.getAttribute('rel') == 'self': self.assertEqual(link.getAttribute('href'), 'http://example.com/syndication/atom/') @@ -299,7 +315,10 @@ class SyndicationFeedTest(FeedTestCase): self.assertEqual(feed.nodeName, 'feed') self.assertEqual(feed.getAttribute('django'), 'rocks') - self.assertChildNodes(feed, ['title', 'subtitle', 'link', 'id', 'updated', 'entry', 'spam', 'rights', 'category', 'author']) + self.assertChildNodes( + feed, + ['title', 'subtitle', 'link', 'id', 'updated', 'entry', 'spam', 'rights', 'category', 'author'] + ) entries = feed.getElementsByTagName('entry') self.assertEqual(len(entries), Entry.objects.count()) diff --git a/tests/template_tests/filter_tests/test_date.py b/tests/template_tests/filter_tests/test_date.py index 612742a501..1740df47da 100644 --- a/tests/template_tests/filter_tests/test_date.py +++ b/tests/template_tests/filter_tests/test_date.py @@ -42,7 +42,9 @@ class DateTests(TimezoneTestCase): # Timezone name @setup({'date06': '{{ d|date:"e" }}'}) def test_date06(self): - output = self.engine.render_to_string('date06', {'d': datetime(2009, 3, 12, tzinfo=timezone.get_fixed_timezone(30))}) + output = self.engine.render_to_string( + 'date06', {'d': datetime(2009, 3, 12, tzinfo=timezone.get_fixed_timezone(30))} + ) self.assertEqual(output, '+0030') @setup({'date07': '{{ d|date:"e" }}'}) diff --git a/tests/template_tests/filter_tests/test_random.py b/tests/template_tests/filter_tests/test_random.py index 155e473c7e..acb8a82f1d 100644 --- a/tests/template_tests/filter_tests/test_random.py +++ b/tests/template_tests/filter_tests/test_random.py @@ -8,10 +8,14 @@ class RandomTests(SimpleTestCase): @setup({'random01': '{{ a|random }} {{ b|random }}'}) def test_random01(self): - output = self.engine.render_to_string('random01', {'a': ['a&b', 'a&b'], 'b': [mark_safe('a&b'), mark_safe('a&b')]}) + output = self.engine.render_to_string( + 'random01', {'a': ['a&b', 'a&b'], 'b': [mark_safe('a&b'), mark_safe('a&b')]} + ) self.assertEqual(output, 'a&b a&b') @setup({'random02': '{% autoescape off %}{{ a|random }} {{ b|random }}{% endautoescape %}'}) def test_random02(self): - output = self.engine.render_to_string('random02', {'a': ['a&b', 'a&b'], 'b': [mark_safe('a&b'), mark_safe('a&b')]}) + output = self.engine.render_to_string( + 'random02', {'a': ['a&b', 'a&b'], 'b': [mark_safe('a&b'), mark_safe('a&b')]} + ) self.assertEqual(output, 'a&b a&b') diff --git a/tests/template_tests/filter_tests/test_timesince.py b/tests/template_tests/filter_tests/test_timesince.py index 52901cea36..0572b5bd1c 100644 --- a/tests/template_tests/filter_tests/test_timesince.py +++ b/tests/template_tests/filter_tests/test_timesince.py @@ -18,17 +18,23 @@ class TimesinceTests(TimezoneTestCase): # Default compare with datetime.now() @setup({'timesince01': '{{ a|timesince }}'}) def test_timesince01(self): - output = self.engine.render_to_string('timesince01', {'a': datetime.now() + timedelta(minutes=-1, seconds=-10)}) + output = self.engine.render_to_string( + 'timesince01', {'a': datetime.now() + timedelta(minutes=-1, seconds=-10)} + ) self.assertEqual(output, '1\xa0minute') @setup({'timesince02': '{{ a|timesince }}'}) def test_timesince02(self): - output = self.engine.render_to_string('timesince02', {'a': datetime.now() - timedelta(days=1, minutes=1)}) + output = self.engine.render_to_string( + 'timesince02', {'a': datetime.now() - timedelta(days=1, minutes=1)} + ) self.assertEqual(output, '1\xa0day') @setup({'timesince03': '{{ a|timesince }}'}) def test_timesince03(self): - output = self.engine.render_to_string('timesince03', {'a': datetime.now() - timedelta(hours=1, minutes=25, seconds=10)}) + output = self.engine.render_to_string( + 'timesince03', {'a': datetime.now() - timedelta(hours=1, minutes=25, seconds=10)} + ) self.assertEqual(output, '1\xa0hour, 25\xa0minutes') # Compare to a given parameter @@ -62,7 +68,9 @@ class TimesinceTests(TimezoneTestCase): @setup({'timesince08': '{{ earlier|timesince:now }}'}) def test_timesince08(self): - output = self.engine.render_to_string('timesince08', {'now': self.now, 'earlier': self.now - timedelta(days=7)}) + output = self.engine.render_to_string( + 'timesince08', {'now': self.now, 'earlier': self.now - timedelta(days=7)} + ) self.assertEqual(output, '1\xa0week') @setup({'timesince09': '{{ later|timesince }}'}) diff --git a/tests/template_tests/filter_tests/test_timeuntil.py b/tests/template_tests/filter_tests/test_timeuntil.py index 5befabb379..2fe633ffa2 100644 --- a/tests/template_tests/filter_tests/test_timeuntil.py +++ b/tests/template_tests/filter_tests/test_timeuntil.py @@ -25,7 +25,9 @@ class TimeuntilTests(TimezoneTestCase): @setup({'timeuntil03': '{{ a|timeuntil }}'}) def test_timeuntil03(self): - output = self.engine.render_to_string('timeuntil03', {'a': (datetime.now() + timedelta(hours=8, minutes=10, seconds=10))}) + output = self.engine.render_to_string( + 'timeuntil03', {'a': (datetime.now() + timedelta(hours=8, minutes=10, seconds=10))} + ) self.assertEqual(output, '8\xa0hours, 10\xa0minutes') # Compare to a given parameter @@ -53,7 +55,9 @@ class TimeuntilTests(TimezoneTestCase): @setup({'timeuntil07': '{{ earlier|timeuntil:now }}'}) def test_timeuntil07(self): - output = self.engine.render_to_string('timeuntil07', {'now': self.now, 'earlier': self.now - timedelta(days=7)}) + output = self.engine.render_to_string( + 'timeuntil07', {'now': self.now, 'earlier': self.now - timedelta(days=7)} + ) self.assertEqual(output, '0\xa0minutes') @setup({'timeuntil08': '{{ later|timeuntil }}'}) diff --git a/tests/template_tests/filter_tests/test_truncatewords.py b/tests/template_tests/filter_tests/test_truncatewords.py index 97b6013bb1..4941e736fd 100644 --- a/tests/template_tests/filter_tests/test_truncatewords.py +++ b/tests/template_tests/filter_tests/test_truncatewords.py @@ -7,15 +7,20 @@ from ..utils import setup class TruncatewordsTests(SimpleTestCase): - @setup({'truncatewords01': - '{% autoescape off %}{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}{% endautoescape %}'}) + @setup({ + 'truncatewords01': '{% autoescape off %}{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}{% endautoescape %}' + }) def test_truncatewords01(self): - output = self.engine.render_to_string('truncatewords01', {'a': 'alpha & bravo', 'b': mark_safe('alpha & bravo')}) + output = self.engine.render_to_string( + 'truncatewords01', {'a': 'alpha & bravo', 'b': mark_safe('alpha & bravo')} + ) self.assertEqual(output, 'alpha & ... alpha & ...') @setup({'truncatewords02': '{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}'}) def test_truncatewords02(self): - output = self.engine.render_to_string('truncatewords02', {'a': 'alpha & bravo', 'b': mark_safe('alpha & bravo')}) + output = self.engine.render_to_string( + 'truncatewords02', {'a': 'alpha & bravo', 'b': mark_safe('alpha & bravo')} + ) self.assertEqual(output, 'alpha & ... alpha & ...') diff --git a/tests/template_tests/filter_tests/test_urlize.py b/tests/template_tests/filter_tests/test_urlize.py index 1d14778905..81451f2d4e 100644 --- a/tests/template_tests/filter_tests/test_urlize.py +++ b/tests/template_tests/filter_tests/test_urlize.py @@ -340,7 +340,7 @@ class FunctionTests(SimpleTestCase): def test_autoescape(self): self.assertEqual( urlize('foobarbuz'), - 'foo<a href=" google.com ">bar</a>buz', + 'foo<a href=" google.com ">bar</a>buz' ) def test_autoescape_off(self): diff --git a/tests/template_tests/filter_tests/test_urlizetrunc.py b/tests/template_tests/filter_tests/test_urlizetrunc.py index cb5c2a6daf..4badf44029 100644 --- a/tests/template_tests/filter_tests/test_urlizetrunc.py +++ b/tests/template_tests/filter_tests/test_urlizetrunc.py @@ -82,7 +82,7 @@ class FunctionTests(SimpleTestCase): def test_autoescape(self): self.assertEqual( urlizetrunc('foobarbuz', 10), - 'foo<a href=" google.com ">bar</a>buz', + 'foo<a href=" google.com ">bar</a>buz' ) def test_autoescape_off(self): diff --git a/tests/template_tests/syntax_tests/test_extends.py b/tests/template_tests/syntax_tests/test_extends.py index 46600cb76c..bc320a2fc2 100644 --- a/tests/template_tests/syntax_tests/test_extends.py +++ b/tests/template_tests/syntax_tests/test_extends.py @@ -251,7 +251,9 @@ class InheritanceTests(SimpleTestCase): """ Inheritance from local context without use of template loader """ - context_template = self.engine.from_string("1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}") + context_template = self.engine.from_string( + "1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}" + ) output = self.engine.render_to_string('inheritance24', {'context_template': context_template}) self.assertEqual(output, '1234') diff --git a/tests/template_tests/syntax_tests/test_for.py b/tests/template_tests/syntax_tests/test_for.py index 32fc5f0e3e..f3d571cff1 100644 --- a/tests/template_tests/syntax_tests/test_for.py +++ b/tests/template_tests/syntax_tests/test_for.py @@ -95,7 +95,9 @@ class ForTagTests(SimpleTestCase): @setup({'for-tag-unpack13': '{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}'}) def test_for_tag_unpack13(self): - output = self.engine.render_to_string('for-tag-unpack13', {'items': (('one', 1, 'carrot'), ('two', 2, 'cheese'))}) + output = self.engine.render_to_string( + 'for-tag-unpack13', {'items': (('one', 1, 'carrot'), ('two', 2, 'cheese'))} + ) if self.engine.string_if_invalid: self.assertEqual(output, 'one:1,carrot/two:2,cheese/') else: diff --git a/tests/template_tests/syntax_tests/test_if_changed.py b/tests/template_tests/syntax_tests/test_if_changed.py index ee67c64218..bf8a95d8a4 100644 --- a/tests/template_tests/syntax_tests/test_if_changed.py +++ b/tests/template_tests/syntax_tests/test_if_changed.py @@ -182,7 +182,9 @@ class IfChangedTests(SimpleTestCase): # When the IfChangeNode stores state at 'self' it stays at '3' and skip the last yielded value below. iter2 = iter([1, 2, 3]) output2 = template.render(Context({'foo': range(3), 'get_value': lambda: next(iter2)})) - self.assertEqual(output2, '[0,1,2,3]', 'Expected [0,1,2,3] in second parallel template, got {}'.format(output2)) + self.assertEqual( + output2, '[0,1,2,3]', 'Expected [0,1,2,3] in second parallel template, got {}'.format(output2) + ) yield 3 gen1 = gen() diff --git a/tests/template_tests/syntax_tests/test_url.py b/tests/template_tests/syntax_tests/test_url.py index bd1ea885d0..0877a316f1 100644 --- a/tests/template_tests/syntax_tests/test_url.py +++ b/tests/template_tests/syntax_tests/test_url.py @@ -127,7 +127,9 @@ class UrlTagTests(SimpleTestCase): @ignore_warnings(category=RemovedInDjango110Warning) @setup({'url19': '{% url named_url client.id %}'}) def test_url19(self): - output = self.engine.render_to_string('url19', {'client': {'id': 1}, 'named_url': 'template_tests.views.client'}) + output = self.engine.render_to_string( + 'url19', {'client': {'id': 1}, 'named_url': 'template_tests.views.client'} + ) self.assertEqual(output, '/client/1/') @setup({'url20': '{% url url_name_in_var client.id %}'}) diff --git a/tests/template_tests/templatetags/custom.py b/tests/template_tests/templatetags/custom.py index 9d47ca4201..ea1d7c6e67 100644 --- a/tests/template_tests/templatetags/custom.py +++ b/tests/template_tests/templatetags/custom.py @@ -80,7 +80,9 @@ simple_one_default.anything = "Expected simple_one_default __dict__" @register.simple_tag def simple_unlimited_args(one, two='hi', *args): """Expected simple_unlimited_args __doc__""" - return "simple_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args))) + return "simple_unlimited_args - Expected result: %s" % ( + ', '.join(six.text_type(arg) for arg in [one, two] + list(args)) + ) simple_unlimited_args.anything = "Expected simple_unlimited_args __dict__" diff --git a/tests/template_tests/templatetags/inclusion.py b/tests/template_tests/templatetags/inclusion.py index 54cc81abe3..185cdb1917 100644 --- a/tests/template_tests/templatetags/inclusion.py +++ b/tests/template_tests/templatetags/inclusion.py @@ -59,21 +59,34 @@ inclusion_no_params_with_context.anything = "Expected inclusion_no_params_with_c @register.inclusion_tag(engine.get_template('inclusion.html'), takes_context=True) def inclusion_no_params_with_context_from_template(context): """Expected inclusion_no_params_with_context_from_template __doc__""" - return {"result": "inclusion_no_params_with_context_from_template - Expected result (context value: %s)" % context['value']} -inclusion_no_params_with_context_from_template.anything = "Expected inclusion_no_params_with_context_from_template __dict__" + return { + "result": ( + "inclusion_no_params_with_context_from_template - Expected result (context value: %s)" % context['value'] + ) + } +inclusion_no_params_with_context_from_template.anything = ( + "Expected inclusion_no_params_with_context_from_template __dict__" +) @register.inclusion_tag('inclusion.html', takes_context=True) def inclusion_params_and_context(context, arg): """Expected inclusion_params_and_context __doc__""" - return {"result": "inclusion_params_and_context - Expected result (context value: %s): %s" % (context['value'], arg)} + return { + "result": "inclusion_params_and_context - Expected result (context value: %s): %s" % (context['value'], arg) + } inclusion_params_and_context.anything = "Expected inclusion_params_and_context __dict__" @register.inclusion_tag(engine.get_template('inclusion.html'), takes_context=True) def inclusion_params_and_context_from_template(context, arg): """Expected inclusion_params_and_context_from_template __doc__""" - return {"result": "inclusion_params_and_context_from_template - Expected result (context value: %s): %s" % (context['value'], arg)} + return { + "result": ( + "inclusion_params_and_context_from_template - Expected result " + "(context value: %s): %s" % (context['value'], arg) + ) + } inclusion_params_and_context_from_template.anything = "Expected inclusion_params_and_context_from_template __dict__" @@ -108,28 +121,48 @@ inclusion_one_default_from_template.anything = "Expected inclusion_one_default_f @register.inclusion_tag('inclusion.html') def inclusion_unlimited_args(one, two='hi', *args): """Expected inclusion_unlimited_args __doc__""" - return {"result": "inclusion_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args)))} + return { + "result": ( + "inclusion_unlimited_args - Expected result: %s" % ( + ', '.join(six.text_type(arg) for arg in [one, two] + list(args)) + ) + ) + } inclusion_unlimited_args.anything = "Expected inclusion_unlimited_args __dict__" @register.inclusion_tag(engine.get_template('inclusion.html')) def inclusion_unlimited_args_from_template(one, two='hi', *args): """Expected inclusion_unlimited_args_from_template __doc__""" - return {"result": "inclusion_unlimited_args_from_template - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args)))} + return { + "result": ( + "inclusion_unlimited_args_from_template - Expected result: %s" % ( + ', '.join(six.text_type(arg) for arg in [one, two] + list(args)) + ) + ) + } inclusion_unlimited_args_from_template.anything = "Expected inclusion_unlimited_args_from_template __dict__" @register.inclusion_tag('inclusion.html') def inclusion_only_unlimited_args(*args): """Expected inclusion_only_unlimited_args __doc__""" - return {"result": "inclusion_only_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in args))} + return { + "result": "inclusion_only_unlimited_args - Expected result: %s" % ( + ', '.join(six.text_type(arg) for arg in args) + ) + } inclusion_only_unlimited_args.anything = "Expected inclusion_only_unlimited_args __dict__" @register.inclusion_tag(engine.get_template('inclusion.html')) def inclusion_only_unlimited_args_from_template(*args): """Expected inclusion_only_unlimited_args_from_template __doc__""" - return {"result": "inclusion_only_unlimited_args_from_template - Expected result: %s" % (', '.join(six.text_type(arg) for arg in args))} + return { + "result": "inclusion_only_unlimited_args_from_template - Expected result: %s" % ( + ', '.join(six.text_type(arg) for arg in args) + ) + } inclusion_only_unlimited_args_from_template.anything = "Expected inclusion_only_unlimited_args_from_template __dict__" diff --git a/tests/template_tests/test_custom.py b/tests/template_tests/test_custom.py index dec97589d6..1b63953860 100644 --- a/tests/template_tests/test_custom.py +++ b/tests/template_tests/test_custom.py @@ -162,7 +162,10 @@ class InclusionTagTests(TagTestCase): 'inclusion_params_and_context - Expected result (context value: 42): 37\n'), ('{% load inclusion %}{% inclusion_two_params 37 42 %}', 'inclusion_two_params - Expected result: 37, 42\n'), - ('{% load inclusion %}{% inclusion_one_default 37 %}', 'inclusion_one_default - Expected result: 37, hi\n'), + ( + '{% load inclusion %}{% inclusion_one_default 37 %}', + 'inclusion_one_default - Expected result: 37, hi\n' + ), ('{% load inclusion %}{% inclusion_one_default 37 two="hello" %}', 'inclusion_one_default - Expected result: 37, hello\n'), ('{% load inclusion %}{% inclusion_one_default one=99 two="hello" %}', diff --git a/tests/template_tests/test_extends.py b/tests/template_tests/test_extends.py index 03a674e25b..7a9008cf54 100644 --- a/tests/template_tests/test_extends.py +++ b/tests/template_tests/test_extends.py @@ -42,16 +42,19 @@ class ExtendsBehaviorTests(SimpleTestCase): def test_recursive_multiple_loaders(self): engine = Engine( dirs=[os.path.join(RECURSIVE, 'fs')], - loaders=[ - ('django.template.loaders.locmem.Loader', { - 'one.html': '{% extends "one.html" %}{% block content %}{{ block.super }} locmem-one{% endblock %}', - 'two.html': '{% extends "two.html" %}{% block content %}{{ block.super }} locmem-two{% endblock %}', + loaders=[( + 'django.template.loaders.locmem.Loader', { + 'one.html': ( + '{% extends "one.html" %}{% block content %}{{ block.super }} locmem-one{% endblock %}' + ), + 'two.html': ( + '{% extends "two.html" %}{% block content %}{{ block.super }} locmem-two{% endblock %}' + ), 'three.html': ( '{% extends "three.html" %}{% block content %}{{ block.super }} locmem-three{% endblock %}' ), - }), - 'django.template.loaders.filesystem.Loader', - ], + } + ), 'django.template.loaders.filesystem.Loader'], ) template = engine.get_template('one.html') output = template.render(Context({})) diff --git a/tests/template_tests/test_nodelist.py b/tests/template_tests/test_nodelist.py index 46b48404dd..042702e3c0 100644 --- a/tests/template_tests/test_nodelist.py +++ b/tests/template_tests/test_nodelist.py @@ -56,9 +56,21 @@ class ErrorIndexTest(TestCase): def test_correct_exception_index(self): tests = [ ('{% load bad_tag %}{% for i in range %}{% badsimpletag %}{% endfor %}', (38, 56)), - ('{% load bad_tag %}{% for i in range %}{% for j in range %}{% badsimpletag %}{% endfor %}{% endfor %}', (58, 76)), - ('{% load bad_tag %}{% for i in range %}{% badsimpletag %}{% for j in range %}Hello{% endfor %}{% endfor %}', (38, 56)), - ('{% load bad_tag %}{% for i in range %}{% for j in five %}{% badsimpletag %}{% endfor %}{% endfor %}', (38, 57)), + ( + '{% load bad_tag %}{% for i in range %}{% for j in range %}' + '{% badsimpletag %}{% endfor %}{% endfor %}', + (58, 76) + ), + ( + '{% load bad_tag %}{% for i in range %}{% badsimpletag %}' + '{% for j in range %}Hello{% endfor %}{% endfor %}', + (38, 56) + ), + ( + '{% load bad_tag %}{% for i in range %}{% for j in five %}' + '{% badsimpletag %}{% endfor %}{% endfor %}', + (38, 57) + ), ('{% load bad_tag %}{% for j in five %}{% badsimpletag %}{% endfor %}', (18, 37)), ] context = Context({ diff --git a/tests/test_client/tests.py b/tests/test_client/tests.py index 042633ad54..1a6a453d04 100644 --- a/tests/test_client/tests.py +++ b/tests/test_client/tests.py @@ -156,7 +156,9 @@ class ClientTest(TestCase): def test_raw_post(self): "POST raw data (with a content type) to a view" - test_doc = """BlinkMalcolm Gladwell""" + test_doc = """ + BlinkMalcolm Gladwell + """ response = self.client.post("/raw_post_view/", test_doc, content_type="text/xml") self.assertEqual(response.status_code, 200) diff --git a/tests/test_client/views.py b/tests/test_client/views.py index 070e6305c2..a4cc5cd3a7 100644 --- a/tests/test_client/views.py +++ b/tests/test_client/views.py @@ -230,7 +230,9 @@ def login_protected_view_changed_redirect(request): c = Context({'user': request.user}) return HttpResponse(t.render(c)) -login_protected_view_changed_redirect = login_required(redirect_field_name="redirect_to")(login_protected_view_changed_redirect) +login_protected_view_changed_redirect = ( + login_required(redirect_field_name="redirect_to")(login_protected_view_changed_redirect) +) def _permission_protected_view(request): @@ -242,7 +244,9 @@ def _permission_protected_view(request): c = Context({'user': request.user}) return HttpResponse(t.render(c)) permission_protected_view = permission_required('permission_not_granted')(_permission_protected_view) -permission_protected_view_exception = permission_required('permission_not_granted', raise_exception=True)(_permission_protected_view) +permission_protected_view_exception = ( + permission_required('permission_not_granted', raise_exception=True)(_permission_protected_view) +) class _ViewManager(object): diff --git a/tests/test_client_regress/tests.py b/tests/test_client_regress/tests.py index a492fd6e76..500c28f9ae 100644 --- a/tests/test_client_regress/tests.py +++ b/tests/test_client_regress/tests.py @@ -261,12 +261,20 @@ class AssertTemplateUsedTests(TestDataMixin, TestCase): try: self.assertTemplateUsed(response, 'Empty POST Template') except AssertionError as e: - self.assertIn("Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e)) + self.assertIn( + "Template 'Empty POST Template' was not a template used to " + "render the response. Actual template(s) used: Empty GET Template", + str(e) + ) try: self.assertTemplateUsed(response, 'Empty POST Template', msg_prefix='abc') except AssertionError as e: - self.assertIn("abc: Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e)) + self.assertIn( + "abc: Template 'Empty POST Template' was not a template used " + "to render the response. Actual template(s) used: Empty GET Template", + str(e) + ) with self.assertRaises(AssertionError) as context: self.assertTemplateUsed(response, 'Empty GET Template', count=2) @@ -307,7 +315,11 @@ class AssertTemplateUsedTests(TestDataMixin, TestCase): try: self.assertTemplateUsed(response, "Valid POST Template") except AssertionError as e: - self.assertIn("Template 'Valid POST Template' was not a template used to render the response. Actual template(s) used: form_view.html, base.html", str(e)) + self.assertIn( + "Template 'Valid POST Template' was not a template used to " + "render the response. Actual template(s) used: form_view.html, base.html", + str(e) + ) with self.assertRaises(AssertionError) as context: self.assertTemplateUsed(response, 'base.html', count=2) @@ -369,13 +381,21 @@ class AssertRedirectsTests(SimpleTestCase): # The redirect target responds with a 301 code, not 200 self.assertRedirects(response, 'http://testserver/permanent_redirect_view/') except AssertionError as e: - self.assertIn("Couldn't retrieve redirection page '/permanent_redirect_view/': response code was 301 (expected 200)", str(e)) + self.assertIn( + "Couldn't retrieve redirection page '/permanent_redirect_view/': " + "response code was 301 (expected 200)", + str(e) + ) try: # The redirect target responds with a 301 code, not 200 self.assertRedirects(response, 'http://testserver/permanent_redirect_view/', msg_prefix='abc') except AssertionError as e: - self.assertIn("abc: Couldn't retrieve redirection page '/permanent_redirect_view/': response code was 301 (expected 200)", str(e)) + self.assertIn( + "abc: Couldn't retrieve redirection page '/permanent_redirect_view/': " + "response code was 301 (expected 200)", + str(e) + ) def test_redirect_chain(self): "You can follow a redirect chain of multiple redirects" @@ -615,11 +635,23 @@ class AssertFormErrorTests(SimpleTestCase): try: self.assertFormError(response, 'form', 'email', 'Some error.') except AssertionError as e: - self.assertIn(str_prefix("The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [%(_)s'Enter a valid email address.'])"), str(e)) + self.assertIn( + str_prefix( + "The field 'email' on form 'form' in context 0 does not " + "contain the error 'Some error.' (actual errors: " + "[%(_)s'Enter a valid email address.'])" + ), str(e) + ) try: self.assertFormError(response, 'form', 'email', 'Some error.', msg_prefix='abc') except AssertionError as e: - self.assertIn(str_prefix("abc: The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [%(_)s'Enter a valid email address.'])"), str(e)) + self.assertIn( + str_prefix( + "abc: The field 'email' on form 'form' in context 0 does " + "not contain the error 'Some error.' (actual errors: " + "[%(_)s'Enter a valid email address.'])", + ), str(e) + ) def test_unknown_nonfield_error(self): """ @@ -640,11 +672,19 @@ class AssertFormErrorTests(SimpleTestCase): try: self.assertFormError(response, 'form', None, 'Some error.') except AssertionError as e: - self.assertIn("The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e)) + self.assertIn( + "The form 'form' in context 0 does not contain the non-field " + "error 'Some error.' (actual errors: )", + str(e) + ) try: self.assertFormError(response, 'form', None, 'Some error.', msg_prefix='abc') except AssertionError as e: - self.assertIn("abc: The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e)) + self.assertIn( + "abc: The form 'form' in context 0 does not contain the " + "non-field error 'Some error.' (actual errors: )", + str(e) + ) @override_settings(ROOT_URLCONF='test_client_regress.urls') diff --git a/tests/test_runner/runner.py b/tests/test_runner/runner.py index 8dc4c74111..ec79395663 100644 --- a/tests/test_runner/runner.py +++ b/tests/test_runner/runner.py @@ -3,7 +3,8 @@ from django.test.runner import DiscoverRunner class CustomOptionsTestRunner(DiscoverRunner): - def __init__(self, verbosity=1, interactive=True, failfast=True, option_a=None, option_b=None, option_c=None, **kwargs): + def __init__(self, verbosity=1, interactive=True, failfast=True, + option_a=None, option_b=None, option_c=None, **kwargs): super(CustomOptionsTestRunner, self).__init__(verbosity=verbosity, interactive=interactive, failfast=failfast) self.option_a = option_a diff --git a/tests/test_utils/tests.py b/tests/test_utils/tests.py index 6869f49666..00c9c0fa2b 100644 --- a/tests/test_utils/tests.py +++ b/tests/test_utils/tests.py @@ -363,7 +363,8 @@ class AssertTemplateUsedContextManagerTests(SimpleTestCase): with self.assertTemplateUsed(template_name='template_used/base.html'): pass - with six.assertRaisesRegex(self, AssertionError, r'^template_used/base\.html.*template_used/alternative\.html$'): + with six.assertRaisesRegex( + self, AssertionError, r'^template_used/base\.html.*template_used/alternative\.html$'): with self.assertTemplateUsed('template_used/base.html'): render_to_string('template_used/alternative.html') @@ -519,13 +520,16 @@ class HTMLEqualTests(SimpleTestCase): """, """ - + + - + + - + + """) @@ -645,7 +649,11 @@ class HTMLEqualTests(SimpleTestCase): def test_unicode_handling(self): response = HttpResponse('

      Some help text for the title (with unicode ŠĐĆŽćžšđ)

      ') - self.assertContains(response, '

      Some help text for the title (with unicode ŠĐĆŽćžšđ)

      ', html=True) + self.assertContains( + response, + '

      Some help text for the title (with unicode ŠĐĆŽćžšđ)

      ', + html=True + ) class JSONEqualTests(SimpleTestCase): @@ -805,9 +813,14 @@ class AssertFieldOutputTests(SimpleTestCase): def test_assert_field_output(self): error_invalid = ['Enter a valid email address.'] self.assertFieldOutput(EmailField, {'a@a.com': 'a@a.com'}, {'aaa': error_invalid}) - self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'a@a.com'}, {'aaa': error_invalid + ['Another error']}) - self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'Wrong output'}, {'aaa': error_invalid}) - self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'a@a.com'}, {'aaa': ['Come on, gimme some well formatted data, dude.']}) + with self.assertRaises(AssertionError): + self.assertFieldOutput(EmailField, {'a@a.com': 'a@a.com'}, {'aaa': error_invalid + ['Another error']}) + with self.assertRaises(AssertionError): + self.assertFieldOutput(EmailField, {'a@a.com': 'Wrong output'}, {'aaa': error_invalid}) + with self.assertRaises(AssertionError): + self.assertFieldOutput( + EmailField, {'a@a.com': 'a@a.com'}, {'aaa': ['Come on, gimme some well formatted data, dude.']} + ) def test_custom_required_message(self): class MyCustomField(IntegerField): diff --git a/tests/timezones/tests.py b/tests/timezones/tests.py index 65a052f2cb..7f550baf6c 100644 --- a/tests/timezones/tests.py +++ b/tests/timezones/tests.py @@ -856,9 +856,18 @@ class TemplateTests(TestCase): } templates = { 'notag': Template("{% load tz %}{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:ICT }}"), - 'noarg': Template("{% load tz %}{% localtime %}{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}"), - 'on': Template("{% load tz %}{% localtime on %}{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}"), - 'off': Template("{% load tz %}{% localtime off %}{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}"), + 'noarg': Template( + "{% load tz %}{% localtime %}{{ dt }}|{{ dt|localtime }}|" + "{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}" + ), + 'on': Template( + "{% load tz %}{% localtime on %}{{ dt }}|{{ dt|localtime }}|" + "{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}" + ), + 'off': Template( + "{% load tz %}{% localtime off %}{{ dt }}|{{ dt|localtime }}|" + "{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}" + ), } # Transform a list of keys in 'datetimes' to the expected template @@ -978,7 +987,10 @@ class TemplateTests(TestCase): ) ctx = Context({'dt': datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC), 'tz1': ICT, 'tz2': None}) - self.assertEqual(tpl.render(ctx), "2011-09-01T13:20:30+03:00|2011-09-01T17:20:30+07:00|2011-09-01T13:20:30+03:00") + self.assertEqual( + tpl.render(ctx), + "2011-09-01T13:20:30+03:00|2011-09-01T17:20:30+07:00|2011-09-01T13:20:30+03:00" + ) @requires_pytz def test_timezone_templatetag_with_pytz(self): @@ -1014,7 +1026,10 @@ class TemplateTests(TestCase): with timezone.override(UTC): self.assertEqual(tpl.render(Context()), "UTC") - tpl = Template("{% load tz %}{% timezone tz %}{% get_current_timezone as time_zone %}{% endtimezone %}{{ time_zone }}") + tpl = Template( + "{% load tz %}{% timezone tz %}{% get_current_timezone as time_zone %}" + "{% endtimezone %}{{ time_zone }}" + ) self.assertEqual(tpl.render(Context({'tz': ICT})), "+0700") with timezone.override(UTC): @@ -1029,7 +1044,11 @@ class TemplateTests(TestCase): with timezone.override(pytz.timezone('Europe/Paris')): self.assertEqual(tpl.render(Context()), "Europe/Paris") - tpl = Template("{% load tz %}{% timezone 'Europe/Paris' %}{% get_current_timezone as time_zone %}{% endtimezone %}{{ time_zone }}") + tpl = Template( + "{% load tz %}{% timezone 'Europe/Paris' %}" + "{% get_current_timezone as time_zone %}{% endtimezone %}" + "{{ time_zone }}" + ) self.assertEqual(tpl.render(Context()), "Europe/Paris") def test_get_current_timezone_templatetag_invalid_argument(self): @@ -1056,7 +1075,10 @@ class TemplateTests(TestCase): self.assertEqual(tpl.render(ctx), "2011-09-02 at 03:20:20") def test_date_and_time_template_filters_honor_localtime(self): - tpl = Template("{% load tz %}{% localtime off %}{{ dt|date:'Y-m-d' }} at {{ dt|time:'H:i:s' }}{% endlocaltime %}") + tpl = Template( + "{% load tz %}{% localtime off %}{{ dt|date:'Y-m-d' }} at " + "{{ dt|time:'H:i:s' }}{% endlocaltime %}" + ) ctx = Context({'dt': datetime.datetime(2011, 9, 1, 20, 20, 20, tzinfo=UTC)}) self.assertEqual(tpl.render(ctx), "2011-09-01 at 20:20:20") with timezone.override(ICT): diff --git a/tests/urlpatterns_reverse/namespace_urls.py b/tests/urlpatterns_reverse/namespace_urls.py index 460778860f..7fddce8f8e 100644 --- a/tests/urlpatterns_reverse/namespace_urls.py +++ b/tests/urlpatterns_reverse/namespace_urls.py @@ -49,7 +49,10 @@ urlpatterns = [ url(r'^inc(?P[0-9]+)/', include('urlpatterns_reverse.included_urls', namespace='inc-ns5')), url(r'^included/([0-9]+)/', include('urlpatterns_reverse.included_namespace_urls')), - url(r'^ns-outer/(?P[0-9]+)/', include('urlpatterns_reverse.included_namespace_urls', namespace='inc-outer')), + url( + r'^ns-outer/(?P[0-9]+)/', + include('urlpatterns_reverse.included_namespace_urls', namespace='inc-outer') + ), url(r'^\+\\\$\*/', include('urlpatterns_reverse.namespace_urls', namespace='special')), ] diff --git a/tests/urlpatterns_reverse/tests.py b/tests/urlpatterns_reverse/tests.py index 66803cd762..292b981907 100644 --- a/tests/urlpatterns_reverse/tests.py +++ b/tests/urlpatterns_reverse/tests.py @@ -37,42 +37,104 @@ 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'}), - ('/view_class/42/37/', 'view-class', '', '', 'view-class', views.view_class_instance, tuple(), {'arg1': '42', 'arg2': '37'}), - ('/included/normal/42/37/', 'inc-normal-view', '', '', 'inc-normal-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}), - ('/included/view_class/42/37/', 'inc-view-class', '', '', 'inc-view-class', views.view_class_instance, tuple(), {'arg1': '42', 'arg2': '37'}), + ( + '/view_class/42/37/', 'view-class', '', '', 'view-class', views.view_class_instance, tuple(), + {'arg1': '42', 'arg2': '37'} + ), + ( + '/included/normal/42/37/', 'inc-normal-view', '', '', 'inc-normal-view', views.empty_view, tuple(), + {'arg1': '42', 'arg2': '37'} + ), + ( + '/included/view_class/42/37/', 'inc-view-class', '', '', 'inc-view-class', views.view_class_instance, tuple(), + {'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'}), - ('/included/mixed_args/42/37/', 'inc-mixed-args', '', '', 'inc-mixed-args', views.empty_view, tuple(), {'arg2': '37'}), - ('/included/12/mixed_args/42/37/', 'inc-mixed-args', '', '', 'inc-mixed-args', views.empty_view, tuple(), {'arg2': '37'}), + ( + '/included/mixed_args/42/37/', 'inc-mixed-args', '', '', 'inc-mixed-args', views.empty_view, tuple(), + {'arg2': '37'} + ), + ( + '/included/12/mixed_args/42/37/', 'inc-mixed-args', '', '', 'inc-mixed-args', views.empty_view, tuple(), + {'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(), {'arg1': '42', 'arg2': '37'}), - ('/unnamed/view_class/42/37/', None, '', '', 'urlpatterns_reverse.views.ViewClass', views.view_class_instance, tuple(), {'arg1': '42', 'arg2': '37'}), + ( + '/unnamed/normal/42/37/', None, '', '', 'urlpatterns_reverse.views.empty_view', views.empty_view, tuple(), + {'arg1': '42', 'arg2': '37'} + ), + ( + '/unnamed/view_class/42/37/', None, '', '', 'urlpatterns_reverse.views.ViewClass', views.view_class_instance, + tuple(), {'arg1': '42', 'arg2': '37'} + ), # If you have no kwargs, you get an args list. ('/no_kwargs/42/37/', 'no-kwargs', '', '', 'no-kwargs', views.empty_view, ('42', '37'), {}), ('/included/no_kwargs/42/37/', 'inc-no-kwargs', '', '', 'inc-no-kwargs', views.empty_view, ('42', '37'), {}), - ('/included/12/no_kwargs/42/37/', 'inc-no-kwargs', '', '', 'inc-no-kwargs', views.empty_view, ('12', '42', '37'), {}), + ( + '/included/12/no_kwargs/42/37/', 'inc-no-kwargs', '', '', 'inc-no-kwargs', views.empty_view, + ('12', '42', '37'), {} + ), # Namespaces - ('/test1/inner/42/37/', 'urlobject-view', 'testapp', 'test-ns1', 'test-ns1:urlobject-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}), - ('/included/test3/inner/42/37/', 'urlobject-view', 'testapp', 'test-ns3', 'test-ns3:urlobject-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}), - ('/ns-included1/normal/42/37/', 'inc-normal-view', '', 'inc-ns1', 'inc-ns1:inc-normal-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}), - ('/included/test3/inner/42/37/', 'urlobject-view', 'testapp', 'test-ns3', 'test-ns3:urlobject-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}), - ('/default/inner/42/37/', 'urlobject-view', 'testapp', 'testapp', 'testapp:urlobject-view', views.empty_view, tuple(), {'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'}), - ('/other1/inner/42/37/', 'urlobject-view', 'nodefault', 'other-ns1', 'other-ns1:urlobject-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}), + ( + '/test1/inner/42/37/', 'urlobject-view', 'testapp', 'test-ns1', 'test-ns1:urlobject-view', + views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'} + ), + ( + '/included/test3/inner/42/37/', 'urlobject-view', 'testapp', 'test-ns3', 'test-ns3:urlobject-view', + views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'} + ), + ( + '/ns-included1/normal/42/37/', 'inc-normal-view', '', 'inc-ns1', 'inc-ns1:inc-normal-view', views.empty_view, + tuple(), {'arg1': '42', 'arg2': '37'} + ), + ( + '/included/test3/inner/42/37/', 'urlobject-view', 'testapp', 'test-ns3', 'test-ns3:urlobject-view', + views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'} + ), + ( + '/default/inner/42/37/', 'urlobject-view', 'testapp', 'testapp', 'testapp:urlobject-view', views.empty_view, + tuple(), {'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'} + ), + ( + '/other1/inner/42/37/', 'urlobject-view', 'nodefault', 'other-ns1', 'other-ns1:urlobject-view', + views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'} + ), # Nested namespaces - ('/ns-included1/test3/inner/42/37/', 'urlobject-view', 'testapp', 'inc-ns1:test-ns3', 'inc-ns1:test-ns3:urlobject-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}), - ('/ns-included1/ns-included4/ns-included2/test3/inner/42/37/', 'urlobject-view', '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'}), - ('/app-included/test3/inner/42/37/', 'urlobject-view', 'inc-app:testapp', 'inc-app:test-ns3', 'inc-app:test-ns3:urlobject-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}), - ('/app-included/ns-included4/ns-included2/test3/inner/42/37/', 'urlobject-view', 'inc-app: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'}), + ( + '/ns-included1/test3/inner/42/37/', 'urlobject-view', 'testapp', 'inc-ns1:test-ns3', + 'inc-ns1:test-ns3:urlobject-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'} + ), + ( + '/ns-included1/ns-included4/ns-included2/test3/inner/42/37/', 'urlobject-view', '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'} + ), + ( + '/app-included/test3/inner/42/37/', 'urlobject-view', 'inc-app:testapp', 'inc-app:test-ns3', + 'inc-app:test-ns3:urlobject-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'} + ), + ( + '/app-included/ns-included4/ns-included2/test3/inner/42/37/', 'urlobject-view', 'inc-app: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'} + ), # Namespaces capturing variables ('/inc70/', 'inner-nothing', '', 'inc-ns5', 'inc-ns5:inner-nothing', views.empty_view, tuple(), {'outer': '70'}), - ('/inc78/extra/foobar/', 'inner-extra', '', 'inc-ns5', 'inc-ns5:inner-extra', views.empty_view, tuple(), {'outer': '78', 'extra': 'foobar'}), + ( + '/inc78/extra/foobar/', 'inner-extra', '', 'inc-ns5', 'inc-ns5:inner-extra', views.empty_view, tuple(), + {'outer': '78', 'extra': 'foobar'} + ), ) test_data = ( @@ -122,7 +184,10 @@ test_data = ( ('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)), - ('windows', r'/windows_path/C:%5CDocuments%20and%20Settings%5Cspam/', [], dict(drive_name='C', path=r'Documents and Settings\spam')), + ( + 'windows', r'/windows_path/C:%5CDocuments%20and%20Settings%5Cspam/', [], + dict(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'], {}), ('special', r'/special_chars/10%25%20complete/', [r'10% complete'], {}), @@ -367,7 +432,13 @@ class ResolverTests(unittest.TestCase): # make sure we at least matched the root ('/') url resolver: self.assertIn('tried', e.args[0]) tried = e.args[0]['tried'] - self.assertEqual(len(e.args[0]['tried']), len(url_types_names), 'Wrong number of tried URLs returned. Expected %s, got %s.' % (len(url_types_names), len(e.args[0]['tried']))) + self.assertEqual( + len(e.args[0]['tried']), + len(url_types_names), + 'Wrong number of tried URLs returned. Expected %s, got %s.' % ( + len(url_types_names), len(e.args[0]['tried']) + ) + ) for tried, expected in zip(e.args[0]['tried'], url_types_names): for t, e in zip(tried, expected): self.assertIsInstance(t, e['type']), str('%s is not an instance of %s') % (t, e['type']) @@ -375,7 +446,11 @@ class ResolverTests(unittest.TestCase): if not e['name']: self.assertIsNone(t.name, 'Expected no URL name but found %s.' % t.name) else: - self.assertEqual(t.name, e['name'], 'Wrong URL name. Expected "%s", got "%s".' % (e['name'], t.name)) + self.assertEqual( + t.name, + e['name'], + 'Wrong URL name. Expected "%s", got "%s".' % (e['name'], t.name) + ) @override_settings(ROOT_URLCONF='urlpatterns_reverse.reverse_lazy_urls') @@ -535,35 +610,46 @@ class NamespaceTests(SimpleTestCase): "Namespace defaults to app_name when including a (pattern, app_name) 2-tuple" self.assertEqual('/new-default/inner/', reverse('newapp:urlobject-view')) self.assertEqual('/new-default/inner/37/42/', reverse('newapp:urlobject-view', args=[37, 42])) - self.assertEqual('/new-default/inner/42/37/', reverse('newapp:urlobject-view', kwargs={'arg1': 42, 'arg2': 37})) + self.assertEqual( + '/new-default/inner/42/37/', reverse('newapp:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}) + ) self.assertEqual('/new-default/inner/+%5C$*/', reverse('newapp:urlobject-special-view')) def test_embedded_namespace_object(self): "Namespaces can be installed anywhere in the URL pattern tree" self.assertEqual('/included/test3/inner/', reverse('test-ns3:urlobject-view')) self.assertEqual('/included/test3/inner/37/42/', reverse('test-ns3:urlobject-view', args=[37, 42])) - self.assertEqual('/included/test3/inner/42/37/', reverse('test-ns3:urlobject-view', kwargs={'arg1': 42, 'arg2': 37})) + self.assertEqual( + '/included/test3/inner/42/37/', reverse('test-ns3:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}) + ) self.assertEqual('/included/test3/inner/+%5C$*/', reverse('test-ns3:urlobject-special-view')) def test_namespace_pattern(self): "Namespaces can be applied to include()'d urlpatterns" self.assertEqual('/ns-included1/normal/', reverse('inc-ns1:inc-normal-view')) self.assertEqual('/ns-included1/normal/37/42/', reverse('inc-ns1:inc-normal-view', args=[37, 42])) - self.assertEqual('/ns-included1/normal/42/37/', reverse('inc-ns1:inc-normal-view', kwargs={'arg1': 42, 'arg2': 37})) + self.assertEqual( + '/ns-included1/normal/42/37/', reverse('inc-ns1:inc-normal-view', kwargs={'arg1': 42, 'arg2': 37}) + ) self.assertEqual('/ns-included1/+%5C$*/', reverse('inc-ns1:inc-special-view')) def test_app_name_pattern(self): "Namespaces can be applied to include()'d urlpatterns that set an app_name attribute" self.assertEqual('/app-included1/normal/', reverse('app-ns1:inc-normal-view')) self.assertEqual('/app-included1/normal/37/42/', reverse('app-ns1:inc-normal-view', args=[37, 42])) - self.assertEqual('/app-included1/normal/42/37/', reverse('app-ns1:inc-normal-view', kwargs={'arg1': 42, 'arg2': 37})) + self.assertEqual( + '/app-included1/normal/42/37/', reverse('app-ns1:inc-normal-view', kwargs={'arg1': 42, 'arg2': 37}) + ) self.assertEqual('/app-included1/+%5C$*/', reverse('app-ns1:inc-special-view')) def test_namespace_pattern_with_variable_prefix(self): "When using an include with namespaces when there is a regex variable in front of it" self.assertEqual('/ns-outer/42/normal/', reverse('inc-outer:inc-normal-view', kwargs={'outer': 42})) self.assertEqual('/ns-outer/42/normal/', reverse('inc-outer:inc-normal-view', args=[42])) - self.assertEqual('/ns-outer/42/normal/37/4/', reverse('inc-outer:inc-normal-view', kwargs={'outer': 42, 'arg1': 37, 'arg2': 4})) + self.assertEqual( + '/ns-outer/42/normal/37/4/', + reverse('inc-outer:inc-normal-view', kwargs={'outer': 42, 'arg1': 37, 'arg2': 4}) + ) self.assertEqual('/ns-outer/42/normal/37/4/', reverse('inc-outer:inc-normal-view', args=[42, 37, 4])) self.assertEqual('/ns-outer/42/+%5C$*/', reverse('inc-outer:inc-special-view', kwargs={'outer': 42})) self.assertEqual('/ns-outer/42/+%5C$*/', reverse('inc-outer:inc-special-view', args=[42])) @@ -572,15 +658,30 @@ class NamespaceTests(SimpleTestCase): "Namespaces can be embedded" self.assertEqual('/ns-included1/test3/inner/', reverse('inc-ns1:test-ns3:urlobject-view')) self.assertEqual('/ns-included1/test3/inner/37/42/', reverse('inc-ns1:test-ns3:urlobject-view', args=[37, 42])) - self.assertEqual('/ns-included1/test3/inner/42/37/', reverse('inc-ns1:test-ns3:urlobject-view', kwargs={'arg1': 42, 'arg2': 37})) + self.assertEqual( + '/ns-included1/test3/inner/42/37/', + reverse('inc-ns1:test-ns3:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}) + ) self.assertEqual('/ns-included1/test3/inner/+%5C$*/', reverse('inc-ns1:test-ns3:urlobject-special-view')) def test_nested_namespace_pattern(self): "Namespaces can be nested" - self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view')) - self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/37/42/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', args=[37, 42])) - self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/42/37/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', kwargs={'arg1': 42, 'arg2': 37})) - self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/+%5C$*/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-special-view')) + self.assertEqual( + '/ns-included1/ns-included4/ns-included1/test3/inner/', + reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view') + ) + self.assertEqual( + '/ns-included1/ns-included4/ns-included1/test3/inner/37/42/', + reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', args=[37, 42]) + ) + self.assertEqual( + '/ns-included1/ns-included4/ns-included1/test3/inner/42/37/', + reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}) + ) + self.assertEqual( + '/ns-included1/ns-included4/ns-included1/test3/inner/+%5C$*/', + reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-special-view') + ) def test_app_lookup_object(self): "A default application namespace can be used for lookup" @@ -592,9 +693,17 @@ class NamespaceTests(SimpleTestCase): def test_app_lookup_object_with_default(self): "A default application namespace is sensitive to the 'current' app can be used for lookup" self.assertEqual('/included/test3/inner/', reverse('testapp:urlobject-view', current_app='test-ns3')) - self.assertEqual('/included/test3/inner/37/42/', reverse('testapp:urlobject-view', args=[37, 42], current_app='test-ns3')) - self.assertEqual('/included/test3/inner/42/37/', reverse('testapp:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}, current_app='test-ns3')) - self.assertEqual('/included/test3/inner/+%5C$*/', reverse('testapp:urlobject-special-view', current_app='test-ns3')) + self.assertEqual( + '/included/test3/inner/37/42/', + reverse('testapp:urlobject-view', args=[37, 42], current_app='test-ns3') + ) + self.assertEqual( + '/included/test3/inner/42/37/', + reverse('testapp:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}, current_app='test-ns3') + ) + self.assertEqual( + '/included/test3/inner/+%5C$*/', reverse('testapp:urlobject-special-view', current_app='test-ns3') + ) def test_app_lookup_object_without_default(self): "An application namespace without a default is sensitive to the 'current' app can be used for lookup" @@ -604,20 +713,30 @@ class NamespaceTests(SimpleTestCase): self.assertEqual('/other2/inner/+%5C$*/', reverse('nodefault:urlobject-special-view')) self.assertEqual('/other1/inner/', reverse('nodefault:urlobject-view', current_app='other-ns1')) - self.assertEqual('/other1/inner/37/42/', reverse('nodefault:urlobject-view', args=[37, 42], current_app='other-ns1')) - self.assertEqual('/other1/inner/42/37/', reverse('nodefault:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}, current_app='other-ns1')) + self.assertEqual( + '/other1/inner/37/42/', reverse('nodefault:urlobject-view', args=[37, 42], current_app='other-ns1') + ) + self.assertEqual( + '/other1/inner/42/37/', + reverse('nodefault:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}, current_app='other-ns1') + ) self.assertEqual('/other1/inner/+%5C$*/', reverse('nodefault:urlobject-special-view', current_app='other-ns1')) def test_special_chars_namespace(self): self.assertEqual('/+%5C$*/included/normal/', reverse('special:inc-normal-view')) self.assertEqual('/+%5C$*/included/normal/37/42/', reverse('special:inc-normal-view', args=[37, 42])) - self.assertEqual('/+%5C$*/included/normal/42/37/', reverse('special:inc-normal-view', kwargs={'arg1': 42, 'arg2': 37})) + self.assertEqual( + '/+%5C$*/included/normal/42/37/', + reverse('special:inc-normal-view', kwargs={'arg1': 42, 'arg2': 37}) + ) self.assertEqual('/+%5C$*/included/+%5C$*/', reverse('special:inc-special-view')) def test_namespaces_with_variables(self): "Namespace prefixes can capture variables: see #15900" self.assertEqual('/inc70/', reverse('inc-ns5:inner-nothing', kwargs={'outer': '70'})) - self.assertEqual('/inc78/extra/foobar/', reverse('inc-ns5:inner-extra', kwargs={'outer': '78', 'extra': 'foobar'})) + self.assertEqual( + '/inc78/extra/foobar/', reverse('inc-ns5:inner-extra', kwargs={'outer': '78', 'extra': 'foobar'}) + ) self.assertEqual('/inc70/', reverse('inc-ns5:inner-nothing', args=['70'])) self.assertEqual('/inc78/extra/foobar/', reverse('inc-ns5:inner-extra', args=['78', 'foobar'])) diff --git a/tests/user_commands/management/commands/optparse_cmd.py b/tests/user_commands/management/commands/optparse_cmd.py index 0ab74837d8..09de44b200 100644 --- a/tests/user_commands/management/commands/optparse_cmd.py +++ b/tests/user_commands/management/commands/optparse_cmd.py @@ -16,5 +16,7 @@ class Command(BaseCommand): options["example"] # BaseCommand default option is available options['verbosity'] - assert isinstance(options['verbosity'], int), "verbosity option is not int, but %s" % type(options['verbosity']) + assert ( + isinstance(options['verbosity'], int), "verbosity option is not int, but %s" % type(options['verbosity']) + ) self.stdout.write("All right, let's dance %s." % options["style"]) diff --git a/tests/utils_tests/test_datetime_safe.py b/tests/utils_tests/test_datetime_safe.py index dcb519b8fb..d86a60400b 100644 --- a/tests/utils_tests/test_datetime_safe.py +++ b/tests/utils_tests/test_datetime_safe.py @@ -22,17 +22,27 @@ class DatetimeTests(unittest.TestCase): self.assertEqual(original_date(*self.more_recent), date(*self.more_recent)) self.assertEqual(original_date(*self.really_old), date(*self.really_old)) - self.assertEqual(original_date(*self.just_safe).strftime('%Y-%m-%d'), date(*self.just_safe).strftime('%Y-%m-%d')) - self.assertEqual(original_datetime(*self.just_safe).strftime('%Y-%m-%d'), datetime(*self.just_safe).strftime('%Y-%m-%d')) + self.assertEqual( + original_date(*self.just_safe).strftime('%Y-%m-%d'), date(*self.just_safe).strftime('%Y-%m-%d') + ) + self.assertEqual( + original_datetime(*self.just_safe).strftime('%Y-%m-%d'), datetime(*self.just_safe).strftime('%Y-%m-%d') + ) - self.assertEqual(original_time(*self.just_time).strftime('%H:%M:%S'), time(*self.just_time).strftime('%H:%M:%S')) + self.assertEqual( + original_time(*self.just_time).strftime('%H:%M:%S'), time(*self.just_time).strftime('%H:%M:%S') + ) def test_safe_strftime(self): self.assertEqual(date(*self.just_unsafe[:3]).strftime('%Y-%m-%d (weekday %w)'), '1899-12-31 (weekday 0)') self.assertEqual(date(*self.just_safe).strftime('%Y-%m-%d (weekday %w)'), '1900-01-01 (weekday 1)') - self.assertEqual(datetime(*self.just_unsafe).strftime('%Y-%m-%d %H:%M:%S (weekday %w)'), '1899-12-31 23:59:59 (weekday 0)') - self.assertEqual(datetime(*self.just_safe).strftime('%Y-%m-%d %H:%M:%S (weekday %w)'), '1900-01-01 00:00:00 (weekday 1)') + self.assertEqual( + datetime(*self.just_unsafe).strftime('%Y-%m-%d %H:%M:%S (weekday %w)'), '1899-12-31 23:59:59 (weekday 0)' + ) + self.assertEqual( + datetime(*self.just_safe).strftime('%Y-%m-%d %H:%M:%S (weekday %w)'), '1900-01-01 00:00:00 (weekday 1)' + ) self.assertEqual(time(*self.just_time).strftime('%H:%M:%S AM'), '11:30:59 AM') diff --git a/tests/utils_tests/test_feedgenerator.py b/tests/utils_tests/test_feedgenerator.py index 427af5e742..21c88f93ce 100644 --- a/tests/utils_tests/test_feedgenerator.py +++ b/tests/utils_tests/test_feedgenerator.py @@ -26,7 +26,10 @@ class FeedgeneratorTest(unittest.TestCase): numbers. """ self.assertEqual( - feedgenerator.get_tag_uri('http://www.example.org:8000/2008/11/14/django#headline', datetime.datetime(2008, 11, 14, 13, 37, 0)), + feedgenerator.get_tag_uri( + 'http://www.example.org:8000/2008/11/14/django#headline', + datetime.datetime(2008, 11, 14, 13, 37, 0), + ), 'tag:www.example.org,2008-11-14:/2008/11/14/django/headline') def test_rfc2822_date(self): diff --git a/tests/utils_tests/test_html.py b/tests/utils_tests/test_html.py index bc9874c696..298aa304a3 100644 --- a/tests/utils_tests/test_html.py +++ b/tests/utils_tests/test_html.py @@ -147,9 +147,15 @@ class TestUtilsHtml(SimpleTestCase): items = ( ('"double quotes" and \'single quotes\'', '\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027'), (r'\ : backslashes, too', '\\u005C : backslashes, too'), - ('and lots of whitespace: \r\n\t\v\f\b', 'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008'), + ( + 'and lots of whitespace: \r\n\t\v\f\b', + 'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008' + ), (r'', '\\u003Cscript\\u003Eand this\\u003C/script\\u003E'), - ('paragraph separator:\u2029and line separator:\u2028', 'paragraph separator:\\u2029and line separator:\\u2028'), + ( + 'paragraph separator:\u2029and line separator:\u2028', + 'paragraph separator:\\u2029and line separator:\\u2028' + ), ) for value, output in items: self.check_output(f, value, output) diff --git a/tests/utils_tests/test_jslex.py b/tests/utils_tests/test_jslex.py index 42d0346144..8308d2830b 100644 --- a/tests/utils_tests/test_jslex.py +++ b/tests/utils_tests/test_jslex.py @@ -13,7 +13,10 @@ class JsTokensTest(SimpleTestCase): ("a ABC $ _ a123", ["id a", "id ABC", "id $", "id _", "id a123"]), ("\\u1234 abc\\u0020 \\u0065_\\u0067", ["id \\u1234", "id abc\\u0020", "id \\u0065_\\u0067"]), # numbers - ("123 1.234 0.123e-3 0 1E+40 1e1 .123", ["dnum 123", "dnum 1.234", "dnum 0.123e-3", "dnum 0", "dnum 1E+40", "dnum 1e1", "dnum .123"]), + ("123 1.234 0.123e-3 0 1E+40 1e1 .123", [ + "dnum 123", "dnum 1.234", "dnum 0.123e-3", "dnum 0", "dnum 1E+40", + "dnum 1e1", "dnum .123", + ]), ("0x1 0xabCD 0XABcd", ["hnum 0x1", "hnum 0xabCD", "hnum 0XABcd"]), ("010 0377 090", ["onum 010", "onum 0377", "dnum 0", "dnum 90"]), ("0xa123ghi", ["hnum 0xa123", "id ghi"]), @@ -23,8 +26,10 @@ class JsTokensTest(SimpleTestCase): ("true true_enough", ["reserved true", "id true_enough"]), # strings (''' 'hello' "hello" ''', ["string 'hello'", 'string "hello"']), - (r""" 'don\'t' "don\"t" '"' "'" '\'' "\"" """, - [r"""string 'don\'t'""", r'''string "don\"t"''', r"""string '"'""", r'''string "'"''', r"""string '\''""", r'''string "\""''']), + (r""" 'don\'t' "don\"t" '"' "'" '\'' "\"" """, [ + r"""string 'don\'t'""", r'''string "don\"t"''', r"""string '"'""", + r'''string "'"''', r"""string '\''""", r'''string "\""''' + ]), (r'"ƃuıxǝ⅂ ʇdıɹɔsɐʌɐſ\""', [r'string "ƃuıxǝ⅂ ʇdıɹɔsɐʌɐſ\""']), # comments ("a//b", ["id a", "linecomment //b"]), @@ -54,7 +59,7 @@ class JsTokensTest(SimpleTestCase): # Various "illegal" regexes that are valid according to the std. (r"""/????/, /++++/, /[----]/ """, ["regex /????/", "punct ,", "regex /++++/", "punct ,", "regex /[----]/"]), - # Stress cases from http://stackoverflow.com/questions/5533925/what-javascript-constructs-does-jslex-incorrectly-lex/5573409#5573409 + # Stress cases from http://stackoverflow.com/questions/5533925/what-javascript-constructs-does-jslex-incorrectly-lex/5573409#5573409 # NOQA (r"""/\[/""", [r"""regex /\[/"""]), (r"""/[i]/""", [r"""regex /[i]/"""]), (r"""/[\]]/""", [r"""regex /[\]]/"""]), @@ -70,13 +75,14 @@ class JsTokensTest(SimpleTestCase): NUMERIC_LITERAL: /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/, SYMBOL: /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/ }; - """, + """, # NOQA ["id rexl", "punct .", "id re", "punct =", "punct {", "id NAME", "punct :", r"""regex /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/""", "punct ,", - "id UNQUOTED_LITERAL", "punct :", r"""regex /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""", "punct ,", + "id UNQUOTED_LITERAL", "punct :", r"""regex /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""", + "punct ,", "id QUOTED_LITERAL", "punct :", r"""regex /^'(?:[^']|'')*'/""", "punct ,", "id NUMERIC_LITERAL", "punct :", r"""regex /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/""", "punct ,", - "id SYMBOL", "punct :", r"""regex /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""", + "id SYMBOL", "punct :", r"""regex /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""", # NOQA "punct }", "punct ;" ]), @@ -89,20 +95,22 @@ class JsTokensTest(SimpleTestCase): SYMBOL: /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/ }; str = '"'; - """, + """, # NOQA ["id rexl", "punct .", "id re", "punct =", "punct {", "id NAME", "punct :", r"""regex /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/""", "punct ,", - "id UNQUOTED_LITERAL", "punct :", r"""regex /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""", "punct ,", + "id UNQUOTED_LITERAL", "punct :", r"""regex /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""", + "punct ,", "id QUOTED_LITERAL", "punct :", r"""regex /^'(?:[^']|'')*'/""", "punct ,", "id NUMERIC_LITERAL", "punct :", r"""regex /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/""", "punct ,", - "id SYMBOL", "punct :", r"""regex /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""", + "id SYMBOL", "punct :", r"""regex /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""", # NOQA "punct }", "punct ;", "id str", "punct =", """string '"'""", "punct ;", ]), (r""" this._js = "e.str(\"" + this.value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\")"; """, - ["keyword this", "punct .", "id _js", "punct =", r'''string "e.str(\""''', "punct +", "keyword this", "punct .", - "id value", "punct .", "id replace", "punct (", r"regex /\\/g", "punct ,", r'string "\\\\"', "punct )", + ["keyword this", "punct .", "id _js", "punct =", r'''string "e.str(\""''', "punct +", "keyword this", + "punct .", "id value", "punct .", "id replace", "punct (", r"regex /\\/g", "punct ,", r'string "\\\\"', + "punct )", "punct .", "id replace", "punct (", r'regex /"/g', "punct ,", r'string "\\\""', "punct )", "punct +", r'string "\")"', "punct ;"]), ] diff --git a/tests/utils_tests/test_lorem_ipsum.py b/tests/utils_tests/test_lorem_ipsum.py index 9d0a2d6b2a..9b160cd2fb 100644 --- a/tests/utils_tests/test_lorem_ipsum.py +++ b/tests/utils_tests/test_lorem_ipsum.py @@ -12,5 +12,15 @@ class WebdesignTest(unittest.TestCase): self.assertEqual(words(7), 'lorem ipsum dolor sit amet consectetur adipisicing') def test_paragraphs(self): - self.assertEqual(paragraphs(1), - ['Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.']) + self.assertEqual( + paragraphs(1), [ + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, ' + 'sed do eiusmod tempor incididunt ut labore et dolore magna ' + 'aliqua. Ut enim ad minim veniam, quis nostrud exercitation ' + 'ullamco laboris nisi ut aliquip ex ea commodo consequat. ' + 'Duis aute irure dolor in reprehenderit in voluptate velit ' + 'esse cillum dolore eu fugiat nulla pariatur. Excepteur sint ' + 'occaecat cupidatat non proident, sunt in culpa qui officia ' + 'deserunt mollit anim id est laborum.' + ] + ) diff --git a/tests/utils_tests/test_timezone.py b/tests/utils_tests/test_timezone.py index 2bd87cc932..87df6b92eb 100644 --- a/tests/utils_tests/test_timezone.py +++ b/tests/utils_tests/test_timezone.py @@ -153,7 +153,9 @@ class TimezoneTests(unittest.TestCase): timezone.make_naive(CET.localize(datetime.datetime(2011, 9, 1, 12, 20, 30)), CET), datetime.datetime(2011, 9, 1, 12, 20, 30)) self.assertEqual( - timezone.make_naive(pytz.timezone("Asia/Bangkok").localize(datetime.datetime(2011, 9, 1, 17, 20, 30)), CET), + timezone.make_naive( + pytz.timezone("Asia/Bangkok").localize(datetime.datetime(2011, 9, 1, 17, 20, 30)), CET + ), datetime.datetime(2011, 9, 1, 12, 20, 30)) with self.assertRaises(ValueError): timezone.make_naive(datetime.datetime(2011, 9, 1, 12, 20, 30), CET) diff --git a/tests/view_tests/urls.py b/tests/view_tests/urls.py index e8f2855c98..34028727aa 100644 --- a/tests/view_tests/urls.py +++ b/tests/view_tests/urls.py @@ -97,6 +97,10 @@ urlpatterns += i18n_patterns( urlpatterns += [ url(r'view_exception/(?P[0-9]+)/$', views.view_exception, name='view_exception'), url(r'template_exception/(?P[0-9]+)/$', views.template_exception, name='template_exception'), - url(r'^raises_template_does_not_exist/(?P.+)$', views.raises_template_does_not_exist, name='raises_template_does_not_exist'), + url( + r'^raises_template_does_not_exist/(?P.+)$', + views.raises_template_does_not_exist, + name='raises_template_does_not_exist' + ), url(r'^render_no_template/$', views.render_no_template, name='render_no_template'), ]