hash
stringlengths
64
64
content
stringlengths
0
1.51M
59e7bb9ddeedb947486f846672b7757ac04e11a57adcbe2cb2c4a82d92a8b22e
""" This encapsulates the logic for displaying filters in the Django admin. Filters are specified in models with the "list_filter" option. Each filter subclass knows how to display a filter for a field that passes a certain test -- e.g. being a DateField or ForeignKey. """ import datetime from django.contrib.admin.exceptions import NotRegistered from django.contrib.admin.options import IncorrectLookupParameters from django.contrib.admin.utils import ( build_q_object_from_lookup_parameters, get_last_value_from_parameters, get_model_from_relation, prepare_lookup_value, reverse_field_path, ) from django.core.exceptions import ImproperlyConfigured, ValidationError from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ class ListFilter: title = None # Human-readable title to appear in the right sidebar. template = "admin/filter.html" def __init__(self, request, params, model, model_admin): self.request = request # This dictionary will eventually contain the request's query string # parameters actually used by this filter. self.used_parameters = {} if self.title is None: raise ImproperlyConfigured( "The list filter '%s' does not specify a 'title'." % self.__class__.__name__ ) def has_output(self): """ Return True if some choices would be output for this filter. """ raise NotImplementedError( "subclasses of ListFilter must provide a has_output() method" ) def choices(self, changelist): """ Return choices ready to be output in the template. `changelist` is the ChangeList to be displayed. """ raise NotImplementedError( "subclasses of ListFilter must provide a choices() method" ) def queryset(self, request, queryset): """ Return the filtered queryset. """ raise NotImplementedError( "subclasses of ListFilter must provide a queryset() method" ) def expected_parameters(self): """ Return the list of parameter names that are expected from the request's query string and that will be used by this filter. """ raise NotImplementedError( "subclasses of ListFilter must provide an expected_parameters() method" ) class FacetsMixin: def get_facet_counts(self, pk_attname, filtered_qs): raise NotImplementedError( "subclasses of FacetsMixin must provide a get_facet_counts() method." ) def get_facet_queryset(self, changelist): filtered_qs = changelist.get_queryset( self.request, exclude_parameters=self.expected_parameters() ) return filtered_qs.aggregate( **self.get_facet_counts(changelist.pk_attname, filtered_qs) ) class SimpleListFilter(FacetsMixin, ListFilter): # The parameter that should be used in the query string for that filter. parameter_name = None def __init__(self, request, params, model, model_admin): super().__init__(request, params, model, model_admin) if self.parameter_name is None: raise ImproperlyConfigured( "The list filter '%s' does not specify a 'parameter_name'." % self.__class__.__name__ ) if self.parameter_name in params: value = params.pop(self.parameter_name) self.used_parameters[self.parameter_name] = value[-1] lookup_choices = self.lookups(request, model_admin) if lookup_choices is None: lookup_choices = () self.lookup_choices = list(lookup_choices) def has_output(self): return len(self.lookup_choices) > 0 def value(self): """ Return the value (in string format) provided in the request's query string for this filter, if any, or None if the value wasn't provided. """ return self.used_parameters.get(self.parameter_name) def lookups(self, request, model_admin): """ Must be overridden to return a list of tuples (value, verbose value) """ raise NotImplementedError( "The SimpleListFilter.lookups() method must be overridden to " "return a list of tuples (value, verbose value)." ) def expected_parameters(self): return [self.parameter_name] def get_facet_counts(self, pk_attname, filtered_qs): original_value = self.used_parameters.get(self.parameter_name) counts = {} for i, choice in enumerate(self.lookup_choices): self.used_parameters[self.parameter_name] = choice[0] lookup_qs = self.queryset(self.request, filtered_qs) if lookup_qs is not None: counts[f"{i}__c"] = models.Count( pk_attname, filter=lookup_qs.query.where, ) self.used_parameters[self.parameter_name] = original_value return counts def choices(self, changelist): add_facets = changelist.add_facets facet_counts = self.get_facet_queryset(changelist) if add_facets else None yield { "selected": self.value() is None, "query_string": changelist.get_query_string(remove=[self.parameter_name]), "display": _("All"), } for i, (lookup, title) in enumerate(self.lookup_choices): if add_facets: if (count := facet_counts.get(f"{i}__c", -1)) != -1: title = f"{title} ({count})" else: title = f"{title} (-)" yield { "selected": self.value() == str(lookup), "query_string": changelist.get_query_string( {self.parameter_name: lookup} ), "display": title, } class FieldListFilter(FacetsMixin, ListFilter): _field_list_filters = [] _take_priority_index = 0 list_separator = "," def __init__(self, field, request, params, model, model_admin, field_path): self.field = field self.field_path = field_path self.title = getattr(field, "verbose_name", field_path) super().__init__(request, params, model, model_admin) for p in self.expected_parameters(): if p in params: value = params.pop(p) self.used_parameters[p] = prepare_lookup_value( p, value, self.list_separator ) def has_output(self): return True def queryset(self, request, queryset): try: q_object = build_q_object_from_lookup_parameters(self.used_parameters) return queryset.filter(q_object) except (ValueError, ValidationError) as e: # Fields may raise a ValueError or ValidationError when converting # the parameters to the correct type. raise IncorrectLookupParameters(e) @classmethod def register(cls, test, list_filter_class, take_priority=False): if take_priority: # This is to allow overriding the default filters for certain types # of fields with some custom filters. The first found in the list # is used in priority. cls._field_list_filters.insert( cls._take_priority_index, (test, list_filter_class) ) cls._take_priority_index += 1 else: cls._field_list_filters.append((test, list_filter_class)) @classmethod def create(cls, field, request, params, model, model_admin, field_path): for test, list_filter_class in cls._field_list_filters: if test(field): return list_filter_class( field, request, params, model, model_admin, field_path=field_path ) class RelatedFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): other_model = get_model_from_relation(field) self.lookup_kwarg = "%s__%s__exact" % (field_path, field.target_field.name) self.lookup_kwarg_isnull = "%s__isnull" % field_path self.lookup_val = params.get(self.lookup_kwarg) self.lookup_val_isnull = get_last_value_from_parameters( params, self.lookup_kwarg_isnull ) super().__init__(field, request, params, model, model_admin, field_path) self.lookup_choices = self.field_choices(field, request, model_admin) if hasattr(field, "verbose_name"): self.lookup_title = field.verbose_name else: self.lookup_title = other_model._meta.verbose_name self.title = self.lookup_title self.empty_value_display = model_admin.get_empty_value_display() @property def include_empty_choice(self): """ Return True if a "(None)" choice should be included, which filters out everything except empty relationships. """ return self.field.null or (self.field.is_relation and self.field.many_to_many) def has_output(self): if self.include_empty_choice: extra = 1 else: extra = 0 return len(self.lookup_choices) + extra > 1 def expected_parameters(self): return [self.lookup_kwarg, self.lookup_kwarg_isnull] def field_admin_ordering(self, field, request, model_admin): """ Return the model admin's ordering for related field, if provided. """ try: related_admin = model_admin.admin_site.get_model_admin( field.remote_field.model ) except NotRegistered: return () else: return related_admin.get_ordering(request) def field_choices(self, field, request, model_admin): ordering = self.field_admin_ordering(field, request, model_admin) return field.get_choices(include_blank=False, ordering=ordering) def get_facet_counts(self, pk_attname, filtered_qs): counts = { f"{pk_val}__c": models.Count( pk_attname, filter=models.Q(**{self.lookup_kwarg: pk_val}) ) for pk_val, _ in self.lookup_choices } if self.include_empty_choice: counts["__c"] = models.Count( pk_attname, filter=models.Q(**{self.lookup_kwarg_isnull: True}) ) return counts def choices(self, changelist): add_facets = changelist.add_facets facet_counts = self.get_facet_queryset(changelist) if add_facets else None yield { "selected": self.lookup_val is None and not self.lookup_val_isnull, "query_string": changelist.get_query_string( remove=[self.lookup_kwarg, self.lookup_kwarg_isnull] ), "display": _("All"), } count = None for pk_val, val in self.lookup_choices: if add_facets: count = facet_counts[f"{pk_val}__c"] val = f"{val} ({count})" yield { "selected": self.lookup_val is not None and str(pk_val) in self.lookup_val, "query_string": changelist.get_query_string( {self.lookup_kwarg: pk_val}, [self.lookup_kwarg_isnull] ), "display": val, } empty_title = self.empty_value_display if self.include_empty_choice: if add_facets: count = facet_counts["__c"] empty_title = f"{empty_title} ({count})" yield { "selected": bool(self.lookup_val_isnull), "query_string": changelist.get_query_string( {self.lookup_kwarg_isnull: "True"}, [self.lookup_kwarg] ), "display": empty_title, } FieldListFilter.register(lambda f: f.remote_field, RelatedFieldListFilter) class BooleanFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): self.lookup_kwarg = "%s__exact" % field_path self.lookup_kwarg2 = "%s__isnull" % field_path self.lookup_val = get_last_value_from_parameters(params, self.lookup_kwarg) self.lookup_val2 = get_last_value_from_parameters(params, self.lookup_kwarg2) super().__init__(field, request, params, model, model_admin, field_path) if ( self.used_parameters and self.lookup_kwarg in self.used_parameters and self.used_parameters[self.lookup_kwarg] in ("1", "0") ): self.used_parameters[self.lookup_kwarg] = bool( int(self.used_parameters[self.lookup_kwarg]) ) def expected_parameters(self): return [self.lookup_kwarg, self.lookup_kwarg2] def get_facet_counts(self, pk_attname, filtered_qs): return { "true__c": models.Count( pk_attname, filter=models.Q(**{self.field_path: True}) ), "false__c": models.Count( pk_attname, filter=models.Q(**{self.field_path: False}) ), "null__c": models.Count( pk_attname, filter=models.Q(**{self.lookup_kwarg2: True}) ), } def choices(self, changelist): field_choices = dict(self.field.flatchoices) add_facets = changelist.add_facets facet_counts = self.get_facet_queryset(changelist) if add_facets else None for lookup, title, count_field in ( (None, _("All"), None), ("1", field_choices.get(True, _("Yes")), "true__c"), ("0", field_choices.get(False, _("No")), "false__c"), ): if add_facets: if count_field is not None: count = facet_counts[count_field] title = f"{title} ({count})" yield { "selected": self.lookup_val == lookup and not self.lookup_val2, "query_string": changelist.get_query_string( {self.lookup_kwarg: lookup}, [self.lookup_kwarg2] ), "display": title, } if self.field.null: display = field_choices.get(None, _("Unknown")) if add_facets: count = facet_counts["null__c"] display = f"{display} ({count})" yield { "selected": self.lookup_val2 == "True", "query_string": changelist.get_query_string( {self.lookup_kwarg2: "True"}, [self.lookup_kwarg] ), "display": display, } FieldListFilter.register( lambda f: isinstance(f, models.BooleanField), BooleanFieldListFilter ) class ChoicesFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): self.lookup_kwarg = "%s__exact" % field_path self.lookup_kwarg_isnull = "%s__isnull" % field_path self.lookup_val = params.get(self.lookup_kwarg) self.lookup_val_isnull = get_last_value_from_parameters( params, self.lookup_kwarg_isnull ) super().__init__(field, request, params, model, model_admin, field_path) def expected_parameters(self): return [self.lookup_kwarg, self.lookup_kwarg_isnull] def get_facet_counts(self, pk_attname, filtered_qs): return { f"{i}__c": models.Count( pk_attname, filter=models.Q( (self.lookup_kwarg, value) if value is not None else (self.lookup_kwarg_isnull, True) ), ) for i, (value, _) in enumerate(self.field.flatchoices) } def choices(self, changelist): add_facets = changelist.add_facets facet_counts = self.get_facet_queryset(changelist) if add_facets else None yield { "selected": self.lookup_val is None, "query_string": changelist.get_query_string( remove=[self.lookup_kwarg, self.lookup_kwarg_isnull] ), "display": _("All"), } none_title = "" for i, (lookup, title) in enumerate(self.field.flatchoices): if add_facets: count = facet_counts[f"{i}__c"] title = f"{title} ({count})" if lookup is None: none_title = title continue yield { "selected": self.lookup_val is not None and str(lookup) in self.lookup_val, "query_string": changelist.get_query_string( {self.lookup_kwarg: lookup}, [self.lookup_kwarg_isnull] ), "display": title, } if none_title: yield { "selected": bool(self.lookup_val_isnull), "query_string": changelist.get_query_string( {self.lookup_kwarg_isnull: "True"}, [self.lookup_kwarg] ), "display": none_title, } FieldListFilter.register(lambda f: bool(f.choices), ChoicesFieldListFilter) class DateFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): self.field_generic = "%s__" % field_path self.date_params = { k: v[-1] for k, v in params.items() if k.startswith(self.field_generic) } now = timezone.now() # When time zone support is enabled, convert "now" to the user's time # zone so Django's definition of "Today" matches what the user expects. if timezone.is_aware(now): now = timezone.localtime(now) if isinstance(field, models.DateTimeField): today = now.replace(hour=0, minute=0, second=0, microsecond=0) else: # field is a models.DateField today = now.date() tomorrow = today + datetime.timedelta(days=1) if today.month == 12: next_month = today.replace(year=today.year + 1, month=1, day=1) else: next_month = today.replace(month=today.month + 1, day=1) next_year = today.replace(year=today.year + 1, month=1, day=1) self.lookup_kwarg_since = "%s__gte" % field_path self.lookup_kwarg_until = "%s__lt" % field_path self.links = ( (_("Any date"), {}), ( _("Today"), { self.lookup_kwarg_since: today, self.lookup_kwarg_until: tomorrow, }, ), ( _("Past 7 days"), { self.lookup_kwarg_since: today - datetime.timedelta(days=7), self.lookup_kwarg_until: tomorrow, }, ), ( _("This month"), { self.lookup_kwarg_since: today.replace(day=1), self.lookup_kwarg_until: next_month, }, ), ( _("This year"), { self.lookup_kwarg_since: today.replace(month=1, day=1), self.lookup_kwarg_until: next_year, }, ), ) if field.null: self.lookup_kwarg_isnull = "%s__isnull" % field_path self.links += ( (_("No date"), {self.field_generic + "isnull": True}), (_("Has date"), {self.field_generic + "isnull": False}), ) super().__init__(field, request, params, model, model_admin, field_path) def expected_parameters(self): params = [self.lookup_kwarg_since, self.lookup_kwarg_until] if self.field.null: params.append(self.lookup_kwarg_isnull) return params def get_facet_counts(self, pk_attname, filtered_qs): return { f"{i}__c": models.Count(pk_attname, filter=models.Q(**param_dict)) for i, (_, param_dict) in enumerate(self.links) } def choices(self, changelist): add_facets = changelist.add_facets facet_counts = self.get_facet_queryset(changelist) if add_facets else None for i, (title, param_dict) in enumerate(self.links): param_dict_str = {key: str(value) for key, value in param_dict.items()} if add_facets: count = facet_counts[f"{i}__c"] title = f"{title} ({count})" yield { "selected": self.date_params == param_dict_str, "query_string": changelist.get_query_string( param_dict_str, [self.field_generic] ), "display": title, } FieldListFilter.register(lambda f: isinstance(f, models.DateField), DateFieldListFilter) # This should be registered last, because it's a last resort. For example, # if a field is eligible to use the BooleanFieldListFilter, that'd be much # more appropriate, and the AllValuesFieldListFilter won't get used for it. class AllValuesFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): self.lookup_kwarg = field_path self.lookup_kwarg_isnull = "%s__isnull" % field_path self.lookup_val = params.get(self.lookup_kwarg) self.lookup_val_isnull = get_last_value_from_parameters( params, self.lookup_kwarg_isnull ) self.empty_value_display = model_admin.get_empty_value_display() parent_model, reverse_path = reverse_field_path(model, field_path) # Obey parent ModelAdmin queryset when deciding which options to show if model == parent_model: queryset = model_admin.get_queryset(request) else: queryset = parent_model._default_manager.all() self.lookup_choices = ( queryset.distinct().order_by(field.name).values_list(field.name, flat=True) ) super().__init__(field, request, params, model, model_admin, field_path) def expected_parameters(self): return [self.lookup_kwarg, self.lookup_kwarg_isnull] def get_facet_counts(self, pk_attname, filtered_qs): return { f"{i}__c": models.Count( pk_attname, filter=models.Q( (self.lookup_kwarg, value) if value is not None else (self.lookup_kwarg_isnull, True) ), ) for i, value in enumerate(self.lookup_choices) } def choices(self, changelist): add_facets = changelist.add_facets facet_counts = self.get_facet_queryset(changelist) if add_facets else None yield { "selected": self.lookup_val is None and self.lookup_val_isnull is None, "query_string": changelist.get_query_string( remove=[self.lookup_kwarg, self.lookup_kwarg_isnull] ), "display": _("All"), } include_none = False count = None empty_title = self.empty_value_display for i, val in enumerate(self.lookup_choices): if add_facets: count = facet_counts[f"{i}__c"] if val is None: include_none = True empty_title = f"{empty_title} ({count})" if add_facets else empty_title continue val = str(val) yield { "selected": self.lookup_val is not None and val in self.lookup_val, "query_string": changelist.get_query_string( {self.lookup_kwarg: val}, [self.lookup_kwarg_isnull] ), "display": f"{val} ({count})" if add_facets else val, } if include_none: yield { "selected": bool(self.lookup_val_isnull), "query_string": changelist.get_query_string( {self.lookup_kwarg_isnull: "True"}, [self.lookup_kwarg] ), "display": empty_title, } FieldListFilter.register(lambda f: True, AllValuesFieldListFilter) class RelatedOnlyFieldListFilter(RelatedFieldListFilter): def field_choices(self, field, request, model_admin): pk_qs = ( model_admin.get_queryset(request) .distinct() .values_list("%s__pk" % self.field_path, flat=True) ) ordering = self.field_admin_ordering(field, request, model_admin) return field.get_choices( include_blank=False, limit_choices_to={"pk__in": pk_qs}, ordering=ordering ) class EmptyFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): if not field.empty_strings_allowed and not field.null: raise ImproperlyConfigured( "The list filter '%s' cannot be used with field '%s' which " "doesn't allow empty strings and nulls." % ( self.__class__.__name__, field.name, ) ) self.lookup_kwarg = "%s__isempty" % field_path self.lookup_val = get_last_value_from_parameters(params, self.lookup_kwarg) super().__init__(field, request, params, model, model_admin, field_path) def get_lookup_condition(self): lookup_conditions = [] if self.field.empty_strings_allowed: lookup_conditions.append((self.field_path, "")) if self.field.null: lookup_conditions.append((f"{self.field_path}__isnull", True)) return models.Q.create(lookup_conditions, connector=models.Q.OR) def queryset(self, request, queryset): if self.lookup_kwarg not in self.used_parameters: return queryset if self.lookup_val not in ("0", "1"): raise IncorrectLookupParameters lookup_condition = self.get_lookup_condition() if self.lookup_val == "1": return queryset.filter(lookup_condition) return queryset.exclude(lookup_condition) def expected_parameters(self): return [self.lookup_kwarg] def get_facet_counts(self, pk_attname, filtered_qs): lookup_condition = self.get_lookup_condition() return { "empty__c": models.Count(pk_attname, filter=lookup_condition), "not_empty__c": models.Count(pk_attname, filter=~lookup_condition), } def choices(self, changelist): add_facets = changelist.add_facets facet_counts = self.get_facet_queryset(changelist) if add_facets else None for lookup, title, count_field in ( (None, _("All"), None), ("1", _("Empty"), "empty__c"), ("0", _("Not empty"), "not_empty__c"), ): if add_facets: if count_field is not None: count = facet_counts[count_field] title = f"{title} ({count})" yield { "selected": self.lookup_val == lookup, "query_string": changelist.get_query_string( {self.lookup_kwarg: lookup} ), "display": title, }
3e30bc75bdb9ce1620c0b4bfe29aba3c0a530ff6119f89ae207d00fd537b9028
from django.apps import apps from django.contrib.admin.exceptions import NotRegistered from django.core.exceptions import FieldDoesNotExist, PermissionDenied from django.http import Http404, JsonResponse from django.views.generic.list import BaseListView class AutocompleteJsonView(BaseListView): """Handle AutocompleteWidget's AJAX requests for data.""" paginate_by = 20 admin_site = None def get(self, request, *args, **kwargs): """ Return a JsonResponse with search results as defined in serialize_result(), by default: { results: [{id: "123" text: "foo"}], pagination: {more: true} } """ ( self.term, self.model_admin, self.source_field, to_field_name, ) = self.process_request(request) if not self.has_perm(request): raise PermissionDenied self.object_list = self.get_queryset() context = self.get_context_data() return JsonResponse( { "results": [ self.serialize_result(obj, to_field_name) for obj in context["object_list"] ], "pagination": {"more": context["page_obj"].has_next()}, } ) def serialize_result(self, obj, to_field_name): """ Convert the provided model object to a dictionary that is added to the results list. """ return {"id": str(getattr(obj, to_field_name)), "text": str(obj)} def get_paginator(self, *args, **kwargs): """Use the ModelAdmin's paginator.""" return self.model_admin.get_paginator(self.request, *args, **kwargs) def get_queryset(self): """Return queryset based on ModelAdmin.get_search_results().""" qs = self.model_admin.get_queryset(self.request) qs = qs.complex_filter(self.source_field.get_limit_choices_to()) qs, search_use_distinct = self.model_admin.get_search_results( self.request, qs, self.term ) if search_use_distinct: qs = qs.distinct() return qs def process_request(self, request): """ Validate request integrity, extract and return request parameters. Since the subsequent view permission check requires the target model admin, which is determined here, raise PermissionDenied if the requested app, model or field are malformed. Raise Http404 if the target model admin is not configured properly with search_fields. """ term = request.GET.get("term", "") try: app_label = request.GET["app_label"] model_name = request.GET["model_name"] field_name = request.GET["field_name"] except KeyError as e: raise PermissionDenied from e # Retrieve objects from parameters. try: source_model = apps.get_model(app_label, model_name) except LookupError as e: raise PermissionDenied from e try: source_field = source_model._meta.get_field(field_name) except FieldDoesNotExist as e: raise PermissionDenied from e try: remote_model = source_field.remote_field.model except AttributeError as e: raise PermissionDenied from e try: model_admin = self.admin_site.get_model_admin(remote_model) except NotRegistered as e: raise PermissionDenied from e # Validate suitability of objects. if not model_admin.get_search_fields(request): raise Http404( "%s must have search_fields for the autocomplete_view." % type(model_admin).__qualname__ ) to_field_name = getattr( source_field.remote_field, "field_name", remote_model._meta.pk.attname ) to_field_name = remote_model._meta.get_field(to_field_name).attname if not model_admin.to_field_allowed(request, to_field_name): raise PermissionDenied return term, model_admin, source_field, to_field_name def has_perm(self, request, obj=None): """Check if user has permission to access the related model.""" return self.model_admin.has_view_permission(request, obj=obj)
8c07a5d393669ae81f5c292fdb7a678fa9bb526e231d344d724112493deebe13
from django.db import DatabaseError from django.db.backends.sqlite3.schema import DatabaseSchemaEditor class SpatialiteSchemaEditor(DatabaseSchemaEditor): sql_add_geometry_column = ( "SELECT AddGeometryColumn(%(table)s, %(column)s, %(srid)s, " "%(geom_type)s, %(dim)s, %(null)s)" ) sql_add_spatial_index = "SELECT CreateSpatialIndex(%(table)s, %(column)s)" sql_drop_spatial_index = "DROP TABLE idx_%(table)s_%(column)s" sql_recover_geometry_metadata = ( "SELECT RecoverGeometryColumn(%(table)s, %(column)s, %(srid)s, " "%(geom_type)s, %(dim)s)" ) sql_remove_geometry_metadata = "SELECT DiscardGeometryColumn(%(table)s, %(column)s)" sql_discard_geometry_columns = ( "DELETE FROM %(geom_table)s WHERE f_table_name = %(table)s" ) sql_update_geometry_columns = ( "UPDATE %(geom_table)s SET f_table_name = %(new_table)s " "WHERE f_table_name = %(old_table)s" ) geometry_tables = [ "geometry_columns", "geometry_columns_auth", "geometry_columns_time", "geometry_columns_statistics", ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.geometry_sql = [] def geo_quote_name(self, name): return self.connection.ops.geo_quote_name(name) def column_sql(self, model, field, include_default=False): from django.contrib.gis.db.models import GeometryField if not isinstance(field, GeometryField): return super().column_sql(model, field, include_default) # Geometry columns are created by the `AddGeometryColumn` function self.geometry_sql.append( self.sql_add_geometry_column % { "table": self.geo_quote_name(model._meta.db_table), "column": self.geo_quote_name(field.column), "srid": field.srid, "geom_type": self.geo_quote_name(field.geom_type), "dim": field.dim, "null": int(not field.null), } ) if field.spatial_index: self.geometry_sql.append( self.sql_add_spatial_index % { "table": self.quote_name(model._meta.db_table), "column": self.quote_name(field.column), } ) return None, None def remove_geometry_metadata(self, model, field): self.execute( self.sql_remove_geometry_metadata % { "table": self.quote_name(model._meta.db_table), "column": self.quote_name(field.column), } ) self.execute( self.sql_drop_spatial_index % { "table": model._meta.db_table, "column": field.column, } ) def create_model(self, model): super().create_model(model) # Create geometry columns for sql in self.geometry_sql: self.execute(sql) self.geometry_sql = [] def delete_model(self, model, **kwargs): from django.contrib.gis.db.models import GeometryField # Drop spatial metadata (dropping the table does not automatically remove them) for field in model._meta.local_fields: if isinstance(field, GeometryField): self.remove_geometry_metadata(model, field) # Make sure all geom stuff is gone for geom_table in self.geometry_tables: try: self.execute( self.sql_discard_geometry_columns % { "geom_table": geom_table, "table": self.quote_name(model._meta.db_table), } ) except DatabaseError: pass super().delete_model(model, **kwargs) def add_field(self, model, field): from django.contrib.gis.db.models import GeometryField if isinstance(field, GeometryField): # Populate self.geometry_sql self.column_sql(model, field) for sql in self.geometry_sql: self.execute(sql) self.geometry_sql = [] else: super().add_field(model, field) def remove_field(self, model, field): from django.contrib.gis.db.models import GeometryField # NOTE: If the field is a geometry field, the table is just recreated, # the parent's remove_field can't be used cause it will skip the # recreation if the field does not have a database type. Geometry fields # do not have a db type cause they are added and removed via stored # procedures. if isinstance(field, GeometryField): self._remake_table(model, delete_field=field) else: super().remove_field(model, field) def alter_db_table( self, model, old_db_table, new_db_table, disable_constraints=True ): from django.contrib.gis.db.models import GeometryField if old_db_table == new_db_table or ( self.connection.features.ignores_table_name_case and old_db_table.lower() == new_db_table.lower() ): return # Remove geometry-ness from temp table for field in model._meta.local_fields: if isinstance(field, GeometryField): self.execute( self.sql_remove_geometry_metadata % { "table": self.quote_name(old_db_table), "column": self.quote_name(field.column), } ) # Alter table super().alter_db_table(model, old_db_table, new_db_table, disable_constraints) # Repoint any straggler names for geom_table in self.geometry_tables: try: self.execute( self.sql_update_geometry_columns % { "geom_table": geom_table, "old_table": self.quote_name(old_db_table), "new_table": self.quote_name(new_db_table), } ) except DatabaseError: pass # Re-add geometry-ness and rename spatial index tables for field in model._meta.local_fields: if isinstance(field, GeometryField): self.execute( self.sql_recover_geometry_metadata % { "table": self.geo_quote_name(new_db_table), "column": self.geo_quote_name(field.column), "srid": field.srid, "geom_type": self.geo_quote_name(field.geom_type), "dim": field.dim, } ) if getattr(field, "spatial_index", False): self.execute( self.sql_rename_table % { "old_table": self.quote_name( "idx_%s_%s" % (old_db_table, field.column) ), "new_table": self.quote_name( "idx_%s_%s" % (new_db_table, field.column) ), } )
8a42d2880cd26cb5b7243b9844f6341f9f00e36fb4c515dbfa04cb63cbdc1be4
import threading from ctypes import POINTER, Structure, byref, c_byte, c_char_p, c_int, c_size_t from django.contrib.gis.geos.base import GEOSBase from django.contrib.gis.geos.libgeos import ( GEOM_PTR, GEOSFuncFactory, geos_version_tuple, ) from django.contrib.gis.geos.prototypes.errcheck import ( check_geom, check_sized_string, check_string, ) from django.contrib.gis.geos.prototypes.geom import c_uchar_p, geos_char_p from django.utils.encoding import force_bytes # ### The WKB/WKT Reader/Writer structures and pointers ### class WKTReader_st(Structure): pass class WKTWriter_st(Structure): pass class WKBReader_st(Structure): pass class WKBWriter_st(Structure): pass WKT_READ_PTR = POINTER(WKTReader_st) WKT_WRITE_PTR = POINTER(WKTWriter_st) WKB_READ_PTR = POINTER(WKBReader_st) WKB_WRITE_PTR = POINTER(WKBReader_st) # WKTReader routines wkt_reader_create = GEOSFuncFactory("GEOSWKTReader_create", restype=WKT_READ_PTR) wkt_reader_destroy = GEOSFuncFactory("GEOSWKTReader_destroy", argtypes=[WKT_READ_PTR]) wkt_reader_read = GEOSFuncFactory( "GEOSWKTReader_read", argtypes=[WKT_READ_PTR, c_char_p], restype=GEOM_PTR, errcheck=check_geom, ) # WKTWriter routines wkt_writer_create = GEOSFuncFactory("GEOSWKTWriter_create", restype=WKT_WRITE_PTR) wkt_writer_destroy = GEOSFuncFactory("GEOSWKTWriter_destroy", argtypes=[WKT_WRITE_PTR]) wkt_writer_write = GEOSFuncFactory( "GEOSWKTWriter_write", argtypes=[WKT_WRITE_PTR, GEOM_PTR], restype=geos_char_p, errcheck=check_string, ) wkt_writer_get_outdim = GEOSFuncFactory( "GEOSWKTWriter_getOutputDimension", argtypes=[WKT_WRITE_PTR], restype=c_int ) wkt_writer_set_outdim = GEOSFuncFactory( "GEOSWKTWriter_setOutputDimension", argtypes=[WKT_WRITE_PTR, c_int] ) wkt_writer_set_trim = GEOSFuncFactory( "GEOSWKTWriter_setTrim", argtypes=[WKT_WRITE_PTR, c_byte] ) wkt_writer_set_precision = GEOSFuncFactory( "GEOSWKTWriter_setRoundingPrecision", argtypes=[WKT_WRITE_PTR, c_int] ) # WKBReader routines wkb_reader_create = GEOSFuncFactory("GEOSWKBReader_create", restype=WKB_READ_PTR) wkb_reader_destroy = GEOSFuncFactory("GEOSWKBReader_destroy", argtypes=[WKB_READ_PTR]) class WKBReadFunc(GEOSFuncFactory): # Although the function definitions take `const unsigned char *` # as their parameter, we use c_char_p here so the function may # take Python strings directly as parameters. Inside Python there # is not a difference between signed and unsigned characters, so # it is not a problem. argtypes = [WKB_READ_PTR, c_char_p, c_size_t] restype = GEOM_PTR errcheck = staticmethod(check_geom) wkb_reader_read = WKBReadFunc("GEOSWKBReader_read") wkb_reader_read_hex = WKBReadFunc("GEOSWKBReader_readHEX") # WKBWriter routines wkb_writer_create = GEOSFuncFactory("GEOSWKBWriter_create", restype=WKB_WRITE_PTR) wkb_writer_destroy = GEOSFuncFactory("GEOSWKBWriter_destroy", argtypes=[WKB_WRITE_PTR]) # WKB Writing prototypes. class WKBWriteFunc(GEOSFuncFactory): argtypes = [WKB_WRITE_PTR, GEOM_PTR, POINTER(c_size_t)] restype = c_uchar_p errcheck = staticmethod(check_sized_string) wkb_writer_write = WKBWriteFunc("GEOSWKBWriter_write") wkb_writer_write_hex = WKBWriteFunc("GEOSWKBWriter_writeHEX") # WKBWriter property getter/setter prototypes. class WKBWriterGet(GEOSFuncFactory): argtypes = [WKB_WRITE_PTR] restype = c_int class WKBWriterSet(GEOSFuncFactory): argtypes = [WKB_WRITE_PTR, c_int] wkb_writer_get_byteorder = WKBWriterGet("GEOSWKBWriter_getByteOrder") wkb_writer_set_byteorder = WKBWriterSet("GEOSWKBWriter_setByteOrder") wkb_writer_get_outdim = WKBWriterGet("GEOSWKBWriter_getOutputDimension") wkb_writer_set_outdim = WKBWriterSet("GEOSWKBWriter_setOutputDimension") wkb_writer_get_include_srid = WKBWriterGet( "GEOSWKBWriter_getIncludeSRID", restype=c_byte ) wkb_writer_set_include_srid = WKBWriterSet( "GEOSWKBWriter_setIncludeSRID", argtypes=[WKB_WRITE_PTR, c_byte] ) # ### Base I/O Class ### class IOBase(GEOSBase): "Base class for GEOS I/O objects." def __init__(self): # Getting the pointer with the constructor. self.ptr = self._constructor() # Loading the real destructor function at this point as doing it in # __del__ is too late (import error). self.destructor.func # ### Base WKB/WKT Reading and Writing objects ### # Non-public WKB/WKT reader classes for internal use because # their `read` methods return _pointers_ instead of GEOSGeometry # objects. class _WKTReader(IOBase): _constructor = wkt_reader_create ptr_type = WKT_READ_PTR destructor = wkt_reader_destroy def read(self, wkt): if not isinstance(wkt, (bytes, str)): raise TypeError return wkt_reader_read(self.ptr, force_bytes(wkt)) class _WKBReader(IOBase): _constructor = wkb_reader_create ptr_type = WKB_READ_PTR destructor = wkb_reader_destroy def read(self, wkb): "Return a _pointer_ to C GEOS Geometry object from the given WKB." if isinstance(wkb, memoryview): wkb_s = bytes(wkb) return wkb_reader_read(self.ptr, wkb_s, len(wkb_s)) elif isinstance(wkb, bytes): return wkb_reader_read_hex(self.ptr, wkb, len(wkb)) elif isinstance(wkb, str): wkb_s = wkb.encode() return wkb_reader_read_hex(self.ptr, wkb_s, len(wkb_s)) else: raise TypeError # ### WKB/WKT Writer Classes ### class WKTWriter(IOBase): _constructor = wkt_writer_create ptr_type = WKT_WRITE_PTR destructor = wkt_writer_destroy _trim = False _precision = None def __init__(self, dim=2, trim=False, precision=None): super().__init__() self.trim = trim if precision is not None: self.precision = precision self.outdim = dim def write(self, geom): "Return the WKT representation of the given geometry." return wkt_writer_write(self.ptr, geom.ptr) @property def outdim(self): return wkt_writer_get_outdim(self.ptr) @outdim.setter def outdim(self, new_dim): if new_dim not in (2, 3): raise ValueError("WKT output dimension must be 2 or 3") wkt_writer_set_outdim(self.ptr, new_dim) @property def trim(self): return self._trim @trim.setter def trim(self, flag): if bool(flag) != self._trim: self._trim = bool(flag) wkt_writer_set_trim(self.ptr, self._trim) @property def precision(self): return self._precision @precision.setter def precision(self, precision): if (not isinstance(precision, int) or precision < 0) and precision is not None: raise AttributeError( "WKT output rounding precision must be non-negative integer or None." ) if precision != self._precision: self._precision = precision wkt_writer_set_precision(self.ptr, -1 if precision is None else precision) class WKBWriter(IOBase): _constructor = wkb_writer_create ptr_type = WKB_WRITE_PTR destructor = wkb_writer_destroy geos_version = geos_version_tuple() def __init__(self, dim=2): super().__init__() self.outdim = dim def _handle_empty_point(self, geom): from django.contrib.gis.geos import Point if isinstance(geom, Point) and geom.empty: if self.srid: # PostGIS uses POINT(NaN NaN) for WKB representation of empty # points. Use it for EWKB as it's a PostGIS specific format. # https://trac.osgeo.org/postgis/ticket/3181 geom = Point(float("NaN"), float("NaN"), srid=geom.srid) else: raise ValueError("Empty point is not representable in WKB.") return geom def write(self, geom): "Return the WKB representation of the given geometry." geom = self._handle_empty_point(geom) wkb = wkb_writer_write(self.ptr, geom.ptr, byref(c_size_t())) return memoryview(wkb) def write_hex(self, geom): "Return the HEXEWKB representation of the given geometry." geom = self._handle_empty_point(geom) wkb = wkb_writer_write_hex(self.ptr, geom.ptr, byref(c_size_t())) return wkb # ### WKBWriter Properties ### # Property for getting/setting the byteorder. def _get_byteorder(self): return wkb_writer_get_byteorder(self.ptr) def _set_byteorder(self, order): if order not in (0, 1): raise ValueError( "Byte order parameter must be 0 (Big Endian) or 1 (Little Endian)." ) wkb_writer_set_byteorder(self.ptr, order) byteorder = property(_get_byteorder, _set_byteorder) # Property for getting/setting the output dimension. @property def outdim(self): return wkb_writer_get_outdim(self.ptr) @outdim.setter def outdim(self, new_dim): if new_dim not in (2, 3): raise ValueError("WKB output dimension must be 2 or 3") wkb_writer_set_outdim(self.ptr, new_dim) # Property for getting/setting the include srid flag. @property def srid(self): return bool(wkb_writer_get_include_srid(self.ptr)) @srid.setter def srid(self, include): wkb_writer_set_include_srid(self.ptr, bool(include)) # `ThreadLocalIO` object holds instances of the WKT and WKB reader/writer # objects that are local to the thread. The `GEOSGeometry` internals # access these instances by calling the module-level functions, defined # below. class ThreadLocalIO(threading.local): wkt_r = None wkt_w = None wkb_r = None wkb_w = None ewkb_w = None thread_context = ThreadLocalIO() # These module-level routines return the I/O object that is local to the # thread. If the I/O object does not exist yet it will be initialized. def wkt_r(): thread_context.wkt_r = thread_context.wkt_r or _WKTReader() return thread_context.wkt_r def wkt_w(dim=2, trim=False, precision=None): if not thread_context.wkt_w: thread_context.wkt_w = WKTWriter(dim=dim, trim=trim, precision=precision) else: thread_context.wkt_w.outdim = dim thread_context.wkt_w.trim = trim thread_context.wkt_w.precision = precision return thread_context.wkt_w def wkb_r(): thread_context.wkb_r = thread_context.wkb_r or _WKBReader() return thread_context.wkb_r def wkb_w(dim=2): if not thread_context.wkb_w: thread_context.wkb_w = WKBWriter(dim=dim) else: thread_context.wkb_w.outdim = dim return thread_context.wkb_w def ewkb_w(dim=2): if not thread_context.ewkb_w: thread_context.ewkb_w = WKBWriter(dim=dim) thread_context.ewkb_w.srid = True else: thread_context.ewkb_w.outdim = dim return thread_context.ewkb_w
49eb1ff6713f099f548a162d29036b1a05cd8c99e6f17c8395c889f56997404e
import datetime import decimal import enum import functools import math import os import pathlib import re import sys import time import uuid import zoneinfo from types import NoneType from unittest import mock import custom_migration_operations.more_operations import custom_migration_operations.operations from django import get_version from django.conf import SettingsReference, settings from django.core.validators import EmailValidator, RegexValidator from django.db import migrations, models from django.db.migrations.serializer import BaseSerializer from django.db.migrations.writer import MigrationWriter, OperationWriter from django.test import SimpleTestCase from django.utils.deconstruct import deconstructible from django.utils.functional import SimpleLazyObject from django.utils.timezone import get_default_timezone, get_fixed_timezone from django.utils.translation import gettext_lazy as _ from .models import FoodManager, FoodQuerySet class DeconstructibleInstances: def deconstruct(self): return ("DeconstructibleInstances", [], {}) class Money(decimal.Decimal): def deconstruct(self): return ( "%s.%s" % (self.__class__.__module__, self.__class__.__name__), [str(self)], {}, ) class TestModel1: def upload_to(self): return "/somewhere/dynamic/" thing = models.FileField(upload_to=upload_to) class TextEnum(enum.Enum): A = "a-value" B = "value-b" class TextTranslatedEnum(enum.Enum): A = _("a-value") B = _("value-b") class BinaryEnum(enum.Enum): A = b"a-value" B = b"value-b" class IntEnum(enum.IntEnum): A = 1 B = 2 class IntFlagEnum(enum.IntFlag): A = 1 B = 2 class OperationWriterTests(SimpleTestCase): def test_empty_signature(self): operation = custom_migration_operations.operations.TestOperation() buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.TestOperation(\n),", ) def test_args_signature(self): operation = custom_migration_operations.operations.ArgsOperation(1, 2) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsOperation(\n" " arg1=1,\n" " arg2=2,\n" "),", ) def test_kwargs_signature(self): operation = custom_migration_operations.operations.KwargsOperation(kwarg1=1) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.KwargsOperation(\n" " kwarg1=1,\n" "),", ) def test_args_kwargs_signature(self): operation = custom_migration_operations.operations.ArgsKwargsOperation( 1, 2, kwarg2=4 ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsKwargsOperation(\n" " arg1=1,\n" " arg2=2,\n" " kwarg2=4,\n" "),", ) def test_nested_args_signature(self): operation = custom_migration_operations.operations.ArgsOperation( custom_migration_operations.operations.ArgsOperation(1, 2), custom_migration_operations.operations.KwargsOperation(kwarg1=3, kwarg2=4), ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsOperation(\n" " arg1=custom_migration_operations.operations.ArgsOperation(\n" " arg1=1,\n" " arg2=2,\n" " ),\n" " arg2=custom_migration_operations.operations.KwargsOperation(\n" " kwarg1=3,\n" " kwarg2=4,\n" " ),\n" "),", ) def test_multiline_args_signature(self): operation = custom_migration_operations.operations.ArgsOperation( "test\n arg1", "test\narg2" ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsOperation(\n" " arg1='test\\n arg1',\n" " arg2='test\\narg2',\n" "),", ) def test_expand_args_signature(self): operation = custom_migration_operations.operations.ExpandArgsOperation([1, 2]) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ExpandArgsOperation(\n" " arg=[\n" " 1,\n" " 2,\n" " ],\n" "),", ) def test_nested_operation_expand_args_signature(self): operation = custom_migration_operations.operations.ExpandArgsOperation( arg=[ custom_migration_operations.operations.KwargsOperation( kwarg1=1, kwarg2=2, ), ] ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ExpandArgsOperation(\n" " arg=[\n" " custom_migration_operations.operations.KwargsOperation(\n" " kwarg1=1,\n" " kwarg2=2,\n" " ),\n" " ],\n" "),", ) class WriterTests(SimpleTestCase): """ Tests the migration writer (makes migration files from Migration instances) """ class NestedEnum(enum.IntEnum): A = 1 B = 2 class NestedChoices(models.TextChoices): X = "X", "X value" Y = "Y", "Y value" @classmethod def method(cls): return cls.X def safe_exec(self, string, value=None): d = {} try: exec(string, globals(), d) except Exception as e: if value: self.fail( "Could not exec %r (from value %r): %s" % (string.strip(), value, e) ) else: self.fail("Could not exec %r: %s" % (string.strip(), e)) return d def serialize_round_trip(self, value): string, imports = MigrationWriter.serialize(value) return self.safe_exec( "%s\ntest_value_result = %s" % ("\n".join(imports), string), value )["test_value_result"] def assertSerializedEqual(self, value): self.assertEqual(self.serialize_round_trip(value), value) def assertSerializedResultEqual(self, value, target): self.assertEqual(MigrationWriter.serialize(value), target) def assertSerializedFieldEqual(self, value): new_value = self.serialize_round_trip(value) self.assertEqual(value.__class__, new_value.__class__) self.assertEqual(value.max_length, new_value.max_length) self.assertEqual(value.null, new_value.null) self.assertEqual(value.unique, new_value.unique) def test_serialize_numbers(self): self.assertSerializedEqual(1) self.assertSerializedEqual(1.2) self.assertTrue(math.isinf(self.serialize_round_trip(float("inf")))) self.assertTrue(math.isinf(self.serialize_round_trip(float("-inf")))) self.assertTrue(math.isnan(self.serialize_round_trip(float("nan")))) self.assertSerializedEqual(decimal.Decimal("1.3")) self.assertSerializedResultEqual( decimal.Decimal("1.3"), ("Decimal('1.3')", {"from decimal import Decimal"}) ) self.assertSerializedEqual(Money("1.3")) self.assertSerializedResultEqual( Money("1.3"), ("migrations.test_writer.Money('1.3')", {"import migrations.test_writer"}), ) def test_serialize_constants(self): self.assertSerializedEqual(None) self.assertSerializedEqual(True) self.assertSerializedEqual(False) def test_serialize_strings(self): self.assertSerializedEqual(b"foobar") string, imports = MigrationWriter.serialize(b"foobar") self.assertEqual(string, "b'foobar'") self.assertSerializedEqual("föobár") string, imports = MigrationWriter.serialize("foobar") self.assertEqual(string, "'foobar'") def test_serialize_multiline_strings(self): self.assertSerializedEqual(b"foo\nbar") string, imports = MigrationWriter.serialize(b"foo\nbar") self.assertEqual(string, "b'foo\\nbar'") self.assertSerializedEqual("föo\nbár") string, imports = MigrationWriter.serialize("foo\nbar") self.assertEqual(string, "'foo\\nbar'") def test_serialize_collections(self): self.assertSerializedEqual({1: 2}) self.assertSerializedEqual(["a", 2, True, None]) self.assertSerializedEqual({2, 3, "eighty"}) self.assertSerializedEqual({"lalalala": ["yeah", "no", "maybe"]}) self.assertSerializedEqual(_("Hello")) def test_serialize_builtin_types(self): self.assertSerializedEqual([list, tuple, dict, set, frozenset]) self.assertSerializedResultEqual( [list, tuple, dict, set, frozenset], ("[list, tuple, dict, set, frozenset]", set()), ) def test_serialize_lazy_objects(self): pattern = re.compile(r"^foo$") lazy_pattern = SimpleLazyObject(lambda: pattern) self.assertEqual(self.serialize_round_trip(lazy_pattern), pattern) def test_serialize_enums(self): self.assertSerializedResultEqual( TextEnum.A, ("migrations.test_writer.TextEnum['A']", {"import migrations.test_writer"}), ) self.assertSerializedResultEqual( TextTranslatedEnum.A, ( "migrations.test_writer.TextTranslatedEnum['A']", {"import migrations.test_writer"}, ), ) self.assertSerializedResultEqual( BinaryEnum.A, ( "migrations.test_writer.BinaryEnum['A']", {"import migrations.test_writer"}, ), ) self.assertSerializedResultEqual( IntEnum.B, ("migrations.test_writer.IntEnum['B']", {"import migrations.test_writer"}), ) self.assertSerializedResultEqual( self.NestedEnum.A, ( "migrations.test_writer.WriterTests.NestedEnum['A']", {"import migrations.test_writer"}, ), ) self.assertSerializedEqual(self.NestedEnum.A) field = models.CharField( default=TextEnum.B, choices=[(m.value, m) for m in TextEnum] ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.CharField(choices=[" "('a-value', migrations.test_writer.TextEnum['A']), " "('value-b', migrations.test_writer.TextEnum['B'])], " "default=migrations.test_writer.TextEnum['B'])", ) field = models.CharField( default=TextTranslatedEnum.A, choices=[(m.value, m) for m in TextTranslatedEnum], ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.CharField(choices=[" "('a-value', migrations.test_writer.TextTranslatedEnum['A']), " "('value-b', migrations.test_writer.TextTranslatedEnum['B'])], " "default=migrations.test_writer.TextTranslatedEnum['A'])", ) field = models.CharField( default=BinaryEnum.B, choices=[(m.value, m) for m in BinaryEnum] ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.CharField(choices=[" "(b'a-value', migrations.test_writer.BinaryEnum['A']), " "(b'value-b', migrations.test_writer.BinaryEnum['B'])], " "default=migrations.test_writer.BinaryEnum['B'])", ) field = models.IntegerField( default=IntEnum.A, choices=[(m.value, m) for m in IntEnum] ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.IntegerField(choices=[" "(1, migrations.test_writer.IntEnum['A']), " "(2, migrations.test_writer.IntEnum['B'])], " "default=migrations.test_writer.IntEnum['A'])", ) def test_serialize_enum_flags(self): self.assertSerializedResultEqual( IntFlagEnum.A, ( "migrations.test_writer.IntFlagEnum['A']", {"import migrations.test_writer"}, ), ) self.assertSerializedResultEqual( IntFlagEnum.B, ( "migrations.test_writer.IntFlagEnum['B']", {"import migrations.test_writer"}, ), ) field = models.IntegerField( default=IntFlagEnum.A, choices=[(m.value, m) for m in IntFlagEnum] ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.IntegerField(choices=[" "(1, migrations.test_writer.IntFlagEnum['A']), " "(2, migrations.test_writer.IntFlagEnum['B'])], " "default=migrations.test_writer.IntFlagEnum['A'])", ) self.assertSerializedResultEqual( IntFlagEnum.A | IntFlagEnum.B, ( "migrations.test_writer.IntFlagEnum['A'] | " "migrations.test_writer.IntFlagEnum['B']", {"import migrations.test_writer"}, ), ) def test_serialize_choices(self): class TextChoices(models.TextChoices): A = "A", "A value" B = "B", "B value" class IntegerChoices(models.IntegerChoices): A = 1, "One" B = 2, "Two" class DateChoices(datetime.date, models.Choices): DATE_1 = 1969, 7, 20, "First date" DATE_2 = 1969, 11, 19, "Second date" self.assertSerializedResultEqual(TextChoices.A, ("'A'", set())) self.assertSerializedResultEqual(IntegerChoices.A, ("1", set())) self.assertSerializedResultEqual( DateChoices.DATE_1, ("datetime.date(1969, 7, 20)", {"import datetime"}), ) field = models.CharField(default=TextChoices.B, choices=TextChoices) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.CharField(choices=[('A', 'A value'), ('B', 'B value')], " "default='B')", ) field = models.IntegerField(default=IntegerChoices.B, choices=IntegerChoices) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.IntegerField(choices=[(1, 'One'), (2, 'Two')], default=2)", ) field = models.DateField(default=DateChoices.DATE_2, choices=DateChoices) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.DateField(choices=[" "(datetime.date(1969, 7, 20), 'First date'), " "(datetime.date(1969, 11, 19), 'Second date')], " "default=datetime.date(1969, 11, 19))", ) def test_serialize_nested_class(self): for nested_cls in [self.NestedEnum, self.NestedChoices]: cls_name = nested_cls.__name__ with self.subTest(cls_name): self.assertSerializedResultEqual( nested_cls, ( "migrations.test_writer.WriterTests.%s" % cls_name, {"import migrations.test_writer"}, ), ) def test_serialize_nested_class_method(self): self.assertSerializedResultEqual( self.NestedChoices.method, ( "migrations.test_writer.WriterTests.NestedChoices.method", {"import migrations.test_writer"}, ), ) def test_serialize_uuid(self): self.assertSerializedEqual(uuid.uuid1()) self.assertSerializedEqual(uuid.uuid4()) uuid_a = uuid.UUID("5c859437-d061-4847-b3f7-e6b78852f8c8") uuid_b = uuid.UUID("c7853ec1-2ea3-4359-b02d-b54e8f1bcee2") self.assertSerializedResultEqual( uuid_a, ("uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8')", {"import uuid"}), ) self.assertSerializedResultEqual( uuid_b, ("uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2')", {"import uuid"}), ) field = models.UUIDField( choices=((uuid_a, "UUID A"), (uuid_b, "UUID B")), default=uuid_a ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.UUIDField(choices=[" "(uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8'), 'UUID A'), " "(uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2'), 'UUID B')], " "default=uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8'))", ) def test_serialize_pathlib(self): # Pure path objects work in all platforms. self.assertSerializedEqual(pathlib.PurePosixPath()) self.assertSerializedEqual(pathlib.PureWindowsPath()) path = pathlib.PurePosixPath("/path/file.txt") expected = ("pathlib.PurePosixPath('/path/file.txt')", {"import pathlib"}) self.assertSerializedResultEqual(path, expected) path = pathlib.PureWindowsPath("A:\\File.txt") expected = ("pathlib.PureWindowsPath('A:/File.txt')", {"import pathlib"}) self.assertSerializedResultEqual(path, expected) # Concrete path objects work on supported platforms. if sys.platform == "win32": self.assertSerializedEqual(pathlib.WindowsPath.cwd()) path = pathlib.WindowsPath("A:\\File.txt") expected = ("pathlib.PureWindowsPath('A:/File.txt')", {"import pathlib"}) self.assertSerializedResultEqual(path, expected) else: self.assertSerializedEqual(pathlib.PosixPath.cwd()) path = pathlib.PosixPath("/path/file.txt") expected = ("pathlib.PurePosixPath('/path/file.txt')", {"import pathlib"}) self.assertSerializedResultEqual(path, expected) field = models.FilePathField(path=pathlib.PurePosixPath("/home/user")) string, imports = MigrationWriter.serialize(field) self.assertEqual( string, "models.FilePathField(path=pathlib.PurePosixPath('/home/user'))", ) self.assertIn("import pathlib", imports) def test_serialize_path_like(self): with os.scandir(os.path.dirname(__file__)) as entries: path_like = list(entries)[0] expected = (repr(path_like.path), {}) self.assertSerializedResultEqual(path_like, expected) field = models.FilePathField(path=path_like) string = MigrationWriter.serialize(field)[0] self.assertEqual(string, "models.FilePathField(path=%r)" % path_like.path) def test_serialize_functions(self): with self.assertRaisesMessage(ValueError, "Cannot serialize function: lambda"): self.assertSerializedEqual(lambda x: 42) self.assertSerializedEqual(models.SET_NULL) string, imports = MigrationWriter.serialize(models.SET(42)) self.assertEqual(string, "models.SET(42)") self.serialize_round_trip(models.SET(42)) def test_serialize_datetime(self): self.assertSerializedEqual(datetime.datetime.now()) self.assertSerializedEqual(datetime.datetime.now) self.assertSerializedEqual(datetime.datetime.today()) self.assertSerializedEqual(datetime.datetime.today) self.assertSerializedEqual(datetime.date.today()) self.assertSerializedEqual(datetime.date.today) self.assertSerializedEqual(datetime.datetime.now().time()) self.assertSerializedEqual( datetime.datetime(2014, 1, 1, 1, 1, tzinfo=get_default_timezone()) ) self.assertSerializedEqual( datetime.datetime(2013, 12, 31, 22, 1, tzinfo=get_fixed_timezone(180)) ) self.assertSerializedResultEqual( datetime.datetime(2014, 1, 1, 1, 1), ("datetime.datetime(2014, 1, 1, 1, 1)", {"import datetime"}), ) self.assertSerializedResultEqual( datetime.datetime(2012, 1, 1, 1, 1, tzinfo=datetime.timezone.utc), ( "datetime.datetime(2012, 1, 1, 1, 1, tzinfo=datetime.timezone.utc)", {"import datetime"}, ), ) self.assertSerializedResultEqual( datetime.datetime( 2012, 1, 1, 2, 1, tzinfo=zoneinfo.ZoneInfo("Europe/Paris") ), ( "datetime.datetime(2012, 1, 1, 1, 1, tzinfo=datetime.timezone.utc)", {"import datetime"}, ), ) def test_serialize_fields(self): self.assertSerializedFieldEqual(models.CharField(max_length=255)) self.assertSerializedResultEqual( models.CharField(max_length=255), ("models.CharField(max_length=255)", {"from django.db import models"}), ) self.assertSerializedFieldEqual(models.TextField(null=True, blank=True)) self.assertSerializedResultEqual( models.TextField(null=True, blank=True), ( "models.TextField(blank=True, null=True)", {"from django.db import models"}, ), ) def test_serialize_settings(self): self.assertSerializedEqual( SettingsReference(settings.AUTH_USER_MODEL, "AUTH_USER_MODEL") ) self.assertSerializedResultEqual( SettingsReference("someapp.model", "AUTH_USER_MODEL"), ("settings.AUTH_USER_MODEL", {"from django.conf import settings"}), ) def test_serialize_iterators(self): self.assertSerializedResultEqual( ((x, x * x) for x in range(3)), ("((0, 0), (1, 1), (2, 4))", set()) ) def test_serialize_compiled_regex(self): """ Make sure compiled regex can be serialized. """ regex = re.compile(r"^\w+$") self.assertSerializedEqual(regex) def test_serialize_class_based_validators(self): """ Ticket #22943: Test serialization of class-based validators, including compiled regexes. """ validator = RegexValidator(message="hello") string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.RegexValidator(message='hello')" ) self.serialize_round_trip(validator) # Test with a compiled regex. validator = RegexValidator(regex=re.compile(r"^\w+$")) string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.RegexValidator(regex=re.compile('^\\\\w+$'))", ) self.serialize_round_trip(validator) # Test a string regex with flag validator = RegexValidator(r"^[0-9]+$", flags=re.S) string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.RegexValidator('^[0-9]+$', " "flags=re.RegexFlag['DOTALL'])", ) self.serialize_round_trip(validator) # Test message and code validator = RegexValidator("^[-a-zA-Z0-9_]+$", "Invalid", "invalid") string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', " "'invalid')", ) self.serialize_round_trip(validator) # Test with a subclass. validator = EmailValidator(message="hello") string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.EmailValidator(message='hello')" ) self.serialize_round_trip(validator) validator = deconstructible(path="migrations.test_writer.EmailValidator")( EmailValidator )(message="hello") string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "migrations.test_writer.EmailValidator(message='hello')" ) validator = deconstructible(path="custom.EmailValidator")(EmailValidator)( message="hello" ) with self.assertRaisesMessage(ImportError, "No module named 'custom'"): MigrationWriter.serialize(validator) validator = deconstructible(path="django.core.validators.EmailValidator2")( EmailValidator )(message="hello") with self.assertRaisesMessage( ValueError, "Could not find object EmailValidator2 in django.core.validators.", ): MigrationWriter.serialize(validator) def test_serialize_complex_func_index(self): index = models.Index( models.Func("rating", function="ABS"), models.Case( models.When(name="special", then=models.Value("X")), default=models.Value("other"), ), models.ExpressionWrapper( models.F("pages"), output_field=models.IntegerField(), ), models.OrderBy(models.F("name").desc()), name="complex_func_index", ) string, imports = MigrationWriter.serialize(index) self.assertEqual( string, "models.Index(models.Func('rating', function='ABS'), " "models.Case(models.When(name='special', then=models.Value('X')), " "default=models.Value('other')), " "models.ExpressionWrapper(" "models.F('pages'), output_field=models.IntegerField()), " "models.OrderBy(models.OrderBy(models.F('name'), descending=True)), " "name='complex_func_index')", ) self.assertEqual(imports, {"from django.db import models"}) def test_serialize_empty_nonempty_tuple(self): """ Ticket #22679: makemigrations generates invalid code for (an empty tuple) default_permissions = () """ empty_tuple = () one_item_tuple = ("a",) many_items_tuple = ("a", "b", "c") self.assertSerializedEqual(empty_tuple) self.assertSerializedEqual(one_item_tuple) self.assertSerializedEqual(many_items_tuple) def test_serialize_range(self): string, imports = MigrationWriter.serialize(range(1, 5)) self.assertEqual(string, "range(1, 5)") self.assertEqual(imports, set()) def test_serialize_builtins(self): string, imports = MigrationWriter.serialize(range) self.assertEqual(string, "range") self.assertEqual(imports, set()) def test_serialize_unbound_method_reference(self): """An unbound method used within a class body can be serialized.""" self.serialize_round_trip(TestModel1.thing) def test_serialize_local_function_reference(self): """A reference in a local scope can't be serialized.""" class TestModel2: def upload_to(self): return "somewhere dynamic" thing = models.FileField(upload_to=upload_to) with self.assertRaisesMessage( ValueError, "Could not find function upload_to in migrations.test_writer" ): self.serialize_round_trip(TestModel2.thing) def test_serialize_managers(self): self.assertSerializedEqual(models.Manager()) self.assertSerializedResultEqual( FoodQuerySet.as_manager(), ( "migrations.models.FoodQuerySet.as_manager()", {"import migrations.models"}, ), ) self.assertSerializedEqual(FoodManager("a", "b")) self.assertSerializedEqual(FoodManager("x", "y", c=3, d=4)) def test_serialize_frozensets(self): self.assertSerializedEqual(frozenset()) self.assertSerializedEqual(frozenset("let it go")) self.assertSerializedResultEqual( frozenset("cba"), ("frozenset(['a', 'b', 'c'])", set()) ) def test_serialize_set(self): self.assertSerializedEqual(set()) self.assertSerializedResultEqual(set(), ("set()", set())) self.assertSerializedEqual({"a"}) self.assertSerializedResultEqual({"a"}, ("{'a'}", set())) self.assertSerializedEqual({"c", "b", "a"}) self.assertSerializedResultEqual({"c", "b", "a"}, ("{'a', 'b', 'c'}", set())) def test_serialize_timedelta(self): self.assertSerializedEqual(datetime.timedelta()) self.assertSerializedEqual(datetime.timedelta(minutes=42)) def test_serialize_functools_partial(self): value = functools.partial(datetime.timedelta, 1, seconds=2) result = self.serialize_round_trip(value) self.assertEqual(result.func, value.func) self.assertEqual(result.args, value.args) self.assertEqual(result.keywords, value.keywords) def test_serialize_functools_partialmethod(self): value = functools.partialmethod(datetime.timedelta, 1, seconds=2) result = self.serialize_round_trip(value) self.assertIsInstance(result, functools.partialmethod) self.assertEqual(result.func, value.func) self.assertEqual(result.args, value.args) self.assertEqual(result.keywords, value.keywords) def test_serialize_type_none(self): self.assertSerializedEqual(NoneType) def test_serialize_type_model(self): self.assertSerializedEqual(models.Model) self.assertSerializedResultEqual( MigrationWriter.serialize(models.Model), ("('models.Model', {'from django.db import models'})", set()), ) def test_simple_migration(self): """ Tests serializing a simple migration. """ fields = { "charfield": models.DateTimeField(default=datetime.datetime.now), "datetimefield": models.DateTimeField(default=datetime.datetime.now), } options = { "verbose_name": "My model", "verbose_name_plural": "My models", } migration = type( "Migration", (migrations.Migration,), { "operations": [ migrations.CreateModel( "MyModel", tuple(fields.items()), options, (models.Model,) ), migrations.CreateModel( "MyModel2", tuple(fields.items()), bases=(models.Model,) ), migrations.CreateModel( name="MyModel3", fields=tuple(fields.items()), options=options, bases=(models.Model,), ), migrations.DeleteModel("MyModel"), migrations.AddField( "OtherModel", "datetimefield", fields["datetimefield"] ), ], "dependencies": [("testapp", "some_other_one")], }, ) writer = MigrationWriter(migration) output = writer.as_string() # We don't test the output formatting - that's too fragile. # Just make sure it runs for now, and that things look alright. result = self.safe_exec(output) self.assertIn("Migration", result) def test_migration_path(self): test_apps = [ "migrations.migrations_test_apps.normal", "migrations.migrations_test_apps.with_package_model", "migrations.migrations_test_apps.without_init_file", ] base_dir = os.path.dirname(os.path.dirname(__file__)) for app in test_apps: with self.modify_settings(INSTALLED_APPS={"append": app}): migration = migrations.Migration("0001_initial", app.split(".")[-1]) expected_path = os.path.join( base_dir, *(app.split(".") + ["migrations", "0001_initial.py"]) ) writer = MigrationWriter(migration) self.assertEqual(writer.path, expected_path) def test_custom_operation(self): migration = type( "Migration", (migrations.Migration,), { "operations": [ custom_migration_operations.operations.TestOperation(), custom_migration_operations.operations.CreateModel(), migrations.CreateModel("MyModel", (), {}, (models.Model,)), custom_migration_operations.more_operations.TestOperation(), ], "dependencies": [], }, ) writer = MigrationWriter(migration) output = writer.as_string() result = self.safe_exec(output) self.assertIn("custom_migration_operations", result) self.assertNotEqual( result["custom_migration_operations"].operations.TestOperation, result["custom_migration_operations"].more_operations.TestOperation, ) def test_sorted_dependencies(self): migration = type( "Migration", (migrations.Migration,), { "operations": [ migrations.AddField("mymodel", "myfield", models.IntegerField()), ], "dependencies": [ ("testapp10", "0005_fifth"), ("testapp02", "0005_third"), ("testapp02", "0004_sixth"), ("testapp01", "0001_initial"), ], }, ) output = MigrationWriter(migration, include_header=False).as_string() self.assertIn( " dependencies = [\n" " ('testapp01', '0001_initial'),\n" " ('testapp02', '0004_sixth'),\n" " ('testapp02', '0005_third'),\n" " ('testapp10', '0005_fifth'),\n" " ]", output, ) def test_sorted_imports(self): """ #24155 - Tests ordering of imports. """ migration = type( "Migration", (migrations.Migration,), { "operations": [ migrations.AddField( "mymodel", "myfield", models.DateTimeField( default=datetime.datetime( 2012, 1, 1, 1, 1, tzinfo=datetime.timezone.utc ), ), ), migrations.AddField( "mymodel", "myfield2", models.FloatField(default=time.time), ), ] }, ) writer = MigrationWriter(migration) output = writer.as_string() self.assertIn( "import datetime\nimport time\nfrom django.db import migrations, models\n", output, ) def test_migration_file_header_comments(self): """ Test comments at top of file. """ migration = type("Migration", (migrations.Migration,), {"operations": []}) dt = datetime.datetime(2015, 7, 31, 4, 40, 0, 0, tzinfo=datetime.timezone.utc) with mock.patch("django.db.migrations.writer.now", lambda: dt): for include_header in (True, False): with self.subTest(include_header=include_header): writer = MigrationWriter(migration, include_header) output = writer.as_string() self.assertEqual( include_header, output.startswith( "# Generated by Django %s on 2015-07-31 04:40\n\n" % get_version() ), ) if not include_header: # Make sure the output starts with something that's not # a comment or indentation or blank line self.assertRegex( output.splitlines(keepends=True)[0], r"^[^#\s]+" ) def test_models_import_omitted(self): """ django.db.models shouldn't be imported if unused. """ migration = type( "Migration", (migrations.Migration,), { "operations": [ migrations.AlterModelOptions( name="model", options={ "verbose_name": "model", "verbose_name_plural": "models", }, ), ] }, ) writer = MigrationWriter(migration) output = writer.as_string() self.assertIn("from django.db import migrations\n", output) def test_deconstruct_class_arguments(self): # Yes, it doesn't make sense to use a class as a default for a # CharField. It does make sense for custom fields though, for example # an enumfield that takes the enum class as an argument. string = MigrationWriter.serialize( models.CharField(default=DeconstructibleInstances) )[0] self.assertEqual( string, "models.CharField(default=migrations.test_writer.DeconstructibleInstances)", ) def test_register_serializer(self): class ComplexSerializer(BaseSerializer): def serialize(self): return "complex(%r)" % self.value, {} MigrationWriter.register_serializer(complex, ComplexSerializer) self.assertSerializedEqual(complex(1, 2)) MigrationWriter.unregister_serializer(complex) with self.assertRaisesMessage(ValueError, "Cannot serialize: (1+2j)"): self.assertSerializedEqual(complex(1, 2)) def test_register_non_serializer(self): with self.assertRaisesMessage( ValueError, "'TestModel1' must inherit from 'BaseSerializer'." ): MigrationWriter.register_serializer(complex, TestModel1)
e8523f2cef375fb981be3633ee904e4a47162494a951b91edab6d1cf86b59409
import math from django.core.exceptions import FieldDoesNotExist from django.db import IntegrityError, connection, migrations, models, transaction from django.db.migrations.migration import Migration from django.db.migrations.operations.fields import FieldOperation from django.db.migrations.state import ModelState, ProjectState from django.db.models.expressions import Value from django.db.models.functions import Abs, Pi from django.db.transaction import atomic from django.test import ( SimpleTestCase, ignore_warnings, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.utils import CaptureQueriesContext from django.utils.deprecation import RemovedInDjango51Warning from .models import FoodManager, FoodQuerySet, UnicodeModel from .test_base import OperationTestBase class Mixin: pass class OperationTests(OperationTestBase): """ Tests running the operations and making sure they do what they say they do. Each test looks at their state changing, and then their database operation - both forwards and backwards. """ def test_create_model(self): """ Tests the CreateModel operation. Most other tests use this operation as part of setup, so check failures here first. """ operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=1)), ], ) self.assertEqual(operation.describe(), "Create model Pony") self.assertEqual(operation.migration_name_fragment, "pony") # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual(new_state.models["test_crmo", "pony"].name, "Pony") self.assertEqual(len(new_state.models["test_crmo", "pony"].fields), 2) # Test the database alteration self.assertTableNotExists("test_crmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["fields", "name"]) # And default manager not in set operation = migrations.CreateModel( "Foo", fields=[], managers=[("objects", models.Manager())] ) definition = operation.deconstruct() self.assertNotIn("managers", definition[2]) def test_create_model_with_duplicate_field_name(self): with self.assertRaisesMessage( ValueError, "Found duplicate value pink in CreateModel fields argument." ): migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.TextField()), ("pink", models.IntegerField(default=1)), ], ) def test_create_model_with_duplicate_base(self): message = "Found duplicate value test_crmo.pony in CreateModel bases argument." with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( "test_crmo.Pony", "test_crmo.Pony", ), ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( "test_crmo.Pony", "test_crmo.pony", ), ) message = ( "Found duplicate value migrations.unicodemodel in CreateModel bases " "argument." ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( UnicodeModel, UnicodeModel, ), ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( UnicodeModel, "migrations.unicodemodel", ), ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( UnicodeModel, "migrations.UnicodeModel", ), ) message = ( "Found duplicate value <class 'django.db.models.base.Model'> in " "CreateModel bases argument." ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( models.Model, models.Model, ), ) message = ( "Found duplicate value <class 'migrations.test_operations.Mixin'> in " "CreateModel bases argument." ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( Mixin, Mixin, ), ) def test_create_model_with_duplicate_manager_name(self): with self.assertRaisesMessage( ValueError, "Found duplicate value objects in CreateModel managers argument.", ): migrations.CreateModel( "Pony", fields=[], managers=[ ("objects", models.Manager()), ("objects", models.Manager()), ], ) def test_create_model_with_unique_after(self): """ Tests the CreateModel operation directly followed by an AlterUniqueTogether (bug #22844 - sqlite remake issues) """ operation1 = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=1)), ], ) operation2 = migrations.CreateModel( "Rider", [ ("id", models.AutoField(primary_key=True)), ("number", models.IntegerField(default=1)), ("pony", models.ForeignKey("test_crmoua.Pony", models.CASCADE)), ], ) operation3 = migrations.AlterUniqueTogether( "Rider", [ ("number", "pony"), ], ) # Test the database alteration project_state = ProjectState() self.assertTableNotExists("test_crmoua_pony") self.assertTableNotExists("test_crmoua_rider") with connection.schema_editor() as editor: new_state = project_state.clone() operation1.state_forwards("test_crmoua", new_state) operation1.database_forwards( "test_crmoua", editor, project_state, new_state ) project_state, new_state = new_state, new_state.clone() operation2.state_forwards("test_crmoua", new_state) operation2.database_forwards( "test_crmoua", editor, project_state, new_state ) project_state, new_state = new_state, new_state.clone() operation3.state_forwards("test_crmoua", new_state) operation3.database_forwards( "test_crmoua", editor, project_state, new_state ) self.assertTableExists("test_crmoua_pony") self.assertTableExists("test_crmoua_rider") def test_create_model_m2m(self): """ Test the creation of a model with a ManyToMany field and the auto-created "through" model. """ project_state = self.set_up_test_model("test_crmomm") operation = migrations.CreateModel( "Stable", [ ("id", models.AutoField(primary_key=True)), ("ponies", models.ManyToManyField("Pony", related_name="stables")), ], ) # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_crmomm", new_state) # Test the database alteration self.assertTableNotExists("test_crmomm_stable_ponies") with connection.schema_editor() as editor: operation.database_forwards("test_crmomm", editor, project_state, new_state) self.assertTableExists("test_crmomm_stable") self.assertTableExists("test_crmomm_stable_ponies") self.assertColumnNotExists("test_crmomm_stable", "ponies") # Make sure the M2M field actually works with atomic(): Pony = new_state.apps.get_model("test_crmomm", "Pony") Stable = new_state.apps.get_model("test_crmomm", "Stable") stable = Stable.objects.create() p1 = Pony.objects.create(pink=False, weight=4.55) p2 = Pony.objects.create(pink=True, weight=5.43) stable.ponies.add(p1, p2) self.assertEqual(stable.ponies.count(), 2) stable.ponies.all().delete() # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crmomm", editor, new_state, project_state ) self.assertTableNotExists("test_crmomm_stable") self.assertTableNotExists("test_crmomm_stable_ponies") @skipUnlessDBFeature("supports_collation_on_charfield", "supports_foreign_keys") def test_create_fk_models_to_pk_field_db_collation(self): """Creation of models with a FK to a PK with db_collation.""" collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") app_label = "test_cfkmtopkfdbc" operations = [ migrations.CreateModel( "Pony", [ ( "id", models.CharField( primary_key=True, max_length=10, db_collation=collation, ), ), ], ) ] project_state = self.apply_operations(app_label, ProjectState(), operations) # ForeignKey. new_state = project_state.clone() operation = migrations.CreateModel( "Rider", [ ("id", models.AutoField(primary_key=True)), ("pony", models.ForeignKey("Pony", models.CASCADE)), ], ) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnCollation(f"{app_label}_rider", "pony_id", collation) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) # OneToOneField. new_state = project_state.clone() operation = migrations.CreateModel( "ShetlandPony", [ ( "pony", models.OneToOneField("Pony", models.CASCADE, primary_key=True), ), ("cuteness", models.IntegerField(default=1)), ], ) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnCollation(f"{app_label}_shetlandpony", "pony_id", collation) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) def test_create_model_inheritance(self): """ Tests the CreateModel operation on a multi-table inheritance setup. """ project_state = self.set_up_test_model("test_crmoih") # Test the state alteration operation = migrations.CreateModel( "ShetlandPony", [ ( "pony_ptr", models.OneToOneField( "test_crmoih.Pony", models.CASCADE, auto_created=True, primary_key=True, to_field="id", serialize=False, ), ), ("cuteness", models.IntegerField(default=1)), ], ) new_state = project_state.clone() operation.state_forwards("test_crmoih", new_state) self.assertIn(("test_crmoih", "shetlandpony"), new_state.models) # Test the database alteration self.assertTableNotExists("test_crmoih_shetlandpony") with connection.schema_editor() as editor: operation.database_forwards("test_crmoih", editor, project_state, new_state) self.assertTableExists("test_crmoih_shetlandpony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crmoih", editor, new_state, project_state ) self.assertTableNotExists("test_crmoih_shetlandpony") def test_create_proxy_model(self): """ CreateModel ignores proxy models. """ project_state = self.set_up_test_model("test_crprmo") # Test the state alteration operation = migrations.CreateModel( "ProxyPony", [], options={"proxy": True}, bases=("test_crprmo.Pony",), ) self.assertEqual(operation.describe(), "Create proxy model ProxyPony") new_state = project_state.clone() operation.state_forwards("test_crprmo", new_state) self.assertIn(("test_crprmo", "proxypony"), new_state.models) # Test the database alteration self.assertTableNotExists("test_crprmo_proxypony") self.assertTableExists("test_crprmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crprmo", editor, project_state, new_state) self.assertTableNotExists("test_crprmo_proxypony") self.assertTableExists("test_crprmo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crprmo", editor, new_state, project_state ) self.assertTableNotExists("test_crprmo_proxypony") self.assertTableExists("test_crprmo_pony") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["bases", "fields", "name", "options"]) def test_create_unmanaged_model(self): """ CreateModel ignores unmanaged models. """ project_state = self.set_up_test_model("test_crummo") # Test the state alteration operation = migrations.CreateModel( "UnmanagedPony", [], options={"proxy": True}, bases=("test_crummo.Pony",), ) self.assertEqual(operation.describe(), "Create proxy model UnmanagedPony") new_state = project_state.clone() operation.state_forwards("test_crummo", new_state) self.assertIn(("test_crummo", "unmanagedpony"), new_state.models) # Test the database alteration self.assertTableNotExists("test_crummo_unmanagedpony") self.assertTableExists("test_crummo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crummo", editor, project_state, new_state) self.assertTableNotExists("test_crummo_unmanagedpony") self.assertTableExists("test_crummo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crummo", editor, new_state, project_state ) self.assertTableNotExists("test_crummo_unmanagedpony") self.assertTableExists("test_crummo_pony") @skipUnlessDBFeature("supports_table_check_constraints") def test_create_model_with_constraint(self): where = models.Q(pink__gt=2) check_constraint = models.CheckConstraint( check=where, name="test_constraint_pony_pink_gt_2" ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ], options={"constraints": [check_constraint]}, ) # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) # Test database alteration self.assertTableNotExists("test_crmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") with connection.cursor() as cursor: with self.assertRaises(IntegrityError): cursor.execute("INSERT INTO test_crmo_pony (id, pink) VALUES (1, 1)") # Test reversal with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Test deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual(definition[2]["options"]["constraints"], [check_constraint]) @skipUnlessDBFeature("supports_table_check_constraints") def test_create_model_with_boolean_expression_in_check_constraint(self): app_label = "test_crmobechc" rawsql_constraint = models.CheckConstraint( check=models.expressions.RawSQL( "price < %s", (1000,), output_field=models.BooleanField() ), name=f"{app_label}_price_lt_1000_raw", ) wrapper_constraint = models.CheckConstraint( check=models.expressions.ExpressionWrapper( models.Q(price__gt=500) | models.Q(price__lt=500), output_field=models.BooleanField(), ), name=f"{app_label}_price_neq_500_wrap", ) operation = migrations.CreateModel( "Product", [ ("id", models.AutoField(primary_key=True)), ("price", models.IntegerField(null=True)), ], options={"constraints": [rawsql_constraint, wrapper_constraint]}, ) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Add table. self.assertTableNotExists(app_label) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertTableExists(f"{app_label}_product") insert_sql = f"INSERT INTO {app_label}_product (id, price) VALUES (%d, %d)" with connection.cursor() as cursor: with self.assertRaises(IntegrityError): cursor.execute(insert_sql % (1, 1000)) cursor.execute(insert_sql % (1, 999)) with self.assertRaises(IntegrityError): cursor.execute(insert_sql % (2, 500)) cursor.execute(insert_sql % (2, 499)) def test_create_model_with_partial_unique_constraint(self): partial_unique_constraint = models.UniqueConstraint( fields=["pink"], condition=models.Q(weight__gt=5), name="test_constraint_pony_pink_for_weight_gt_5_uniq", ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ("weight", models.FloatField()), ], options={"constraints": [partial_unique_constraint]}, ) # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) # Test database alteration self.assertTableNotExists("test_crmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") # Test constraint works Pony = new_state.apps.get_model("test_crmo", "Pony") Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=6.0) if connection.features.supports_partial_indexes: with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=7.0) else: Pony.objects.create(pink=1, weight=7.0) # Test reversal with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Test deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual( definition[2]["options"]["constraints"], [partial_unique_constraint] ) def test_create_model_with_deferred_unique_constraint(self): deferred_unique_constraint = models.UniqueConstraint( fields=["pink"], name="deferrable_pink_constraint", deferrable=models.Deferrable.DEFERRED, ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ], options={"constraints": [deferred_unique_constraint]}, ) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) self.assertTableNotExists("test_crmo_pony") # Create table. with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") Pony = new_state.apps.get_model("test_crmo", "Pony") Pony.objects.create(pink=1) if connection.features.supports_deferrable_unique_constraints: # Unique constraint is deferred. with transaction.atomic(): obj = Pony.objects.create(pink=1) obj.pink = 2 obj.save() # Constraint behavior can be changed with SET CONSTRAINTS. with self.assertRaises(IntegrityError): with transaction.atomic(), connection.cursor() as cursor: quoted_name = connection.ops.quote_name( deferred_unique_constraint.name ) cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name) obj = Pony.objects.create(pink=1) obj.pink = 3 obj.save() else: Pony.objects.create(pink=1) # Reversal. with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual( definition[2]["options"]["constraints"], [deferred_unique_constraint], ) @skipUnlessDBFeature("supports_covering_indexes") def test_create_model_with_covering_unique_constraint(self): covering_unique_constraint = models.UniqueConstraint( fields=["pink"], include=["weight"], name="test_constraint_pony_pink_covering_weight", ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ("weight", models.FloatField()), ], options={"constraints": [covering_unique_constraint]}, ) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) self.assertTableNotExists("test_crmo_pony") # Create table. with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") Pony = new_state.apps.get_model("test_crmo", "Pony") Pony.objects.create(pink=1, weight=4.0) with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=7.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual( definition[2]["options"]["constraints"], [covering_unique_constraint], ) def test_create_model_managers(self): """ The managers on a model are set. """ project_state = self.set_up_test_model("test_cmoma") # Test the state alteration operation = migrations.CreateModel( "Food", fields=[ ("id", models.AutoField(primary_key=True)), ], managers=[ ("food_qs", FoodQuerySet.as_manager()), ("food_mgr", FoodManager("a", "b")), ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)), ], ) self.assertEqual(operation.describe(), "Create model Food") new_state = project_state.clone() operation.state_forwards("test_cmoma", new_state) self.assertIn(("test_cmoma", "food"), new_state.models) managers = new_state.models["test_cmoma", "food"].managers self.assertEqual(managers[0][0], "food_qs") self.assertIsInstance(managers[0][1], models.Manager) self.assertEqual(managers[1][0], "food_mgr") self.assertIsInstance(managers[1][1], FoodManager) self.assertEqual(managers[1][1].args, ("a", "b", 1, 2)) self.assertEqual(managers[2][0], "food_mgr_kwargs") self.assertIsInstance(managers[2][1], FoodManager) self.assertEqual(managers[2][1].args, ("x", "y", 3, 4)) def test_delete_model(self): """ Tests the DeleteModel operation. """ project_state = self.set_up_test_model("test_dlmo") # Test the state alteration operation = migrations.DeleteModel("Pony") self.assertEqual(operation.describe(), "Delete model Pony") self.assertEqual(operation.migration_name_fragment, "delete_pony") new_state = project_state.clone() operation.state_forwards("test_dlmo", new_state) self.assertNotIn(("test_dlmo", "pony"), new_state.models) # Test the database alteration self.assertTableExists("test_dlmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_dlmo", editor, project_state, new_state) self.assertTableNotExists("test_dlmo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_dlmo", editor, new_state, project_state) self.assertTableExists("test_dlmo_pony") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "DeleteModel") self.assertEqual(definition[1], []) self.assertEqual(list(definition[2]), ["name"]) def test_delete_proxy_model(self): """ Tests the DeleteModel operation ignores proxy models. """ project_state = self.set_up_test_model("test_dlprmo", proxy_model=True) # Test the state alteration operation = migrations.DeleteModel("ProxyPony") new_state = project_state.clone() operation.state_forwards("test_dlprmo", new_state) self.assertIn(("test_dlprmo", "proxypony"), project_state.models) self.assertNotIn(("test_dlprmo", "proxypony"), new_state.models) # Test the database alteration self.assertTableExists("test_dlprmo_pony") self.assertTableNotExists("test_dlprmo_proxypony") with connection.schema_editor() as editor: operation.database_forwards("test_dlprmo", editor, project_state, new_state) self.assertTableExists("test_dlprmo_pony") self.assertTableNotExists("test_dlprmo_proxypony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_dlprmo", editor, new_state, project_state ) self.assertTableExists("test_dlprmo_pony") self.assertTableNotExists("test_dlprmo_proxypony") def test_delete_mti_model(self): project_state = self.set_up_test_model("test_dlmtimo", mti_model=True) # Test the state alteration operation = migrations.DeleteModel("ShetlandPony") new_state = project_state.clone() operation.state_forwards("test_dlmtimo", new_state) self.assertIn(("test_dlmtimo", "shetlandpony"), project_state.models) self.assertNotIn(("test_dlmtimo", "shetlandpony"), new_state.models) # Test the database alteration self.assertTableExists("test_dlmtimo_pony") self.assertTableExists("test_dlmtimo_shetlandpony") self.assertColumnExists("test_dlmtimo_shetlandpony", "pony_ptr_id") with connection.schema_editor() as editor: operation.database_forwards( "test_dlmtimo", editor, project_state, new_state ) self.assertTableExists("test_dlmtimo_pony") self.assertTableNotExists("test_dlmtimo_shetlandpony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_dlmtimo", editor, new_state, project_state ) self.assertTableExists("test_dlmtimo_pony") self.assertTableExists("test_dlmtimo_shetlandpony") self.assertColumnExists("test_dlmtimo_shetlandpony", "pony_ptr_id") def test_rename_model(self): """ Tests the RenameModel operation. """ project_state = self.set_up_test_model("test_rnmo", related_model=True) # Test the state alteration operation = migrations.RenameModel("Pony", "Horse") self.assertEqual(operation.describe(), "Rename model Pony to Horse") self.assertEqual(operation.migration_name_fragment, "rename_pony_horse") # Test initial state and database self.assertIn(("test_rnmo", "pony"), project_state.models) self.assertNotIn(("test_rnmo", "horse"), project_state.models) self.assertTableExists("test_rnmo_pony") self.assertTableNotExists("test_rnmo_horse") if connection.features.supports_foreign_keys: self.assertFKExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id") ) self.assertFKNotExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id") ) # Migrate forwards new_state = project_state.clone() atomic_rename = connection.features.supports_atomic_references_rename new_state = self.apply_operations( "test_rnmo", new_state, [operation], atomic=atomic_rename ) # Test new state and database self.assertNotIn(("test_rnmo", "pony"), new_state.models) self.assertIn(("test_rnmo", "horse"), new_state.models) # RenameModel also repoints all incoming FKs and M2Ms self.assertEqual( new_state.models["test_rnmo", "rider"].fields["pony"].remote_field.model, "test_rnmo.Horse", ) self.assertTableNotExists("test_rnmo_pony") self.assertTableExists("test_rnmo_horse") if connection.features.supports_foreign_keys: self.assertFKNotExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id") ) self.assertFKExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id") ) # Migrate backwards original_state = self.unapply_operations( "test_rnmo", project_state, [operation], atomic=atomic_rename ) # Test original state and database self.assertIn(("test_rnmo", "pony"), original_state.models) self.assertNotIn(("test_rnmo", "horse"), original_state.models) self.assertEqual( original_state.models["test_rnmo", "rider"] .fields["pony"] .remote_field.model, "Pony", ) self.assertTableExists("test_rnmo_pony") self.assertTableNotExists("test_rnmo_horse") if connection.features.supports_foreign_keys: self.assertFKExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id") ) self.assertFKNotExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id") ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RenameModel") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"old_name": "Pony", "new_name": "Horse"}) def test_rename_model_state_forwards(self): """ RenameModel operations shouldn't trigger the caching of rendered apps on state without prior apps. """ state = ProjectState() state.add_model(ModelState("migrations", "Foo", [])) operation = migrations.RenameModel("Foo", "Bar") operation.state_forwards("migrations", state) self.assertNotIn("apps", state.__dict__) self.assertNotIn(("migrations", "foo"), state.models) self.assertIn(("migrations", "bar"), state.models) # Now with apps cached. apps = state.apps operation = migrations.RenameModel("Bar", "Foo") operation.state_forwards("migrations", state) self.assertIs(state.apps, apps) self.assertNotIn(("migrations", "bar"), state.models) self.assertIn(("migrations", "foo"), state.models) def test_rename_model_with_self_referential_fk(self): """ Tests the RenameModel operation on model with self referential FK. """ project_state = self.set_up_test_model("test_rmwsrf", related_model=True) # Test the state alteration operation = migrations.RenameModel("Rider", "HorseRider") self.assertEqual(operation.describe(), "Rename model Rider to HorseRider") new_state = project_state.clone() operation.state_forwards("test_rmwsrf", new_state) self.assertNotIn(("test_rmwsrf", "rider"), new_state.models) self.assertIn(("test_rmwsrf", "horserider"), new_state.models) # Remember, RenameModel also repoints all incoming FKs and M2Ms self.assertEqual( "self", new_state.models["test_rmwsrf", "horserider"] .fields["friend"] .remote_field.model, ) HorseRider = new_state.apps.get_model("test_rmwsrf", "horserider") self.assertIs( HorseRider._meta.get_field("horserider").remote_field.model, HorseRider ) # Test the database alteration self.assertTableExists("test_rmwsrf_rider") self.assertTableNotExists("test_rmwsrf_horserider") if connection.features.supports_foreign_keys: self.assertFKExists( "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_rider", "id") ) self.assertFKNotExists( "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_horserider", "id") ) atomic_rename = connection.features.supports_atomic_references_rename with connection.schema_editor(atomic=atomic_rename) as editor: operation.database_forwards("test_rmwsrf", editor, project_state, new_state) self.assertTableNotExists("test_rmwsrf_rider") self.assertTableExists("test_rmwsrf_horserider") if connection.features.supports_foreign_keys: self.assertFKNotExists( "test_rmwsrf_horserider", ["friend_id"], ("test_rmwsrf_rider", "id") ) self.assertFKExists( "test_rmwsrf_horserider", ["friend_id"], ("test_rmwsrf_horserider", "id"), ) # And test reversal with connection.schema_editor(atomic=atomic_rename) as editor: operation.database_backwards( "test_rmwsrf", editor, new_state, project_state ) self.assertTableExists("test_rmwsrf_rider") self.assertTableNotExists("test_rmwsrf_horserider") if connection.features.supports_foreign_keys: self.assertFKExists( "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_rider", "id") ) self.assertFKNotExists( "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_horserider", "id") ) def test_rename_model_with_superclass_fk(self): """ Tests the RenameModel operation on a model which has a superclass that has a foreign key. """ project_state = self.set_up_test_model( "test_rmwsc", related_model=True, mti_model=True ) # Test the state alteration operation = migrations.RenameModel("ShetlandPony", "LittleHorse") self.assertEqual( operation.describe(), "Rename model ShetlandPony to LittleHorse" ) new_state = project_state.clone() operation.state_forwards("test_rmwsc", new_state) self.assertNotIn(("test_rmwsc", "shetlandpony"), new_state.models) self.assertIn(("test_rmwsc", "littlehorse"), new_state.models) # RenameModel shouldn't repoint the superclass's relations, only local ones self.assertEqual( project_state.models["test_rmwsc", "rider"] .fields["pony"] .remote_field.model, new_state.models["test_rmwsc", "rider"].fields["pony"].remote_field.model, ) # Before running the migration we have a table for Shetland Pony, not # Little Horse. self.assertTableExists("test_rmwsc_shetlandpony") self.assertTableNotExists("test_rmwsc_littlehorse") if connection.features.supports_foreign_keys: # and the foreign key on rider points to pony, not shetland pony self.assertFKExists( "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_pony", "id") ) self.assertFKNotExists( "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_shetlandpony", "id") ) with connection.schema_editor( atomic=connection.features.supports_atomic_references_rename ) as editor: operation.database_forwards("test_rmwsc", editor, project_state, new_state) # Now we have a little horse table, not shetland pony self.assertTableNotExists("test_rmwsc_shetlandpony") self.assertTableExists("test_rmwsc_littlehorse") if connection.features.supports_foreign_keys: # but the Foreign keys still point at pony, not little horse self.assertFKExists( "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_pony", "id") ) self.assertFKNotExists( "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_littlehorse", "id") ) def test_rename_model_no_relations_with_db_table_noop(self): app_label = "test_rmwdbtnoop" project_state = self.set_up_test_model(app_label, db_table="my_pony") operation = migrations.RenameModel("Pony", "LittleHorse") new_state = project_state.clone() operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor, self.assertNumQueries(0): operation.database_forwards(app_label, editor, project_state, new_state) def test_rename_model_with_self_referential_m2m(self): app_label = "test_rename_model_with_self_referential_m2m" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "ReflexivePony", fields=[ ("id", models.AutoField(primary_key=True)), ("ponies", models.ManyToManyField("self")), ], ), ], ) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameModel("ReflexivePony", "ReflexivePony2"), ], atomic=connection.features.supports_atomic_references_rename, ) Pony = project_state.apps.get_model(app_label, "ReflexivePony2") pony = Pony.objects.create() pony.ponies.add(pony) def test_rename_model_with_m2m(self): app_label = "test_rename_model_with_m2m" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("riders", models.ManyToManyField("Rider")), ], ), ], ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameModel("Pony", "Pony2"), ], atomic=connection.features.supports_atomic_references_rename, ) Pony = project_state.apps.get_model(app_label, "Pony2") Rider = project_state.apps.get_model(app_label, "Rider") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) self.assertEqual(Pony.objects.count(), 2) self.assertEqual(Rider.objects.count(), 2) self.assertEqual( Pony._meta.get_field("riders").remote_field.through.objects.count(), 2 ) def test_rename_model_with_m2m_models_in_different_apps_with_same_name(self): app_label_1 = "test_rmw_m2m_1" app_label_2 = "test_rmw_m2m_2" project_state = self.apply_operations( app_label_1, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], ), ], ) project_state = self.apply_operations( app_label_2, project_state, operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ("riders", models.ManyToManyField(f"{app_label_1}.Rider")), ], ), ], ) m2m_table = f"{app_label_2}_rider_riders" self.assertColumnExists(m2m_table, "from_rider_id") self.assertColumnExists(m2m_table, "to_rider_id") Rider_1 = project_state.apps.get_model(app_label_1, "Rider") Rider_2 = project_state.apps.get_model(app_label_2, "Rider") rider_2 = Rider_2.objects.create() rider_2.riders.add(Rider_1.objects.create()) # Rename model. project_state_2 = project_state.clone() project_state = self.apply_operations( app_label_2, project_state, operations=[migrations.RenameModel("Rider", "Pony")], atomic=connection.features.supports_atomic_references_rename, ) m2m_table = f"{app_label_2}_pony_riders" self.assertColumnExists(m2m_table, "pony_id") self.assertColumnExists(m2m_table, "rider_id") Rider_1 = project_state.apps.get_model(app_label_1, "Rider") Rider_2 = project_state.apps.get_model(app_label_2, "Pony") rider_2 = Rider_2.objects.create() rider_2.riders.add(Rider_1.objects.create()) self.assertEqual(Rider_1.objects.count(), 2) self.assertEqual(Rider_2.objects.count(), 2) self.assertEqual( Rider_2._meta.get_field("riders").remote_field.through.objects.count(), 2 ) # Reversal. self.unapply_operations( app_label_2, project_state_2, operations=[migrations.RenameModel("Rider", "Pony")], atomic=connection.features.supports_atomic_references_rename, ) m2m_table = f"{app_label_2}_rider_riders" self.assertColumnExists(m2m_table, "to_rider_id") self.assertColumnExists(m2m_table, "from_rider_id") def test_rename_model_with_db_table_rename_m2m(self): app_label = "test_rmwdbrm2m" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("riders", models.ManyToManyField("Rider")), ], options={"db_table": "pony"}, ), ], ) new_state = self.apply_operations( app_label, project_state, operations=[migrations.RenameModel("Pony", "PinkPony")], atomic=connection.features.supports_atomic_references_rename, ) Pony = new_state.apps.get_model(app_label, "PinkPony") Rider = new_state.apps.get_model(app_label, "Rider") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) def test_rename_m2m_target_model(self): app_label = "test_rename_m2m_target_model" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("riders", models.ManyToManyField("Rider")), ], ), ], ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameModel("Rider", "Rider2"), ], atomic=connection.features.supports_atomic_references_rename, ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider2") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) self.assertEqual(Pony.objects.count(), 2) self.assertEqual(Rider.objects.count(), 2) self.assertEqual( Pony._meta.get_field("riders").remote_field.through.objects.count(), 2 ) def test_rename_m2m_through_model(self): app_label = "test_rename_through" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ( "rider", models.ForeignKey( "test_rename_through.Rider", models.CASCADE ), ), ( "pony", models.ForeignKey( "test_rename_through.Pony", models.CASCADE ), ), ], ), migrations.AddField( "Pony", "riders", models.ManyToManyField( "test_rename_through.Rider", through="test_rename_through.PonyRider", ), ), ], ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider") PonyRider = project_state.apps.get_model(app_label, "PonyRider") pony = Pony.objects.create() rider = Rider.objects.create() PonyRider.objects.create(pony=pony, rider=rider) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameModel("PonyRider", "PonyRider2"), ], ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider") PonyRider = project_state.apps.get_model(app_label, "PonyRider2") pony = Pony.objects.first() rider = Rider.objects.create() PonyRider.objects.create(pony=pony, rider=rider) self.assertEqual(Pony.objects.count(), 1) self.assertEqual(Rider.objects.count(), 2) self.assertEqual(PonyRider.objects.count(), 2) self.assertEqual(pony.riders.count(), 2) def test_rename_m2m_model_after_rename_field(self): """RenameModel renames a many-to-many column after a RenameField.""" app_label = "test_rename_multiple" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=20)), ], ), migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ( "pony", models.ForeignKey( "test_rename_multiple.Pony", models.CASCADE ), ), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ("riders", models.ManyToManyField("Rider")), ], ), migrations.RenameField( model_name="pony", old_name="name", new_name="fancy_name" ), migrations.RenameModel(old_name="Rider", new_name="Jockey"), ], atomic=connection.features.supports_atomic_references_rename, ) Pony = project_state.apps.get_model(app_label, "Pony") Jockey = project_state.apps.get_model(app_label, "Jockey") PonyRider = project_state.apps.get_model(app_label, "PonyRider") # No "no such column" error means the column was renamed correctly. pony = Pony.objects.create(fancy_name="a good name") jockey = Jockey.objects.create(pony=pony) ponyrider = PonyRider.objects.create() ponyrider.riders.add(jockey) def test_add_field(self): """ Tests the AddField operation. """ # Test the state alteration operation = migrations.AddField( "Pony", "height", models.FloatField(null=True, default=5), ) self.assertEqual(operation.describe(), "Add field height to Pony") self.assertEqual(operation.migration_name_fragment, "pony_height") project_state, new_state = self.make_test_state("test_adfl", operation) self.assertEqual(len(new_state.models["test_adfl", "pony"].fields), 6) field = new_state.models["test_adfl", "pony"].fields["height"] self.assertEqual(field.default, 5) # Test the database alteration self.assertColumnNotExists("test_adfl_pony", "height") with connection.schema_editor() as editor: operation.database_forwards("test_adfl", editor, project_state, new_state) self.assertColumnExists("test_adfl_pony", "height") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_adfl", editor, new_state, project_state) self.assertColumnNotExists("test_adfl_pony", "height") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AddField") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["field", "model_name", "name"]) def test_add_charfield(self): """ Tests the AddField operation on TextField. """ project_state = self.set_up_test_model("test_adchfl") Pony = project_state.apps.get_model("test_adchfl", "Pony") pony = Pony.objects.create(weight=42) new_state = self.apply_operations( "test_adchfl", project_state, [ migrations.AddField( "Pony", "text", models.CharField(max_length=10, default="some text"), ), migrations.AddField( "Pony", "empty", models.CharField(max_length=10, default=""), ), # If not properly quoted digits would be interpreted as an int. migrations.AddField( "Pony", "digits", models.CharField(max_length=10, default="42"), ), # Manual quoting is fragile and could trip on quotes. Refs #xyz. migrations.AddField( "Pony", "quotes", models.CharField(max_length=10, default='"\'"'), ), ], ) Pony = new_state.apps.get_model("test_adchfl", "Pony") pony = Pony.objects.get(pk=pony.pk) self.assertEqual(pony.text, "some text") self.assertEqual(pony.empty, "") self.assertEqual(pony.digits, "42") self.assertEqual(pony.quotes, '"\'"') def test_add_textfield(self): """ Tests the AddField operation on TextField. """ project_state = self.set_up_test_model("test_adtxtfl") Pony = project_state.apps.get_model("test_adtxtfl", "Pony") pony = Pony.objects.create(weight=42) new_state = self.apply_operations( "test_adtxtfl", project_state, [ migrations.AddField( "Pony", "text", models.TextField(default="some text"), ), migrations.AddField( "Pony", "empty", models.TextField(default=""), ), # If not properly quoted digits would be interpreted as an int. migrations.AddField( "Pony", "digits", models.TextField(default="42"), ), # Manual quoting is fragile and could trip on quotes. Refs #xyz. migrations.AddField( "Pony", "quotes", models.TextField(default='"\'"'), ), ], ) Pony = new_state.apps.get_model("test_adtxtfl", "Pony") pony = Pony.objects.get(pk=pony.pk) self.assertEqual(pony.text, "some text") self.assertEqual(pony.empty, "") self.assertEqual(pony.digits, "42") self.assertEqual(pony.quotes, '"\'"') def test_add_binaryfield(self): """ Tests the AddField operation on TextField/BinaryField. """ project_state = self.set_up_test_model("test_adbinfl") Pony = project_state.apps.get_model("test_adbinfl", "Pony") pony = Pony.objects.create(weight=42) new_state = self.apply_operations( "test_adbinfl", project_state, [ migrations.AddField( "Pony", "blob", models.BinaryField(default=b"some text"), ), migrations.AddField( "Pony", "empty", models.BinaryField(default=b""), ), # If not properly quoted digits would be interpreted as an int. migrations.AddField( "Pony", "digits", models.BinaryField(default=b"42"), ), # Manual quoting is fragile and could trip on quotes. Refs #xyz. migrations.AddField( "Pony", "quotes", models.BinaryField(default=b'"\'"'), ), ], ) Pony = new_state.apps.get_model("test_adbinfl", "Pony") pony = Pony.objects.get(pk=pony.pk) # SQLite returns buffer/memoryview, cast to bytes for checking. self.assertEqual(bytes(pony.blob), b"some text") self.assertEqual(bytes(pony.empty), b"") self.assertEqual(bytes(pony.digits), b"42") self.assertEqual(bytes(pony.quotes), b'"\'"') def test_column_name_quoting(self): """ Column names that are SQL keywords shouldn't cause problems when used in migrations (#22168). """ project_state = self.set_up_test_model("test_regr22168") operation = migrations.AddField( "Pony", "order", models.IntegerField(default=0), ) new_state = project_state.clone() operation.state_forwards("test_regr22168", new_state) with connection.schema_editor() as editor: operation.database_forwards( "test_regr22168", editor, project_state, new_state ) self.assertColumnExists("test_regr22168_pony", "order") def test_add_field_preserve_default(self): """ Tests the AddField operation's state alteration when preserve_default = False. """ project_state = self.set_up_test_model("test_adflpd") # Test the state alteration operation = migrations.AddField( "Pony", "height", models.FloatField(null=True, default=4), preserve_default=False, ) new_state = project_state.clone() operation.state_forwards("test_adflpd", new_state) self.assertEqual(len(new_state.models["test_adflpd", "pony"].fields), 6) field = new_state.models["test_adflpd", "pony"].fields["height"] self.assertEqual(field.default, models.NOT_PROVIDED) # Test the database alteration project_state.apps.get_model("test_adflpd", "pony").objects.create( weight=4, ) self.assertColumnNotExists("test_adflpd_pony", "height") with connection.schema_editor() as editor: operation.database_forwards("test_adflpd", editor, project_state, new_state) self.assertColumnExists("test_adflpd_pony", "height") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AddField") self.assertEqual(definition[1], []) self.assertEqual( sorted(definition[2]), ["field", "model_name", "name", "preserve_default"] ) def test_add_field_database_default(self): """The AddField operation can set and unset a database default.""" app_label = "test_adfldd" table_name = f"{app_label}_pony" project_state = self.set_up_test_model(app_label) operation = migrations.AddField( "Pony", "height", models.FloatField(null=True, db_default=4) ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual(len(new_state.models[app_label, "pony"].fields), 6) field = new_state.models[app_label, "pony"].fields["height"] self.assertEqual(field.default, models.NOT_PROVIDED) self.assertEqual(field.db_default, Value(4)) project_state.apps.get_model(app_label, "pony").objects.create(weight=4) self.assertColumnNotExists(table_name, "height") # Add field. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnExists(table_name, "height") new_model = new_state.apps.get_model(app_label, "pony") old_pony = new_model.objects.get() self.assertEqual(old_pony.height, 4) new_pony = new_model.objects.create(weight=5) if not connection.features.can_return_columns_from_insert: new_pony.refresh_from_db() self.assertEqual(new_pony.height, 4) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertColumnNotExists(table_name, "height") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddField") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "field": field, "model_name": "Pony", "name": "height", }, ) def test_add_field_database_default_special_char_escaping(self): app_label = "test_adflddsce" table_name = f"{app_label}_pony" project_state = self.set_up_test_model(app_label) old_pony_pk = ( project_state.apps.get_model(app_label, "pony").objects.create(weight=4).pk ) tests = ["%", "'", '"'] for db_default in tests: with self.subTest(db_default=db_default): operation = migrations.AddField( "Pony", "special_char", models.CharField(max_length=1, db_default=db_default), ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual(len(new_state.models[app_label, "pony"].fields), 6) field = new_state.models[app_label, "pony"].fields["special_char"] self.assertEqual(field.default, models.NOT_PROVIDED) self.assertEqual(field.db_default, Value(db_default)) self.assertColumnNotExists(table_name, "special_char") with connection.schema_editor() as editor: operation.database_forwards( app_label, editor, project_state, new_state ) self.assertColumnExists(table_name, "special_char") new_model = new_state.apps.get_model(app_label, "pony") try: new_pony = new_model.objects.create(weight=5) if not connection.features.can_return_columns_from_insert: new_pony.refresh_from_db() self.assertEqual(new_pony.special_char, db_default) old_pony = new_model.objects.get(pk=old_pony_pk) if connection.vendor != "oracle" or db_default != "'": # The single quotation mark ' is properly quoted and is # set for new rows on Oracle, however it is not set on # existing rows. Skip the assertion as it's probably a # bug in Oracle. self.assertEqual(old_pony.special_char, db_default) finally: with connection.schema_editor() as editor: operation.database_backwards( app_label, editor, new_state, project_state ) @skipUnlessDBFeature("supports_expression_defaults") def test_add_field_database_default_function(self): app_label = "test_adflddf" table_name = f"{app_label}_pony" project_state = self.set_up_test_model(app_label) operation = migrations.AddField( "Pony", "height", models.FloatField(db_default=Pi()) ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual(len(new_state.models[app_label, "pony"].fields), 6) field = new_state.models[app_label, "pony"].fields["height"] self.assertEqual(field.default, models.NOT_PROVIDED) self.assertEqual(field.db_default, Pi()) project_state.apps.get_model(app_label, "pony").objects.create(weight=4) self.assertColumnNotExists(table_name, "height") # Add field. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnExists(table_name, "height") new_model = new_state.apps.get_model(app_label, "pony") old_pony = new_model.objects.get() self.assertAlmostEqual(old_pony.height, math.pi) new_pony = new_model.objects.create(weight=5) if not connection.features.can_return_columns_from_insert: new_pony.refresh_from_db() self.assertAlmostEqual(old_pony.height, math.pi) def test_add_field_both_defaults(self): """The AddField operation with both default and db_default.""" app_label = "test_adflbddd" table_name = f"{app_label}_pony" project_state = self.set_up_test_model(app_label) operation = migrations.AddField( "Pony", "height", models.FloatField(default=3, db_default=4) ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual(len(new_state.models[app_label, "pony"].fields), 6) field = new_state.models[app_label, "pony"].fields["height"] self.assertEqual(field.default, 3) self.assertEqual(field.db_default, Value(4)) project_state.apps.get_model(app_label, "pony").objects.create(weight=4) self.assertColumnNotExists(table_name, "height") # Add field. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnExists(table_name, "height") new_model = new_state.apps.get_model(app_label, "pony") old_pony = new_model.objects.get() self.assertEqual(old_pony.height, 4) new_pony = new_model.objects.create(weight=5) if not connection.features.can_return_columns_from_insert: new_pony.refresh_from_db() self.assertEqual(new_pony.height, 3) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertColumnNotExists(table_name, "height") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddField") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "field": field, "model_name": "Pony", "name": "height", }, ) def test_add_field_m2m(self): """ Tests the AddField operation with a ManyToManyField. """ project_state = self.set_up_test_model("test_adflmm", second_model=True) # Test the state alteration operation = migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable", related_name="ponies") ) new_state = project_state.clone() operation.state_forwards("test_adflmm", new_state) self.assertEqual(len(new_state.models["test_adflmm", "pony"].fields), 6) # Test the database alteration self.assertTableNotExists("test_adflmm_pony_stables") with connection.schema_editor() as editor: operation.database_forwards("test_adflmm", editor, project_state, new_state) self.assertTableExists("test_adflmm_pony_stables") self.assertColumnNotExists("test_adflmm_pony", "stables") # Make sure the M2M field actually works with atomic(): Pony = new_state.apps.get_model("test_adflmm", "Pony") p = Pony.objects.create(pink=False, weight=4.55) p.stables.create() self.assertEqual(p.stables.count(), 1) p.stables.all().delete() # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_adflmm", editor, new_state, project_state ) self.assertTableNotExists("test_adflmm_pony_stables") def test_alter_field_m2m(self): project_state = self.set_up_test_model("test_alflmm", second_model=True) project_state = self.apply_operations( "test_alflmm", project_state, operations=[ migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"), ) ], ) Pony = project_state.apps.get_model("test_alflmm", "Pony") self.assertFalse(Pony._meta.get_field("stables").blank) project_state = self.apply_operations( "test_alflmm", project_state, operations=[ migrations.AlterField( "Pony", "stables", models.ManyToManyField( to="Stable", related_name="ponies", blank=True ), ) ], ) Pony = project_state.apps.get_model("test_alflmm", "Pony") self.assertTrue(Pony._meta.get_field("stables").blank) def test_repoint_field_m2m(self): project_state = self.set_up_test_model( "test_alflmm", second_model=True, third_model=True ) project_state = self.apply_operations( "test_alflmm", project_state, operations=[ migrations.AddField( "Pony", "places", models.ManyToManyField("Stable", related_name="ponies"), ) ], ) Pony = project_state.apps.get_model("test_alflmm", "Pony") project_state = self.apply_operations( "test_alflmm", project_state, operations=[ migrations.AlterField( "Pony", "places", models.ManyToManyField(to="Van", related_name="ponies"), ) ], ) # Ensure the new field actually works Pony = project_state.apps.get_model("test_alflmm", "Pony") p = Pony.objects.create(pink=False, weight=4.55) p.places.create() self.assertEqual(p.places.count(), 1) p.places.all().delete() def test_remove_field_m2m(self): project_state = self.set_up_test_model("test_rmflmm", second_model=True) project_state = self.apply_operations( "test_rmflmm", project_state, operations=[ migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"), ) ], ) self.assertTableExists("test_rmflmm_pony_stables") with_field_state = project_state.clone() operations = [migrations.RemoveField("Pony", "stables")] project_state = self.apply_operations( "test_rmflmm", project_state, operations=operations ) self.assertTableNotExists("test_rmflmm_pony_stables") # And test reversal self.unapply_operations("test_rmflmm", with_field_state, operations=operations) self.assertTableExists("test_rmflmm_pony_stables") def test_remove_field_m2m_with_through(self): project_state = self.set_up_test_model("test_rmflmmwt", second_model=True) self.assertTableNotExists("test_rmflmmwt_ponystables") project_state = self.apply_operations( "test_rmflmmwt", project_state, operations=[ migrations.CreateModel( "PonyStables", fields=[ ( "pony", models.ForeignKey("test_rmflmmwt.Pony", models.CASCADE), ), ( "stable", models.ForeignKey("test_rmflmmwt.Stable", models.CASCADE), ), ], ), migrations.AddField( "Pony", "stables", models.ManyToManyField( "Stable", related_name="ponies", through="test_rmflmmwt.PonyStables", ), ), ], ) self.assertTableExists("test_rmflmmwt_ponystables") operations = [ migrations.RemoveField("Pony", "stables"), migrations.DeleteModel("PonyStables"), ] self.apply_operations("test_rmflmmwt", project_state, operations=operations) def test_remove_field(self): """ Tests the RemoveField operation. """ project_state = self.set_up_test_model("test_rmfl") # Test the state alteration operation = migrations.RemoveField("Pony", "pink") self.assertEqual(operation.describe(), "Remove field pink from Pony") self.assertEqual(operation.migration_name_fragment, "remove_pony_pink") new_state = project_state.clone() operation.state_forwards("test_rmfl", new_state) self.assertEqual(len(new_state.models["test_rmfl", "pony"].fields), 4) # Test the database alteration self.assertColumnExists("test_rmfl_pony", "pink") with connection.schema_editor() as editor: operation.database_forwards("test_rmfl", editor, project_state, new_state) self.assertColumnNotExists("test_rmfl_pony", "pink") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_rmfl", editor, new_state, project_state) self.assertColumnExists("test_rmfl_pony", "pink") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveField") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "name": "pink"}) def test_remove_fk(self): """ Tests the RemoveField operation on a foreign key. """ project_state = self.set_up_test_model("test_rfk", related_model=True) self.assertColumnExists("test_rfk_rider", "pony_id") operation = migrations.RemoveField("Rider", "pony") new_state = project_state.clone() operation.state_forwards("test_rfk", new_state) with connection.schema_editor() as editor: operation.database_forwards("test_rfk", editor, project_state, new_state) self.assertColumnNotExists("test_rfk_rider", "pony_id") with connection.schema_editor() as editor: operation.database_backwards("test_rfk", editor, new_state, project_state) self.assertColumnExists("test_rfk_rider", "pony_id") def test_alter_model_table(self): """ Tests the AlterModelTable operation. """ project_state = self.set_up_test_model("test_almota") # Test the state alteration operation = migrations.AlterModelTable("Pony", "test_almota_pony_2") self.assertEqual( operation.describe(), "Rename table for Pony to test_almota_pony_2" ) self.assertEqual(operation.migration_name_fragment, "alter_pony_table") new_state = project_state.clone() operation.state_forwards("test_almota", new_state) self.assertEqual( new_state.models["test_almota", "pony"].options["db_table"], "test_almota_pony_2", ) # Test the database alteration self.assertTableExists("test_almota_pony") self.assertTableNotExists("test_almota_pony_2") with connection.schema_editor() as editor: operation.database_forwards("test_almota", editor, project_state, new_state) self.assertTableNotExists("test_almota_pony") self.assertTableExists("test_almota_pony_2") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_almota", editor, new_state, project_state ) self.assertTableExists("test_almota_pony") self.assertTableNotExists("test_almota_pony_2") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterModelTable") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"name": "Pony", "table": "test_almota_pony_2"}) def test_alter_model_table_none(self): """ Tests the AlterModelTable operation if the table name is set to None. """ operation = migrations.AlterModelTable("Pony", None) self.assertEqual(operation.describe(), "Rename table for Pony to (default)") def test_alter_model_table_noop(self): """ Tests the AlterModelTable operation if the table name is not changed. """ project_state = self.set_up_test_model("test_almota") # Test the state alteration operation = migrations.AlterModelTable("Pony", "test_almota_pony") new_state = project_state.clone() operation.state_forwards("test_almota", new_state) self.assertEqual( new_state.models["test_almota", "pony"].options["db_table"], "test_almota_pony", ) # Test the database alteration self.assertTableExists("test_almota_pony") with connection.schema_editor() as editor: operation.database_forwards("test_almota", editor, project_state, new_state) self.assertTableExists("test_almota_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_almota", editor, new_state, project_state ) self.assertTableExists("test_almota_pony") def test_alter_model_table_m2m(self): """ AlterModelTable should rename auto-generated M2M tables. """ app_label = "test_talflmltlm2m" pony_db_table = "pony_foo" project_state = self.set_up_test_model( app_label, second_model=True, db_table=pony_db_table ) # Add the M2M field first_state = project_state.clone() operation = migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable") ) operation.state_forwards(app_label, first_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, first_state) original_m2m_table = "%s_%s" % (pony_db_table, "stables") new_m2m_table = "%s_%s" % (app_label, "pony_stables") self.assertTableExists(original_m2m_table) self.assertTableNotExists(new_m2m_table) # Rename the Pony db_table which should also rename the m2m table. second_state = first_state.clone() operation = migrations.AlterModelTable(name="pony", table=None) operation.state_forwards(app_label, second_state) atomic_rename = connection.features.supports_atomic_references_rename with connection.schema_editor(atomic=atomic_rename) as editor: operation.database_forwards(app_label, editor, first_state, second_state) self.assertTableExists(new_m2m_table) self.assertTableNotExists(original_m2m_table) # And test reversal with connection.schema_editor(atomic=atomic_rename) as editor: operation.database_backwards(app_label, editor, second_state, first_state) self.assertTableExists(original_m2m_table) self.assertTableNotExists(new_m2m_table) def test_alter_model_table_m2m_field(self): app_label = "test_talm2mfl" project_state = self.set_up_test_model(app_label, second_model=True) # Add the M2M field. project_state = self.apply_operations( app_label, project_state, operations=[ migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable"), ) ], ) m2m_table = f"{app_label}_pony_stables" self.assertColumnExists(m2m_table, "pony_id") self.assertColumnExists(m2m_table, "stable_id") # Point the M2M field to self. with_field_state = project_state.clone() operations = [ migrations.AlterField( model_name="Pony", name="stables", field=models.ManyToManyField("self"), ) ] project_state = self.apply_operations( app_label, project_state, operations=operations ) self.assertColumnExists(m2m_table, "from_pony_id") self.assertColumnExists(m2m_table, "to_pony_id") # Reversal. self.unapply_operations(app_label, with_field_state, operations=operations) self.assertColumnExists(m2m_table, "pony_id") self.assertColumnExists(m2m_table, "stable_id") def test_alter_field(self): """ Tests the AlterField operation. """ project_state = self.set_up_test_model("test_alfl") # Test the state alteration operation = migrations.AlterField( "Pony", "pink", models.IntegerField(null=True) ) self.assertEqual(operation.describe(), "Alter field pink on Pony") self.assertEqual(operation.migration_name_fragment, "alter_pony_pink") new_state = project_state.clone() operation.state_forwards("test_alfl", new_state) self.assertIs( project_state.models["test_alfl", "pony"].fields["pink"].null, False ) self.assertIs(new_state.models["test_alfl", "pony"].fields["pink"].null, True) # Test the database alteration self.assertColumnNotNull("test_alfl_pony", "pink") with connection.schema_editor() as editor: operation.database_forwards("test_alfl", editor, project_state, new_state) self.assertColumnNull("test_alfl_pony", "pink") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_alfl", editor, new_state, project_state) self.assertColumnNotNull("test_alfl_pony", "pink") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterField") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["field", "model_name", "name"]) def test_alter_field_add_database_default(self): app_label = "test_alfladd" project_state = self.set_up_test_model(app_label) operation = migrations.AlterField( "Pony", "weight", models.FloatField(db_default=4.5) ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) old_weight = project_state.models[app_label, "pony"].fields["weight"] self.assertIs(old_weight.db_default, models.NOT_PROVIDED) new_weight = new_state.models[app_label, "pony"].fields["weight"] self.assertEqual(new_weight.db_default, Value(4.5)) with self.assertRaises(IntegrityError), transaction.atomic(): project_state.apps.get_model(app_label, "pony").objects.create() # Alter field. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) pony = new_state.apps.get_model(app_label, "pony").objects.create() if not connection.features.can_return_columns_from_insert: pony.refresh_from_db() self.assertEqual(pony.weight, 4.5) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) with self.assertRaises(IntegrityError), transaction.atomic(): project_state.apps.get_model(app_label, "pony").objects.create() # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AlterField") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "field": new_weight, "model_name": "Pony", "name": "weight", }, ) def test_alter_field_change_default_to_database_default(self): """The AlterField operation changing default to db_default.""" app_label = "test_alflcdtdd" project_state = self.set_up_test_model(app_label) operation = migrations.AlterField( "Pony", "pink", models.IntegerField(db_default=4) ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) old_pink = project_state.models[app_label, "pony"].fields["pink"] self.assertEqual(old_pink.default, 3) self.assertIs(old_pink.db_default, models.NOT_PROVIDED) new_pink = new_state.models[app_label, "pony"].fields["pink"] self.assertIs(new_pink.default, models.NOT_PROVIDED) self.assertEqual(new_pink.db_default, Value(4)) pony = project_state.apps.get_model(app_label, "pony").objects.create(weight=1) self.assertEqual(pony.pink, 3) # Alter field. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) pony = new_state.apps.get_model(app_label, "pony").objects.create(weight=1) if not connection.features.can_return_columns_from_insert: pony.refresh_from_db() self.assertEqual(pony.pink, 4) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) pony = project_state.apps.get_model(app_label, "pony").objects.create(weight=1) self.assertEqual(pony.pink, 3) def test_alter_field_change_nullable_to_database_default_not_null(self): """ The AlterField operation changing a null field to db_default. """ app_label = "test_alflcntddnn" project_state = self.set_up_test_model(app_label) operation = migrations.AlterField( "Pony", "green", models.IntegerField(db_default=4) ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) old_green = project_state.models[app_label, "pony"].fields["green"] self.assertIs(old_green.db_default, models.NOT_PROVIDED) new_green = new_state.models[app_label, "pony"].fields["green"] self.assertEqual(new_green.db_default, Value(4)) old_pony = project_state.apps.get_model(app_label, "pony").objects.create( weight=1 ) self.assertIsNone(old_pony.green) # Alter field. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) old_pony.refresh_from_db() self.assertEqual(old_pony.green, 4) pony = new_state.apps.get_model(app_label, "pony").objects.create(weight=1) if not connection.features.can_return_columns_from_insert: pony.refresh_from_db() self.assertEqual(pony.green, 4) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) pony = project_state.apps.get_model(app_label, "pony").objects.create(weight=1) self.assertIsNone(pony.green) @skipIfDBFeature("interprets_empty_strings_as_nulls") def test_alter_field_change_blank_nullable_database_default_to_not_null(self): app_label = "test_alflcbnddnn" table_name = f"{app_label}_pony" project_state = self.set_up_test_model(app_label) default = "Yellow" operation = migrations.AlterField( "Pony", "yellow", models.CharField(blank=True, db_default=default, max_length=20), ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertColumnNull(table_name, "yellow") pony = project_state.apps.get_model(app_label, "pony").objects.create( weight=1, yellow=None ) self.assertIsNone(pony.yellow) # Alter field. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnNotNull(table_name, "yellow") pony.refresh_from_db() self.assertEqual(pony.yellow, default) pony = new_state.apps.get_model(app_label, "pony").objects.create(weight=1) if not connection.features.can_return_columns_from_insert: pony.refresh_from_db() self.assertEqual(pony.yellow, default) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertColumnNull(table_name, "yellow") pony = project_state.apps.get_model(app_label, "pony").objects.create( weight=1, yellow=None ) self.assertIsNone(pony.yellow) def test_alter_field_add_db_column_noop(self): """ AlterField operation is a noop when adding only a db_column and the column name is not changed. """ app_label = "test_afadbn" project_state = self.set_up_test_model(app_label, related_model=True) pony_table = "%s_pony" % app_label new_state = project_state.clone() operation = migrations.AlterField( "Pony", "weight", models.FloatField(db_column="weight") ) operation.state_forwards(app_label, new_state) self.assertIsNone( project_state.models[app_label, "pony"].fields["weight"].db_column, ) self.assertEqual( new_state.models[app_label, "pony"].fields["weight"].db_column, "weight", ) self.assertColumnExists(pony_table, "weight") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnExists(pony_table, "weight") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_backwards( app_label, editor, new_state, project_state ) self.assertColumnExists(pony_table, "weight") rider_table = "%s_rider" % app_label new_state = project_state.clone() operation = migrations.AlterField( "Rider", "pony", models.ForeignKey("Pony", models.CASCADE, db_column="pony_id"), ) operation.state_forwards(app_label, new_state) self.assertIsNone( project_state.models[app_label, "rider"].fields["pony"].db_column, ) self.assertIs( new_state.models[app_label, "rider"].fields["pony"].db_column, "pony_id", ) self.assertColumnExists(rider_table, "pony_id") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnExists(rider_table, "pony_id") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards(app_label, editor, new_state, project_state) self.assertColumnExists(rider_table, "pony_id") @skipUnlessDBFeature("supports_comments") def test_alter_model_table_comment(self): app_label = "test_almotaco" project_state = self.set_up_test_model(app_label) pony_table = f"{app_label}_pony" # Add table comment. operation = migrations.AlterModelTableComment("Pony", "Custom pony comment") self.assertEqual(operation.describe(), "Alter Pony table comment") self.assertEqual(operation.migration_name_fragment, "alter_pony_table_comment") new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( new_state.models[app_label, "pony"].options["db_table_comment"], "Custom pony comment", ) self.assertTableCommentNotExists(pony_table) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertTableComment(pony_table, "Custom pony comment") # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertTableCommentNotExists(pony_table) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AlterModelTableComment") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Pony", "table_comment": "Custom pony comment"} ) def test_alter_field_pk(self): """ The AlterField operation on primary keys (things like PostgreSQL's SERIAL weirdness). """ project_state = self.set_up_test_model("test_alflpk") # Test the state alteration operation = migrations.AlterField( "Pony", "id", models.IntegerField(primary_key=True) ) new_state = project_state.clone() operation.state_forwards("test_alflpk", new_state) self.assertIsInstance( project_state.models["test_alflpk", "pony"].fields["id"], models.AutoField, ) self.assertIsInstance( new_state.models["test_alflpk", "pony"].fields["id"], models.IntegerField, ) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_alflpk", editor, project_state, new_state) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alflpk", editor, new_state, project_state ) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_field_pk_fk(self): """ Tests the AlterField operation on primary keys changes any FKs pointing to it. """ project_state = self.set_up_test_model("test_alflpkfk", related_model=True) project_state = self.apply_operations( "test_alflpkfk", project_state, [ migrations.CreateModel( "Stable", fields=[ ("ponies", models.ManyToManyField("Pony")), ], ), migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable"), ), ], ) # Test the state alteration operation = migrations.AlterField( "Pony", "id", models.FloatField(primary_key=True) ) new_state = project_state.clone() operation.state_forwards("test_alflpkfk", new_state) self.assertIsInstance( project_state.models["test_alflpkfk", "pony"].fields["id"], models.AutoField, ) self.assertIsInstance( new_state.models["test_alflpkfk", "pony"].fields["id"], models.FloatField, ) def assertIdTypeEqualsFkType(): with connection.cursor() as cursor: id_type, id_null = [ (c.type_code, c.null_ok) for c in connection.introspection.get_table_description( cursor, "test_alflpkfk_pony" ) if c.name == "id" ][0] fk_type, fk_null = [ (c.type_code, c.null_ok) for c in connection.introspection.get_table_description( cursor, "test_alflpkfk_rider" ) if c.name == "pony_id" ][0] m2m_fk_type, m2m_fk_null = [ (c.type_code, c.null_ok) for c in connection.introspection.get_table_description( cursor, "test_alflpkfk_pony_stables", ) if c.name == "pony_id" ][0] remote_m2m_fk_type, remote_m2m_fk_null = [ (c.type_code, c.null_ok) for c in connection.introspection.get_table_description( cursor, "test_alflpkfk_stable_ponies", ) if c.name == "pony_id" ][0] self.assertEqual(id_type, fk_type) self.assertEqual(id_type, m2m_fk_type) self.assertEqual(id_type, remote_m2m_fk_type) self.assertEqual(id_null, fk_null) self.assertEqual(id_null, m2m_fk_null) self.assertEqual(id_null, remote_m2m_fk_null) assertIdTypeEqualsFkType() # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_alflpkfk", editor, project_state, new_state ) assertIdTypeEqualsFkType() if connection.features.supports_foreign_keys: self.assertFKExists( "test_alflpkfk_pony_stables", ["pony_id"], ("test_alflpkfk_pony", "id"), ) self.assertFKExists( "test_alflpkfk_stable_ponies", ["pony_id"], ("test_alflpkfk_pony", "id"), ) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alflpkfk", editor, new_state, project_state ) assertIdTypeEqualsFkType() if connection.features.supports_foreign_keys: self.assertFKExists( "test_alflpkfk_pony_stables", ["pony_id"], ("test_alflpkfk_pony", "id"), ) self.assertFKExists( "test_alflpkfk_stable_ponies", ["pony_id"], ("test_alflpkfk_pony", "id"), ) @skipUnlessDBFeature("supports_collation_on_charfield", "supports_foreign_keys") def test_alter_field_pk_fk_db_collation(self): """ AlterField operation of db_collation on primary keys changes any FKs pointing to it. """ collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") app_label = "test_alflpkfkdbc" project_state = self.apply_operations( app_label, ProjectState(), [ migrations.CreateModel( "Pony", [ ("id", models.CharField(primary_key=True, max_length=10)), ], ), migrations.CreateModel( "Rider", [ ("pony", models.ForeignKey("Pony", models.CASCADE)), ], ), migrations.CreateModel( "Stable", [ ("ponies", models.ManyToManyField("Pony")), ], ), ], ) # State alteration. operation = migrations.AlterField( "Pony", "id", models.CharField( primary_key=True, max_length=10, db_collation=collation, ), ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Database alteration. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnCollation(f"{app_label}_pony", "id", collation) self.assertColumnCollation(f"{app_label}_rider", "pony_id", collation) self.assertColumnCollation(f"{app_label}_stable_ponies", "pony_id", collation) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) def test_alter_field_pk_mti_fk(self): app_label = "test_alflpkmtifk" project_state = self.set_up_test_model(app_label, mti_model=True) project_state = self.apply_operations( app_label, project_state, [ migrations.CreateModel( "ShetlandRider", fields=[ ( "pony", models.ForeignKey( f"{app_label}.ShetlandPony", models.CASCADE ), ), ], ), ], ) operation = migrations.AlterField( "Pony", "id", models.BigAutoField(primary_key=True), ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertIsInstance( new_state.models[app_label, "pony"].fields["id"], models.BigAutoField, ) def _get_column_id_type(cursor, table, column): return [ c.type_code for c in connection.introspection.get_table_description( cursor, f"{app_label}_{table}", ) if c.name == column ][0] def assertIdTypeEqualsMTIFkType(): with connection.cursor() as cursor: parent_id_type = _get_column_id_type(cursor, "pony", "id") child_id_type = _get_column_id_type( cursor, "shetlandpony", "pony_ptr_id" ) mti_id_type = _get_column_id_type(cursor, "shetlandrider", "pony_id") self.assertEqual(parent_id_type, child_id_type) self.assertEqual(parent_id_type, mti_id_type) assertIdTypeEqualsMTIFkType() # Alter primary key. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) assertIdTypeEqualsMTIFkType() if connection.features.supports_foreign_keys: self.assertFKExists( f"{app_label}_shetlandpony", ["pony_ptr_id"], (f"{app_label}_pony", "id"), ) self.assertFKExists( f"{app_label}_shetlandrider", ["pony_id"], (f"{app_label}_shetlandpony", "pony_ptr_id"), ) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) assertIdTypeEqualsMTIFkType() if connection.features.supports_foreign_keys: self.assertFKExists( f"{app_label}_shetlandpony", ["pony_ptr_id"], (f"{app_label}_pony", "id"), ) self.assertFKExists( f"{app_label}_shetlandrider", ["pony_id"], (f"{app_label}_shetlandpony", "pony_ptr_id"), ) def test_alter_field_pk_mti_and_fk_to_base(self): app_label = "test_alflpkmtiftb" project_state = self.set_up_test_model( app_label, mti_model=True, related_model=True, ) operation = migrations.AlterField( "Pony", "id", models.BigAutoField(primary_key=True), ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertIsInstance( new_state.models[app_label, "pony"].fields["id"], models.BigAutoField, ) def _get_column_id_type(cursor, table, column): return [ c.type_code for c in connection.introspection.get_table_description( cursor, f"{app_label}_{table}", ) if c.name == column ][0] def assertIdTypeEqualsMTIFkType(): with connection.cursor() as cursor: parent_id_type = _get_column_id_type(cursor, "pony", "id") fk_id_type = _get_column_id_type(cursor, "rider", "pony_id") child_id_type = _get_column_id_type( cursor, "shetlandpony", "pony_ptr_id" ) self.assertEqual(parent_id_type, child_id_type) self.assertEqual(parent_id_type, fk_id_type) assertIdTypeEqualsMTIFkType() # Alter primary key. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) assertIdTypeEqualsMTIFkType() if connection.features.supports_foreign_keys: self.assertFKExists( f"{app_label}_shetlandpony", ["pony_ptr_id"], (f"{app_label}_pony", "id"), ) self.assertFKExists( f"{app_label}_rider", ["pony_id"], (f"{app_label}_pony", "id"), ) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) assertIdTypeEqualsMTIFkType() if connection.features.supports_foreign_keys: self.assertFKExists( f"{app_label}_shetlandpony", ["pony_ptr_id"], (f"{app_label}_pony", "id"), ) self.assertFKExists( f"{app_label}_rider", ["pony_id"], (f"{app_label}_pony", "id"), ) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_field_reloads_state_on_fk_with_to_field_target_type_change(self): app_label = "test_alflrsfkwtflttc" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ("code", models.IntegerField(unique=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ( "rider", models.ForeignKey( "%s.Rider" % app_label, models.CASCADE, to_field="code" ), ), ], ), ], ) operation = migrations.AlterField( "Rider", "code", models.CharField(max_length=100, unique=True), ) self.apply_operations(app_label, project_state, operations=[operation]) id_type, id_null = [ (c.type_code, c.null_ok) for c in self.get_table_description("%s_rider" % app_label) if c.name == "code" ][0] fk_type, fk_null = [ (c.type_code, c.null_ok) for c in self.get_table_description("%s_pony" % app_label) if c.name == "rider_id" ][0] self.assertEqual(id_type, fk_type) self.assertEqual(id_null, fk_null) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_field_reloads_state_fk_with_to_field_related_name_target_type_change( self, ): app_label = "test_alflrsfkwtflrnttc" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ("code", models.PositiveIntegerField(unique=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ( "rider", models.ForeignKey( "%s.Rider" % app_label, models.CASCADE, to_field="code", related_name="+", ), ), ], ), ], ) operation = migrations.AlterField( "Rider", "code", models.CharField(max_length=100, unique=True), ) self.apply_operations(app_label, project_state, operations=[operation]) def test_alter_field_reloads_state_on_fk_target_changes(self): """ If AlterField doesn't reload state appropriately, the second AlterField crashes on MySQL due to not dropping the PonyRider.pony foreign key constraint before modifying the column. """ app_label = "alter_alter_field_reloads_state_on_fk_target_changes" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ( "rider", models.ForeignKey("%s.Rider" % app_label, models.CASCADE), ), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ( "pony", models.ForeignKey("%s.Pony" % app_label, models.CASCADE), ), ], ), ], ) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.AlterField( "Rider", "id", models.CharField(primary_key=True, max_length=99) ), migrations.AlterField( "Pony", "id", models.CharField(primary_key=True, max_length=99) ), ], ) def test_alter_field_reloads_state_on_fk_with_to_field_target_changes(self): """ If AlterField doesn't reload state appropriately, the second AlterField crashes on MySQL due to not dropping the PonyRider.pony foreign key constraint before modifying the column. """ app_label = "alter_alter_field_reloads_state_on_fk_with_to_field_target_changes" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ("slug", models.CharField(unique=True, max_length=100)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ( "rider", models.ForeignKey( "%s.Rider" % app_label, models.CASCADE, to_field="slug" ), ), ("slug", models.CharField(unique=True, max_length=100)), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ( "pony", models.ForeignKey( "%s.Pony" % app_label, models.CASCADE, to_field="slug" ), ), ], ), ], ) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.AlterField( "Rider", "slug", models.CharField(unique=True, max_length=99) ), migrations.AlterField( "Pony", "slug", models.CharField(unique=True, max_length=99) ), ], ) def test_alter_field_pk_fk_char_to_int(self): app_label = "alter_field_pk_fk_char_to_int" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( name="Parent", fields=[ ("id", models.CharField(max_length=255, primary_key=True)), ], ), migrations.CreateModel( name="Child", fields=[ ("id", models.BigAutoField(primary_key=True)), ( "parent", models.ForeignKey( f"{app_label}.Parent", on_delete=models.CASCADE, ), ), ], ), ], ) self.apply_operations( app_label, project_state, operations=[ migrations.AlterField( model_name="parent", name="id", field=models.BigIntegerField(primary_key=True), ), ], ) def test_rename_field_reloads_state_on_fk_target_changes(self): """ If RenameField doesn't reload state appropriately, the AlterField crashes on MySQL due to not dropping the PonyRider.pony foreign key constraint before modifying the column. """ app_label = "alter_rename_field_reloads_state_on_fk_target_changes" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ( "rider", models.ForeignKey("%s.Rider" % app_label, models.CASCADE), ), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ( "pony", models.ForeignKey("%s.Pony" % app_label, models.CASCADE), ), ], ), ], ) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameField("Rider", "id", "id2"), migrations.AlterField( "Pony", "id", models.CharField(primary_key=True, max_length=99) ), ], atomic=connection.features.supports_atomic_references_rename, ) def test_rename_field(self): """ Tests the RenameField operation. """ project_state = self.set_up_test_model("test_rnfl") operation = migrations.RenameField("Pony", "pink", "blue") self.assertEqual(operation.describe(), "Rename field pink on Pony to blue") self.assertEqual(operation.migration_name_fragment, "rename_pink_pony_blue") new_state = project_state.clone() operation.state_forwards("test_rnfl", new_state) self.assertIn("blue", new_state.models["test_rnfl", "pony"].fields) self.assertNotIn("pink", new_state.models["test_rnfl", "pony"].fields) # Rename field. self.assertColumnExists("test_rnfl_pony", "pink") self.assertColumnNotExists("test_rnfl_pony", "blue") with connection.schema_editor() as editor: operation.database_forwards("test_rnfl", editor, project_state, new_state) self.assertColumnExists("test_rnfl_pony", "blue") self.assertColumnNotExists("test_rnfl_pony", "pink") # Reversal. with connection.schema_editor() as editor: operation.database_backwards("test_rnfl", editor, new_state, project_state) self.assertColumnExists("test_rnfl_pony", "pink") self.assertColumnNotExists("test_rnfl_pony", "blue") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RenameField") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "old_name": "pink", "new_name": "blue"}, ) def test_rename_field_unique_together(self): project_state = self.set_up_test_model("test_rnflut", unique_together=True) operation = migrations.RenameField("Pony", "pink", "blue") new_state = project_state.clone() operation.state_forwards("test_rnflut", new_state) # unique_together has the renamed column. self.assertIn( "blue", new_state.models["test_rnflut", "pony"].options["unique_together"][0], ) self.assertNotIn( "pink", new_state.models["test_rnflut", "pony"].options["unique_together"][0], ) # Rename field. self.assertColumnExists("test_rnflut_pony", "pink") self.assertColumnNotExists("test_rnflut_pony", "blue") with connection.schema_editor() as editor: operation.database_forwards("test_rnflut", editor, project_state, new_state) self.assertColumnExists("test_rnflut_pony", "blue") self.assertColumnNotExists("test_rnflut_pony", "pink") # The unique constraint has been ported over. with connection.cursor() as cursor: cursor.execute("INSERT INTO test_rnflut_pony (blue, weight) VALUES (1, 1)") with self.assertRaises(IntegrityError): with atomic(): cursor.execute( "INSERT INTO test_rnflut_pony (blue, weight) VALUES (1, 1)" ) cursor.execute("DELETE FROM test_rnflut_pony") # Reversal. with connection.schema_editor() as editor: operation.database_backwards( "test_rnflut", editor, new_state, project_state ) self.assertColumnExists("test_rnflut_pony", "pink") self.assertColumnNotExists("test_rnflut_pony", "blue") @ignore_warnings(category=RemovedInDjango51Warning) def test_rename_field_index_together(self): project_state = self.set_up_test_model("test_rnflit", index_together=True) operation = migrations.RenameField("Pony", "pink", "blue") new_state = project_state.clone() operation.state_forwards("test_rnflit", new_state) self.assertIn("blue", new_state.models["test_rnflit", "pony"].fields) self.assertNotIn("pink", new_state.models["test_rnflit", "pony"].fields) # index_together has the renamed column. self.assertIn( "blue", new_state.models["test_rnflit", "pony"].options["index_together"][0] ) self.assertNotIn( "pink", new_state.models["test_rnflit", "pony"].options["index_together"][0] ) # Rename field. self.assertColumnExists("test_rnflit_pony", "pink") self.assertColumnNotExists("test_rnflit_pony", "blue") with connection.schema_editor() as editor: operation.database_forwards("test_rnflit", editor, project_state, new_state) self.assertColumnExists("test_rnflit_pony", "blue") self.assertColumnNotExists("test_rnflit_pony", "pink") # The index constraint has been ported over. self.assertIndexExists("test_rnflit_pony", ["weight", "blue"]) # Reversal. with connection.schema_editor() as editor: operation.database_backwards( "test_rnflit", editor, new_state, project_state ) self.assertIndexExists("test_rnflit_pony", ["weight", "pink"]) def test_rename_field_with_db_column(self): project_state = self.apply_operations( "test_rfwdbc", ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField(db_column="db_field")), ( "fk_field", models.ForeignKey( "Pony", models.CASCADE, db_column="db_fk_field", ), ), ], ), ], ) new_state = project_state.clone() operation = migrations.RenameField("Pony", "field", "renamed_field") operation.state_forwards("test_rfwdbc", new_state) self.assertIn("renamed_field", new_state.models["test_rfwdbc", "pony"].fields) self.assertNotIn("field", new_state.models["test_rfwdbc", "pony"].fields) self.assertColumnExists("test_rfwdbc_pony", "db_field") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards( "test_rfwdbc", editor, project_state, new_state ) self.assertColumnExists("test_rfwdbc_pony", "db_field") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_backwards( "test_rfwdbc", editor, new_state, project_state ) self.assertColumnExists("test_rfwdbc_pony", "db_field") new_state = project_state.clone() operation = migrations.RenameField("Pony", "fk_field", "renamed_fk_field") operation.state_forwards("test_rfwdbc", new_state) self.assertIn( "renamed_fk_field", new_state.models["test_rfwdbc", "pony"].fields ) self.assertNotIn("fk_field", new_state.models["test_rfwdbc", "pony"].fields) self.assertColumnExists("test_rfwdbc_pony", "db_fk_field") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards( "test_rfwdbc", editor, project_state, new_state ) self.assertColumnExists("test_rfwdbc_pony", "db_fk_field") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_backwards( "test_rfwdbc", editor, new_state, project_state ) self.assertColumnExists("test_rfwdbc_pony", "db_fk_field") def test_rename_field_case(self): project_state = self.apply_operations( "test_rfmx", ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField()), ], ), ], ) new_state = project_state.clone() operation = migrations.RenameField("Pony", "field", "FiElD") operation.state_forwards("test_rfmx", new_state) self.assertIn("FiElD", new_state.models["test_rfmx", "pony"].fields) self.assertColumnExists("test_rfmx_pony", "field") with connection.schema_editor() as editor: operation.database_forwards("test_rfmx", editor, project_state, new_state) self.assertColumnExists( "test_rfmx_pony", connection.introspection.identifier_converter("FiElD"), ) with connection.schema_editor() as editor: operation.database_backwards("test_rfmx", editor, new_state, project_state) self.assertColumnExists("test_rfmx_pony", "field") def test_rename_missing_field(self): state = ProjectState() state.add_model(ModelState("app", "model", [])) with self.assertRaisesMessage( FieldDoesNotExist, "app.model has no field named 'field'" ): migrations.RenameField("model", "field", "new_field").state_forwards( "app", state ) def test_rename_referenced_field_state_forward(self): state = ProjectState() state.add_model( ModelState( "app", "Model", [ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField(unique=True)), ], ) ) state.add_model( ModelState( "app", "OtherModel", [ ("id", models.AutoField(primary_key=True)), ( "fk", models.ForeignKey("Model", models.CASCADE, to_field="field"), ), ( "fo", models.ForeignObject( "Model", models.CASCADE, from_fields=("fk",), to_fields=("field",), ), ), ], ) ) operation = migrations.RenameField("Model", "field", "renamed") new_state = state.clone() operation.state_forwards("app", new_state) self.assertEqual( new_state.models["app", "othermodel"].fields["fk"].remote_field.field_name, "renamed", ) self.assertEqual( new_state.models["app", "othermodel"].fields["fk"].from_fields, ["self"] ) self.assertEqual( new_state.models["app", "othermodel"].fields["fk"].to_fields, ("renamed",) ) self.assertEqual( new_state.models["app", "othermodel"].fields["fo"].from_fields, ("fk",) ) self.assertEqual( new_state.models["app", "othermodel"].fields["fo"].to_fields, ("renamed",) ) operation = migrations.RenameField("OtherModel", "fk", "renamed_fk") new_state = state.clone() operation.state_forwards("app", new_state) self.assertEqual( new_state.models["app", "othermodel"] .fields["renamed_fk"] .remote_field.field_name, "renamed", ) self.assertEqual( new_state.models["app", "othermodel"].fields["renamed_fk"].from_fields, ("self",), ) self.assertEqual( new_state.models["app", "othermodel"].fields["renamed_fk"].to_fields, ("renamed",), ) self.assertEqual( new_state.models["app", "othermodel"].fields["fo"].from_fields, ("renamed_fk",), ) self.assertEqual( new_state.models["app", "othermodel"].fields["fo"].to_fields, ("renamed",) ) def test_alter_unique_together(self): """ Tests the AlterUniqueTogether operation. """ project_state = self.set_up_test_model("test_alunto") # Test the state alteration operation = migrations.AlterUniqueTogether("Pony", [("pink", "weight")]) self.assertEqual( operation.describe(), "Alter unique_together for Pony (1 constraint(s))" ) self.assertEqual( operation.migration_name_fragment, "alter_pony_unique_together", ) new_state = project_state.clone() operation.state_forwards("test_alunto", new_state) self.assertEqual( len( project_state.models["test_alunto", "pony"].options.get( "unique_together", set() ) ), 0, ) self.assertEqual( len( new_state.models["test_alunto", "pony"].options.get( "unique_together", set() ) ), 1, ) # Make sure we can insert duplicate rows with connection.cursor() as cursor: cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") cursor.execute("DELETE FROM test_alunto_pony") # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_alunto", editor, project_state, new_state ) cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") with self.assertRaises(IntegrityError): with atomic(): cursor.execute( "INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)" ) cursor.execute("DELETE FROM test_alunto_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alunto", editor, new_state, project_state ) cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") cursor.execute("DELETE FROM test_alunto_pony") # Test flat unique_together operation = migrations.AlterUniqueTogether("Pony", ("pink", "weight")) operation.state_forwards("test_alunto", new_state) self.assertEqual( len( new_state.models["test_alunto", "pony"].options.get( "unique_together", set() ) ), 1, ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterUniqueTogether") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Pony", "unique_together": {("pink", "weight")}} ) def test_alter_unique_together_remove(self): operation = migrations.AlterUniqueTogether("Pony", None) self.assertEqual( operation.describe(), "Alter unique_together for Pony (0 constraint(s))" ) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") def test_remove_unique_together_on_pk_field(self): app_label = "test_rutopkf" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[("id", models.AutoField(primary_key=True))], options={"unique_together": {("id",)}}, ), ], ) table_name = f"{app_label}_pony" pk_constraint_name = f"{table_name}_pkey" unique_together_constraint_name = f"{table_name}_id_fb61f881_uniq" self.assertConstraintExists(table_name, pk_constraint_name, value=False) self.assertConstraintExists( table_name, unique_together_constraint_name, value=False ) new_state = project_state.clone() operation = migrations.AlterUniqueTogether("Pony", set()) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertConstraintExists(table_name, pk_constraint_name, value=False) self.assertConstraintNotExists(table_name, unique_together_constraint_name) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") def test_remove_unique_together_on_unique_field(self): app_label = "test_rutouf" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=30, unique=True)), ], options={"unique_together": {("name",)}}, ), ], ) table_name = f"{app_label}_pony" unique_constraint_name = f"{table_name}_name_key" unique_together_constraint_name = f"{table_name}_name_694f3b9f_uniq" self.assertConstraintExists(table_name, unique_constraint_name, value=False) self.assertConstraintExists( table_name, unique_together_constraint_name, value=False ) new_state = project_state.clone() operation = migrations.AlterUniqueTogether("Pony", set()) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertConstraintExists(table_name, unique_constraint_name, value=False) self.assertConstraintNotExists(table_name, unique_together_constraint_name) def test_add_index(self): """ Test the AddIndex operation. """ project_state = self.set_up_test_model("test_adin") msg = ( "Indexes passed to AddIndex operations require a name argument. " "<Index: fields=['pink']> doesn't have one." ) with self.assertRaisesMessage(ValueError, msg): migrations.AddIndex("Pony", models.Index(fields=["pink"])) index = models.Index(fields=["pink"], name="test_adin_pony_pink_idx") operation = migrations.AddIndex("Pony", index) self.assertEqual( operation.describe(), "Create index test_adin_pony_pink_idx on field(s) pink of model Pony", ) self.assertEqual( operation.migration_name_fragment, "pony_test_adin_pony_pink_idx", ) new_state = project_state.clone() operation.state_forwards("test_adin", new_state) # Test the database alteration self.assertEqual( len(new_state.models["test_adin", "pony"].options["indexes"]), 1 ) self.assertIndexNotExists("test_adin_pony", ["pink"]) with connection.schema_editor() as editor: operation.database_forwards("test_adin", editor, project_state, new_state) self.assertIndexExists("test_adin_pony", ["pink"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_adin", editor, new_state, project_state) self.assertIndexNotExists("test_adin_pony", ["pink"]) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AddIndex") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "index": index}) def test_remove_index(self): """ Test the RemoveIndex operation. """ project_state = self.set_up_test_model("test_rmin", multicol_index=True) self.assertTableExists("test_rmin_pony") self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) operation = migrations.RemoveIndex("Pony", "pony_test_idx") self.assertEqual(operation.describe(), "Remove index pony_test_idx from Pony") self.assertEqual( operation.migration_name_fragment, "remove_pony_pony_test_idx", ) new_state = project_state.clone() operation.state_forwards("test_rmin", new_state) # Test the state alteration self.assertEqual( len(new_state.models["test_rmin", "pony"].options["indexes"]), 0 ) self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_rmin", editor, project_state, new_state) self.assertIndexNotExists("test_rmin_pony", ["pink", "weight"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_rmin", editor, new_state, project_state) self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveIndex") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "name": "pony_test_idx"}) # Also test a field dropped with index - sqlite remake issue operations = [ migrations.RemoveIndex("Pony", "pony_test_idx"), migrations.RemoveField("Pony", "pink"), ] self.assertColumnExists("test_rmin_pony", "pink") self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) # Test database alteration new_state = project_state.clone() self.apply_operations("test_rmin", new_state, operations=operations) self.assertColumnNotExists("test_rmin_pony", "pink") self.assertIndexNotExists("test_rmin_pony", ["pink", "weight"]) # And test reversal self.unapply_operations("test_rmin", project_state, operations=operations) self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) def test_rename_index(self): app_label = "test_rnin" project_state = self.set_up_test_model(app_label, index=True) table_name = app_label + "_pony" self.assertIndexNameExists(table_name, "pony_pink_idx") self.assertIndexNameNotExists(table_name, "new_pony_test_idx") operation = migrations.RenameIndex( "Pony", new_name="new_pony_test_idx", old_name="pony_pink_idx" ) self.assertEqual( operation.describe(), "Rename index pony_pink_idx on Pony to new_pony_test_idx", ) self.assertEqual( operation.migration_name_fragment, "rename_pony_pink_idx_new_pony_test_idx", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Rename index. expected_queries = 1 if connection.features.can_rename_index else 2 with connection.schema_editor() as editor, self.assertNumQueries( expected_queries ): operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameNotExists(table_name, "pony_pink_idx") self.assertIndexNameExists(table_name, "new_pony_test_idx") # Reversal. with connection.schema_editor() as editor, self.assertNumQueries( expected_queries ): operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, "pony_pink_idx") self.assertIndexNameNotExists(table_name, "new_pony_test_idx") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RenameIndex") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "old_name": "pony_pink_idx", "new_name": "new_pony_test_idx", }, ) def test_rename_index_arguments(self): msg = "RenameIndex.old_name and old_fields are mutually exclusive." with self.assertRaisesMessage(ValueError, msg): migrations.RenameIndex( "Pony", new_name="new_idx_name", old_name="old_idx_name", old_fields=("weight", "pink"), ) msg = "RenameIndex requires one of old_name and old_fields arguments to be set." with self.assertRaisesMessage(ValueError, msg): migrations.RenameIndex("Pony", new_name="new_idx_name") @ignore_warnings(category=RemovedInDjango51Warning) def test_rename_index_unnamed_index(self): app_label = "test_rninui" project_state = self.set_up_test_model(app_label, index_together=True) table_name = app_label + "_pony" self.assertIndexNameNotExists(table_name, "new_pony_test_idx") operation = migrations.RenameIndex( "Pony", new_name="new_pony_test_idx", old_fields=("weight", "pink") ) self.assertEqual( operation.describe(), "Rename unnamed index for ('weight', 'pink') on Pony to new_pony_test_idx", ) self.assertEqual( operation.migration_name_fragment, "rename_pony_weight_pink_new_pony_test_idx", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Rename index. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameExists(table_name, "new_pony_test_idx") # Reverse is a no-op. with connection.schema_editor() as editor, self.assertNumQueries(0): operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, "new_pony_test_idx") # Reapply, RenameIndex operation is a noop when the old and new name # match. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, "new_pony_test_idx") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RenameIndex") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "new_name": "new_pony_test_idx", "old_fields": ("weight", "pink"), }, ) def test_rename_index_unknown_unnamed_index(self): app_label = "test_rninuui" project_state = self.set_up_test_model(app_label) operation = migrations.RenameIndex( "Pony", new_name="new_pony_test_idx", old_fields=("weight", "pink") ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) msg = "Found wrong number (0) of indexes for test_rninuui_pony(weight, pink)." with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, msg): operation.database_forwards(app_label, editor, project_state, new_state) def test_add_index_state_forwards(self): project_state = self.set_up_test_model("test_adinsf") index = models.Index(fields=["pink"], name="test_adinsf_pony_pink_idx") old_model = project_state.apps.get_model("test_adinsf", "Pony") new_state = project_state.clone() operation = migrations.AddIndex("Pony", index) operation.state_forwards("test_adinsf", new_state) new_model = new_state.apps.get_model("test_adinsf", "Pony") self.assertIsNot(old_model, new_model) def test_remove_index_state_forwards(self): project_state = self.set_up_test_model("test_rminsf") index = models.Index(fields=["pink"], name="test_rminsf_pony_pink_idx") migrations.AddIndex("Pony", index).state_forwards("test_rminsf", project_state) old_model = project_state.apps.get_model("test_rminsf", "Pony") new_state = project_state.clone() operation = migrations.RemoveIndex("Pony", "test_rminsf_pony_pink_idx") operation.state_forwards("test_rminsf", new_state) new_model = new_state.apps.get_model("test_rminsf", "Pony") self.assertIsNot(old_model, new_model) def test_rename_index_state_forwards(self): app_label = "test_rnidsf" project_state = self.set_up_test_model(app_label, index=True) old_model = project_state.apps.get_model(app_label, "Pony") new_state = project_state.clone() operation = migrations.RenameIndex( "Pony", new_name="new_pony_pink_idx", old_name="pony_pink_idx" ) operation.state_forwards(app_label, new_state) new_model = new_state.apps.get_model(app_label, "Pony") self.assertIsNot(old_model, new_model) self.assertEqual(new_model._meta.indexes[0].name, "new_pony_pink_idx") @ignore_warnings(category=RemovedInDjango51Warning) def test_rename_index_state_forwards_unnamed_index(self): app_label = "test_rnidsfui" project_state = self.set_up_test_model(app_label, index_together=True) old_model = project_state.apps.get_model(app_label, "Pony") new_state = project_state.clone() operation = migrations.RenameIndex( "Pony", new_name="new_pony_pink_idx", old_fields=("weight", "pink") ) operation.state_forwards(app_label, new_state) new_model = new_state.apps.get_model(app_label, "Pony") self.assertIsNot(old_model, new_model) self.assertEqual(new_model._meta.index_together, tuple()) self.assertEqual(new_model._meta.indexes[0].name, "new_pony_pink_idx") @skipUnlessDBFeature("supports_expression_indexes") def test_add_func_index(self): app_label = "test_addfuncin" index_name = f"{app_label}_pony_abs_idx" table_name = f"{app_label}_pony" project_state = self.set_up_test_model(app_label) index = models.Index(Abs("weight"), name=index_name) operation = migrations.AddIndex("Pony", index) self.assertEqual( operation.describe(), "Create index test_addfuncin_pony_abs_idx on Abs(F(weight)) on model Pony", ) self.assertEqual( operation.migration_name_fragment, "pony_test_addfuncin_pony_abs_idx", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual(len(new_state.models[app_label, "pony"].options["indexes"]), 1) self.assertIndexNameNotExists(table_name, index_name) # Add index. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameExists(table_name, index_name) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameNotExists(table_name, index_name) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddIndex") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "index": index}) @skipUnlessDBFeature("supports_expression_indexes") def test_remove_func_index(self): app_label = "test_rmfuncin" index_name = f"{app_label}_pony_abs_idx" table_name = f"{app_label}_pony" project_state = self.set_up_test_model( app_label, indexes=[ models.Index(Abs("weight"), name=index_name), ], ) self.assertTableExists(table_name) self.assertIndexNameExists(table_name, index_name) operation = migrations.RemoveIndex("Pony", index_name) self.assertEqual( operation.describe(), "Remove index test_rmfuncin_pony_abs_idx from Pony", ) self.assertEqual( operation.migration_name_fragment, "remove_pony_test_rmfuncin_pony_abs_idx", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual(len(new_state.models[app_label, "pony"].options["indexes"]), 0) # Remove index. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameNotExists(table_name, index_name) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, index_name) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveIndex") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "name": index_name}) @skipUnlessDBFeature("supports_expression_indexes") def test_alter_field_with_func_index(self): app_label = "test_alfuncin" index_name = f"{app_label}_pony_idx" table_name = f"{app_label}_pony" project_state = self.set_up_test_model( app_label, indexes=[models.Index(Abs("pink"), name=index_name)], ) operation = migrations.AlterField( "Pony", "pink", models.IntegerField(null=True) ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameExists(table_name, index_name) with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, index_name) def test_alter_field_with_index(self): """ Test AlterField operation with an index to ensure indexes created via Meta.indexes don't get dropped with sqlite3 remake. """ project_state = self.set_up_test_model("test_alflin", index=True) operation = migrations.AlterField( "Pony", "pink", models.IntegerField(null=True) ) new_state = project_state.clone() operation.state_forwards("test_alflin", new_state) # Test the database alteration self.assertColumnNotNull("test_alflin_pony", "pink") with connection.schema_editor() as editor: operation.database_forwards("test_alflin", editor, project_state, new_state) # Index hasn't been dropped self.assertIndexExists("test_alflin_pony", ["pink"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alflin", editor, new_state, project_state ) # Ensure the index is still there self.assertIndexExists("test_alflin_pony", ["pink"]) @ignore_warnings(category=RemovedInDjango51Warning) def test_alter_index_together(self): """ Tests the AlterIndexTogether operation. """ project_state = self.set_up_test_model("test_alinto") # Test the state alteration operation = migrations.AlterIndexTogether("Pony", [("pink", "weight")]) self.assertEqual( operation.describe(), "Alter index_together for Pony (1 constraint(s))" ) self.assertEqual( operation.migration_name_fragment, "alter_pony_index_together", ) new_state = project_state.clone() operation.state_forwards("test_alinto", new_state) self.assertEqual( len( project_state.models["test_alinto", "pony"].options.get( "index_together", set() ) ), 0, ) self.assertEqual( len( new_state.models["test_alinto", "pony"].options.get( "index_together", set() ) ), 1, ) # Make sure there's no matching index self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"]) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_alinto", editor, project_state, new_state) self.assertIndexExists("test_alinto_pony", ["pink", "weight"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alinto", editor, new_state, project_state ) self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"]) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterIndexTogether") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Pony", "index_together": {("pink", "weight")}} ) def test_alter_index_together_remove(self): operation = migrations.AlterIndexTogether("Pony", None) self.assertEqual( operation.describe(), "Alter index_together for Pony (0 constraint(s))" ) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") @ignore_warnings(category=RemovedInDjango51Warning) def test_alter_index_together_remove_with_unique_together(self): app_label = "test_alintoremove_wunto" table_name = "%s_pony" % app_label project_state = self.set_up_test_model(app_label, unique_together=True) self.assertUniqueConstraintExists(table_name, ["pink", "weight"]) # Add index together. new_state = project_state.clone() operation = migrations.AlterIndexTogether("Pony", [("pink", "weight")]) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexExists(table_name, ["pink", "weight"]) # Remove index together. project_state = new_state new_state = project_state.clone() operation = migrations.AlterIndexTogether("Pony", set()) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNotExists(table_name, ["pink", "weight"]) self.assertUniqueConstraintExists(table_name, ["pink", "weight"]) def test_add_constraint(self): project_state = self.set_up_test_model("test_addconstraint") gt_check = models.Q(pink__gt=2) gt_constraint = models.CheckConstraint( check=gt_check, name="test_add_constraint_pony_pink_gt_2" ) gt_operation = migrations.AddConstraint("Pony", gt_constraint) self.assertEqual( gt_operation.describe(), "Create constraint test_add_constraint_pony_pink_gt_2 on model Pony", ) self.assertEqual( gt_operation.migration_name_fragment, "pony_test_add_constraint_pony_pink_gt_2", ) # Test the state alteration new_state = project_state.clone() gt_operation.state_forwards("test_addconstraint", new_state) self.assertEqual( len(new_state.models["test_addconstraint", "pony"].options["constraints"]), 1, ) Pony = new_state.apps.get_model("test_addconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 1) # Test the database alteration with ( CaptureQueriesContext(connection) as ctx, connection.schema_editor() as editor, ): gt_operation.database_forwards( "test_addconstraint", editor, project_state, new_state ) if connection.features.supports_table_check_constraints: with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=1, weight=1.0) else: self.assertIs( any("CHECK" in query["sql"] for query in ctx.captured_queries), False ) Pony.objects.create(pink=1, weight=1.0) # Add another one. lt_check = models.Q(pink__lt=100) lt_constraint = models.CheckConstraint( check=lt_check, name="test_add_constraint_pony_pink_lt_100" ) lt_operation = migrations.AddConstraint("Pony", lt_constraint) lt_operation.state_forwards("test_addconstraint", new_state) self.assertEqual( len(new_state.models["test_addconstraint", "pony"].options["constraints"]), 2, ) Pony = new_state.apps.get_model("test_addconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 2) with ( CaptureQueriesContext(connection) as ctx, connection.schema_editor() as editor, ): lt_operation.database_forwards( "test_addconstraint", editor, project_state, new_state ) if connection.features.supports_table_check_constraints: with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=100, weight=1.0) else: self.assertIs( any("CHECK" in query["sql"] for query in ctx.captured_queries), False ) Pony.objects.create(pink=100, weight=1.0) # Test reversal with connection.schema_editor() as editor: gt_operation.database_backwards( "test_addconstraint", editor, new_state, project_state ) Pony.objects.create(pink=1, weight=1.0) # Test deconstruction definition = gt_operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": gt_constraint} ) @skipUnlessDBFeature("supports_table_check_constraints") def test_add_constraint_percent_escaping(self): app_label = "add_constraint_string_quoting" operations = [ migrations.CreateModel( "Author", fields=[ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ("surname", models.CharField(max_length=100, default="")), ("rebate", models.CharField(max_length=100)), ], ), ] from_state = self.apply_operations(app_label, ProjectState(), operations) checks = [ # "%" generated in startswith lookup should be escaped in a way # that is considered a leading wildcard. ( models.Q(name__startswith="Albert"), {"name": "Alberta"}, {"name": "Artur"}, ), # Literal "%" should be escaped in a way that is not a considered a # wildcard. (models.Q(rebate__endswith="%"), {"rebate": "10%"}, {"rebate": "10%$"}), # Right-hand-side baked "%" literals should not be used for # parameters interpolation. ( ~models.Q(surname__startswith=models.F("name")), {"name": "Albert"}, {"name": "Albert", "surname": "Alberto"}, ), # Exact matches against "%" literals should also be supported. ( models.Q(name="%"), {"name": "%"}, {"name": "Albert"}, ), ] for check, valid, invalid in checks: with self.subTest(check=check, valid=valid, invalid=invalid): constraint = models.CheckConstraint(check=check, name="constraint") operation = migrations.AddConstraint("Author", constraint) to_state = from_state.clone() operation.state_forwards(app_label, to_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Author = to_state.apps.get_model(app_label, "Author") try: with transaction.atomic(): Author.objects.create(**valid).delete() with self.assertRaises(IntegrityError), transaction.atomic(): Author.objects.create(**invalid) finally: with connection.schema_editor() as editor: operation.database_backwards( app_label, editor, from_state, to_state ) @skipUnlessDBFeature("supports_table_check_constraints") def test_add_or_constraint(self): app_label = "test_addorconstraint" constraint_name = "add_constraint_or" from_state = self.set_up_test_model(app_label) check = models.Q(pink__gt=2, weight__gt=2) | models.Q(weight__lt=0) constraint = models.CheckConstraint(check=check, name=constraint_name) operation = migrations.AddConstraint("Pony", constraint) to_state = from_state.clone() operation.state_forwards(app_label, to_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Pony = to_state.apps.get_model(app_label, "Pony") with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=2, weight=3.0) with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=3, weight=1.0) Pony.objects.bulk_create( [ Pony(pink=3, weight=-1.0), Pony(pink=1, weight=-1.0), Pony(pink=3, weight=3.0), ] ) @skipUnlessDBFeature("supports_table_check_constraints") def test_add_constraint_combinable(self): app_label = "test_addconstraint_combinable" operations = [ migrations.CreateModel( "Book", fields=[ ("id", models.AutoField(primary_key=True)), ("read", models.PositiveIntegerField()), ("unread", models.PositiveIntegerField()), ], ), ] from_state = self.apply_operations(app_label, ProjectState(), operations) constraint = models.CheckConstraint( check=models.Q(read=(100 - models.F("unread"))), name="test_addconstraint_combinable_sum_100", ) operation = migrations.AddConstraint("Book", constraint) to_state = from_state.clone() operation.state_forwards(app_label, to_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Book = to_state.apps.get_model(app_label, "Book") with self.assertRaises(IntegrityError), transaction.atomic(): Book.objects.create(read=70, unread=10) Book.objects.create(read=70, unread=30) def test_remove_constraint(self): project_state = self.set_up_test_model( "test_removeconstraint", constraints=[ models.CheckConstraint( check=models.Q(pink__gt=2), name="test_remove_constraint_pony_pink_gt_2", ), models.CheckConstraint( check=models.Q(pink__lt=100), name="test_remove_constraint_pony_pink_lt_100", ), ], ) gt_operation = migrations.RemoveConstraint( "Pony", "test_remove_constraint_pony_pink_gt_2" ) self.assertEqual( gt_operation.describe(), "Remove constraint test_remove_constraint_pony_pink_gt_2 from model Pony", ) self.assertEqual( gt_operation.migration_name_fragment, "remove_pony_test_remove_constraint_pony_pink_gt_2", ) # Test state alteration new_state = project_state.clone() gt_operation.state_forwards("test_removeconstraint", new_state) self.assertEqual( len( new_state.models["test_removeconstraint", "pony"].options["constraints"] ), 1, ) Pony = new_state.apps.get_model("test_removeconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 1) # Test database alteration with connection.schema_editor() as editor: gt_operation.database_forwards( "test_removeconstraint", editor, project_state, new_state ) Pony.objects.create(pink=1, weight=1.0).delete() if connection.features.supports_table_check_constraints: with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=100, weight=1.0) else: Pony.objects.create(pink=100, weight=1.0) # Remove the other one. lt_operation = migrations.RemoveConstraint( "Pony", "test_remove_constraint_pony_pink_lt_100" ) lt_operation.state_forwards("test_removeconstraint", new_state) self.assertEqual( len( new_state.models["test_removeconstraint", "pony"].options["constraints"] ), 0, ) Pony = new_state.apps.get_model("test_removeconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 0) with connection.schema_editor() as editor: lt_operation.database_forwards( "test_removeconstraint", editor, project_state, new_state ) Pony.objects.create(pink=100, weight=1.0).delete() # Test reversal with connection.schema_editor() as editor: gt_operation.database_backwards( "test_removeconstraint", editor, new_state, project_state ) if connection.features.supports_table_check_constraints: with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=1, weight=1.0) else: Pony.objects.create(pink=1, weight=1.0) # Test deconstruction definition = gt_operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "name": "test_remove_constraint_pony_pink_gt_2"}, ) def test_add_partial_unique_constraint(self): project_state = self.set_up_test_model("test_addpartialuniqueconstraint") partial_unique_constraint = models.UniqueConstraint( fields=["pink"], condition=models.Q(weight__gt=5), name="test_constraint_pony_pink_for_weight_gt_5_uniq", ) operation = migrations.AddConstraint("Pony", partial_unique_constraint) self.assertEqual( operation.describe(), "Create constraint test_constraint_pony_pink_for_weight_gt_5_uniq " "on model Pony", ) # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_addpartialuniqueconstraint", new_state) self.assertEqual( len( new_state.models["test_addpartialuniqueconstraint", "pony"].options[ "constraints" ] ), 1, ) Pony = new_state.apps.get_model("test_addpartialuniqueconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 1) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_addpartialuniqueconstraint", editor, project_state, new_state ) # Test constraint works Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=6.0) if connection.features.supports_partial_indexes: with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=1, weight=7.0) else: Pony.objects.create(pink=1, weight=7.0) # Test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_addpartialuniqueconstraint", editor, new_state, project_state ) # Test constraint doesn't work Pony.objects.create(pink=1, weight=7.0) # Test deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": partial_unique_constraint}, ) def test_remove_partial_unique_constraint(self): project_state = self.set_up_test_model( "test_removepartialuniqueconstraint", constraints=[ models.UniqueConstraint( fields=["pink"], condition=models.Q(weight__gt=5), name="test_constraint_pony_pink_for_weight_gt_5_uniq", ), ], ) gt_operation = migrations.RemoveConstraint( "Pony", "test_constraint_pony_pink_for_weight_gt_5_uniq" ) self.assertEqual( gt_operation.describe(), "Remove constraint test_constraint_pony_pink_for_weight_gt_5_uniq from " "model Pony", ) # Test state alteration new_state = project_state.clone() gt_operation.state_forwards("test_removepartialuniqueconstraint", new_state) self.assertEqual( len( new_state.models["test_removepartialuniqueconstraint", "pony"].options[ "constraints" ] ), 0, ) Pony = new_state.apps.get_model("test_removepartialuniqueconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 0) # Test database alteration with connection.schema_editor() as editor: gt_operation.database_forwards( "test_removepartialuniqueconstraint", editor, project_state, new_state ) # Test constraint doesn't work Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=6.0) Pony.objects.create(pink=1, weight=7.0).delete() # Test reversal with connection.schema_editor() as editor: gt_operation.database_backwards( "test_removepartialuniqueconstraint", editor, new_state, project_state ) # Test constraint works if connection.features.supports_partial_indexes: with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=1, weight=7.0) else: Pony.objects.create(pink=1, weight=7.0) # Test deconstruction definition = gt_operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "name": "test_constraint_pony_pink_for_weight_gt_5_uniq", }, ) def test_add_deferred_unique_constraint(self): app_label = "test_adddeferred_uc" project_state = self.set_up_test_model(app_label) deferred_unique_constraint = models.UniqueConstraint( fields=["pink"], name="deferred_pink_constraint_add", deferrable=models.Deferrable.DEFERRED, ) operation = migrations.AddConstraint("Pony", deferred_unique_constraint) self.assertEqual( operation.describe(), "Create constraint deferred_pink_constraint_add on model Pony", ) # Add constraint. new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 1 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 1) with connection.schema_editor() as editor, CaptureQueriesContext( connection ) as ctx: operation.database_forwards(app_label, editor, project_state, new_state) Pony.objects.create(pink=1, weight=4.0) if connection.features.supports_deferrable_unique_constraints: # Unique constraint is deferred. with transaction.atomic(): obj = Pony.objects.create(pink=1, weight=4.0) obj.pink = 2 obj.save() # Constraint behavior can be changed with SET CONSTRAINTS. with self.assertRaises(IntegrityError): with transaction.atomic(), connection.cursor() as cursor: quoted_name = connection.ops.quote_name( deferred_unique_constraint.name ) cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name) obj = Pony.objects.create(pink=1, weight=4.0) obj.pink = 3 obj.save() else: self.assertEqual(len(ctx), 0) Pony.objects.create(pink=1, weight=4.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": deferred_unique_constraint}, ) def test_remove_deferred_unique_constraint(self): app_label = "test_removedeferred_uc" deferred_unique_constraint = models.UniqueConstraint( fields=["pink"], name="deferred_pink_constraint_rm", deferrable=models.Deferrable.DEFERRED, ) project_state = self.set_up_test_model( app_label, constraints=[deferred_unique_constraint] ) operation = migrations.RemoveConstraint("Pony", deferred_unique_constraint.name) self.assertEqual( operation.describe(), "Remove constraint deferred_pink_constraint_rm from model Pony", ) # Remove constraint. new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 0 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 0) with connection.schema_editor() as editor, CaptureQueriesContext( connection ) as ctx: operation.database_forwards(app_label, editor, project_state, new_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0).delete() if not connection.features.supports_deferrable_unique_constraints: self.assertEqual(len(ctx), 0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) if connection.features.supports_deferrable_unique_constraints: # Unique constraint is deferred. with transaction.atomic(): obj = Pony.objects.create(pink=1, weight=4.0) obj.pink = 2 obj.save() # Constraint behavior can be changed with SET CONSTRAINTS. with self.assertRaises(IntegrityError): with transaction.atomic(), connection.cursor() as cursor: quoted_name = connection.ops.quote_name( deferred_unique_constraint.name ) cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name) obj = Pony.objects.create(pink=1, weight=4.0) obj.pink = 3 obj.save() else: Pony.objects.create(pink=1, weight=4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "name": "deferred_pink_constraint_rm", }, ) def test_add_covering_unique_constraint(self): app_label = "test_addcovering_uc" project_state = self.set_up_test_model(app_label) covering_unique_constraint = models.UniqueConstraint( fields=["pink"], name="covering_pink_constraint_add", include=["weight"], ) operation = migrations.AddConstraint("Pony", covering_unique_constraint) self.assertEqual( operation.describe(), "Create constraint covering_pink_constraint_add on model Pony", ) # Add constraint. new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 1 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 1) with connection.schema_editor() as editor, CaptureQueriesContext( connection ) as ctx: operation.database_forwards(app_label, editor, project_state, new_state) Pony.objects.create(pink=1, weight=4.0) if connection.features.supports_covering_indexes: with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=4.0) else: self.assertEqual(len(ctx), 0) Pony.objects.create(pink=1, weight=4.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": covering_unique_constraint}, ) def test_remove_covering_unique_constraint(self): app_label = "test_removecovering_uc" covering_unique_constraint = models.UniqueConstraint( fields=["pink"], name="covering_pink_constraint_rm", include=["weight"], ) project_state = self.set_up_test_model( app_label, constraints=[covering_unique_constraint] ) operation = migrations.RemoveConstraint("Pony", covering_unique_constraint.name) self.assertEqual( operation.describe(), "Remove constraint covering_pink_constraint_rm from model Pony", ) # Remove constraint. new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 0 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 0) with connection.schema_editor() as editor, CaptureQueriesContext( connection ) as ctx: operation.database_forwards(app_label, editor, project_state, new_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0).delete() if not connection.features.supports_covering_indexes: self.assertEqual(len(ctx), 0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) if connection.features.supports_covering_indexes: with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=4.0) else: Pony.objects.create(pink=1, weight=4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "name": "covering_pink_constraint_rm", }, ) def test_alter_field_with_func_unique_constraint(self): app_label = "test_alfuncuc" constraint_name = f"{app_label}_pony_uq" table_name = f"{app_label}_pony" project_state = self.set_up_test_model( app_label, constraints=[ models.UniqueConstraint("pink", "weight", name=constraint_name) ], ) operation = migrations.AlterField( "Pony", "pink", models.IntegerField(null=True) ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) def test_add_func_unique_constraint(self): app_label = "test_adfuncuc" constraint_name = f"{app_label}_pony_abs_uq" table_name = f"{app_label}_pony" project_state = self.set_up_test_model(app_label) constraint = models.UniqueConstraint(Abs("weight"), name=constraint_name) operation = migrations.AddConstraint("Pony", constraint) self.assertEqual( operation.describe(), "Create constraint test_adfuncuc_pony_abs_uq on model Pony", ) self.assertEqual( operation.migration_name_fragment, "pony_test_adfuncuc_pony_abs_uq", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 1 ) self.assertIndexNameNotExists(table_name, constraint_name) # Add constraint. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) Pony = new_state.apps.get_model(app_label, "Pony") Pony.objects.create(weight=4.0) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) with self.assertRaises(IntegrityError): Pony.objects.create(weight=-4.0) else: self.assertIndexNameNotExists(table_name, constraint_name) Pony.objects.create(weight=-4.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameNotExists(table_name, constraint_name) # Constraint doesn't work. Pony.objects.create(weight=-4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": constraint}, ) def test_remove_func_unique_constraint(self): app_label = "test_rmfuncuc" constraint_name = f"{app_label}_pony_abs_uq" table_name = f"{app_label}_pony" project_state = self.set_up_test_model( app_label, constraints=[ models.UniqueConstraint(Abs("weight"), name=constraint_name), ], ) self.assertTableExists(table_name) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) operation = migrations.RemoveConstraint("Pony", constraint_name) self.assertEqual( operation.describe(), "Remove constraint test_rmfuncuc_pony_abs_uq from model Pony", ) self.assertEqual( operation.migration_name_fragment, "remove_pony_test_rmfuncuc_pony_abs_uq", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 0 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 0) # Remove constraint. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameNotExists(table_name, constraint_name) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=-4.0).delete() # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) with self.assertRaises(IntegrityError): Pony.objects.create(weight=-4.0) else: self.assertIndexNameNotExists(table_name, constraint_name) Pony.objects.create(weight=-4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "name": constraint_name}) def test_alter_model_options(self): """ Tests the AlterModelOptions operation. """ project_state = self.set_up_test_model("test_almoop") # Test the state alteration (no DB alteration to test) operation = migrations.AlterModelOptions( "Pony", {"permissions": [("can_groom", "Can groom")]} ) self.assertEqual(operation.describe(), "Change Meta options on Pony") self.assertEqual(operation.migration_name_fragment, "alter_pony_options") new_state = project_state.clone() operation.state_forwards("test_almoop", new_state) self.assertEqual( len( project_state.models["test_almoop", "pony"].options.get( "permissions", [] ) ), 0, ) self.assertEqual( len(new_state.models["test_almoop", "pony"].options.get("permissions", [])), 1, ) self.assertEqual( new_state.models["test_almoop", "pony"].options["permissions"][0][0], "can_groom", ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterModelOptions") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Pony", "options": {"permissions": [("can_groom", "Can groom")]}}, ) def test_alter_model_options_emptying(self): """ The AlterModelOptions operation removes keys from the dict (#23121) """ project_state = self.set_up_test_model("test_almoop", options=True) # Test the state alteration (no DB alteration to test) operation = migrations.AlterModelOptions("Pony", {}) self.assertEqual(operation.describe(), "Change Meta options on Pony") new_state = project_state.clone() operation.state_forwards("test_almoop", new_state) self.assertEqual( len( project_state.models["test_almoop", "pony"].options.get( "permissions", [] ) ), 1, ) self.assertEqual( len(new_state.models["test_almoop", "pony"].options.get("permissions", [])), 0, ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterModelOptions") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"name": "Pony", "options": {}}) def test_alter_order_with_respect_to(self): """ Tests the AlterOrderWithRespectTo operation. """ project_state = self.set_up_test_model("test_alorwrtto", related_model=True) # Test the state alteration operation = migrations.AlterOrderWithRespectTo("Rider", "pony") self.assertEqual( operation.describe(), "Set order_with_respect_to on Rider to pony" ) self.assertEqual( operation.migration_name_fragment, "alter_rider_order_with_respect_to", ) new_state = project_state.clone() operation.state_forwards("test_alorwrtto", new_state) self.assertIsNone( project_state.models["test_alorwrtto", "rider"].options.get( "order_with_respect_to", None ) ) self.assertEqual( new_state.models["test_alorwrtto", "rider"].options.get( "order_with_respect_to", None ), "pony", ) # Make sure there's no matching index self.assertColumnNotExists("test_alorwrtto_rider", "_order") # Create some rows before alteration rendered_state = project_state.apps pony = rendered_state.get_model("test_alorwrtto", "Pony").objects.create( weight=50 ) rider1 = rendered_state.get_model("test_alorwrtto", "Rider").objects.create( pony=pony ) rider1.friend = rider1 rider1.save() rider2 = rendered_state.get_model("test_alorwrtto", "Rider").objects.create( pony=pony ) rider2.friend = rider2 rider2.save() # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_alorwrtto", editor, project_state, new_state ) self.assertColumnExists("test_alorwrtto_rider", "_order") # Check for correct value in rows updated_riders = new_state.apps.get_model( "test_alorwrtto", "Rider" ).objects.all() self.assertEqual(updated_riders[0]._order, 0) self.assertEqual(updated_riders[1]._order, 0) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alorwrtto", editor, new_state, project_state ) self.assertColumnNotExists("test_alorwrtto_rider", "_order") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterOrderWithRespectTo") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Rider", "order_with_respect_to": "pony"} ) def test_alter_model_managers(self): """ The managers on a model are set. """ project_state = self.set_up_test_model("test_almoma") # Test the state alteration operation = migrations.AlterModelManagers( "Pony", managers=[ ("food_qs", FoodQuerySet.as_manager()), ("food_mgr", FoodManager("a", "b")), ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)), ], ) self.assertEqual(operation.describe(), "Change managers on Pony") self.assertEqual(operation.migration_name_fragment, "alter_pony_managers") managers = project_state.models["test_almoma", "pony"].managers self.assertEqual(managers, []) new_state = project_state.clone() operation.state_forwards("test_almoma", new_state) self.assertIn(("test_almoma", "pony"), new_state.models) managers = new_state.models["test_almoma", "pony"].managers self.assertEqual(managers[0][0], "food_qs") self.assertIsInstance(managers[0][1], models.Manager) self.assertEqual(managers[1][0], "food_mgr") self.assertIsInstance(managers[1][1], FoodManager) self.assertEqual(managers[1][1].args, ("a", "b", 1, 2)) self.assertEqual(managers[2][0], "food_mgr_kwargs") self.assertIsInstance(managers[2][1], FoodManager) self.assertEqual(managers[2][1].args, ("x", "y", 3, 4)) rendered_state = new_state.apps model = rendered_state.get_model("test_almoma", "pony") self.assertIsInstance(model.food_qs, models.Manager) self.assertIsInstance(model.food_mgr, FoodManager) self.assertIsInstance(model.food_mgr_kwargs, FoodManager) def test_alter_model_managers_emptying(self): """ The managers on a model are set. """ project_state = self.set_up_test_model("test_almomae", manager_model=True) # Test the state alteration operation = migrations.AlterModelManagers("Food", managers=[]) self.assertEqual(operation.describe(), "Change managers on Food") self.assertIn(("test_almomae", "food"), project_state.models) managers = project_state.models["test_almomae", "food"].managers self.assertEqual(managers[0][0], "food_qs") self.assertIsInstance(managers[0][1], models.Manager) self.assertEqual(managers[1][0], "food_mgr") self.assertIsInstance(managers[1][1], FoodManager) self.assertEqual(managers[1][1].args, ("a", "b", 1, 2)) self.assertEqual(managers[2][0], "food_mgr_kwargs") self.assertIsInstance(managers[2][1], FoodManager) self.assertEqual(managers[2][1].args, ("x", "y", 3, 4)) new_state = project_state.clone() operation.state_forwards("test_almomae", new_state) managers = new_state.models["test_almomae", "food"].managers self.assertEqual(managers, []) def test_alter_fk(self): """ Creating and then altering an FK works correctly and deals with the pending SQL (#23091) """ project_state = self.set_up_test_model("test_alfk") # Test adding and then altering the FK in one go create_operation = migrations.CreateModel( name="Rider", fields=[ ("id", models.AutoField(primary_key=True)), ("pony", models.ForeignKey("Pony", models.CASCADE)), ], ) create_state = project_state.clone() create_operation.state_forwards("test_alfk", create_state) alter_operation = migrations.AlterField( model_name="Rider", name="pony", field=models.ForeignKey("Pony", models.CASCADE, editable=False), ) alter_state = create_state.clone() alter_operation.state_forwards("test_alfk", alter_state) with connection.schema_editor() as editor: create_operation.database_forwards( "test_alfk", editor, project_state, create_state ) alter_operation.database_forwards( "test_alfk", editor, create_state, alter_state ) def test_alter_fk_non_fk(self): """ Altering an FK to a non-FK works (#23244) """ # Test the state alteration operation = migrations.AlterField( model_name="Rider", name="pony", field=models.FloatField(), ) project_state, new_state = self.make_test_state( "test_afknfk", operation, related_model=True ) # Test the database alteration self.assertColumnExists("test_afknfk_rider", "pony_id") self.assertColumnNotExists("test_afknfk_rider", "pony") with connection.schema_editor() as editor: operation.database_forwards("test_afknfk", editor, project_state, new_state) self.assertColumnExists("test_afknfk_rider", "pony") self.assertColumnNotExists("test_afknfk_rider", "pony_id") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_afknfk", editor, new_state, project_state ) self.assertColumnExists("test_afknfk_rider", "pony_id") self.assertColumnNotExists("test_afknfk_rider", "pony") def test_run_sql(self): """ Tests the RunSQL operation. """ project_state = self.set_up_test_model("test_runsql") # Create the operation operation = migrations.RunSQL( # Use a multi-line string with a comment to test splitting on # SQLite and MySQL respectively. "CREATE TABLE i_love_ponies (id int, special_thing varchar(15));\n" "INSERT INTO i_love_ponies (id, special_thing) " "VALUES (1, 'i love ponies'); -- this is magic!\n" "INSERT INTO i_love_ponies (id, special_thing) " "VALUES (2, 'i love django');\n" "UPDATE i_love_ponies SET special_thing = 'Ponies' " "WHERE special_thing LIKE '%%ponies';" "UPDATE i_love_ponies SET special_thing = 'Django' " "WHERE special_thing LIKE '%django';", # Run delete queries to test for parameter substitution failure # reported in #23426 "DELETE FROM i_love_ponies WHERE special_thing LIKE '%Django%';" "DELETE FROM i_love_ponies WHERE special_thing LIKE '%%Ponies%%';" "DROP TABLE i_love_ponies", state_operations=[ migrations.CreateModel( "SomethingElse", [("id", models.AutoField(primary_key=True))] ) ], ) self.assertEqual(operation.describe(), "Raw SQL operation") # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_runsql", new_state) self.assertEqual( len(new_state.models["test_runsql", "somethingelse"].fields), 1 ) # Make sure there's no table self.assertTableNotExists("i_love_ponies") # Test SQL collection with connection.schema_editor(collect_sql=True) as editor: operation.database_forwards("test_runsql", editor, project_state, new_state) self.assertIn("LIKE '%%ponies';", "\n".join(editor.collected_sql)) operation.database_backwards( "test_runsql", editor, project_state, new_state ) self.assertIn("LIKE '%%Ponies%%';", "\n".join(editor.collected_sql)) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_runsql", editor, project_state, new_state) self.assertTableExists("i_love_ponies") # Make sure all the SQL was processed with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM i_love_ponies") self.assertEqual(cursor.fetchall()[0][0], 2) cursor.execute( "SELECT COUNT(*) FROM i_love_ponies WHERE special_thing = 'Django'" ) self.assertEqual(cursor.fetchall()[0][0], 1) cursor.execute( "SELECT COUNT(*) FROM i_love_ponies WHERE special_thing = 'Ponies'" ) self.assertEqual(cursor.fetchall()[0][0], 1) # And test reversal self.assertTrue(operation.reversible) with connection.schema_editor() as editor: operation.database_backwards( "test_runsql", editor, new_state, project_state ) self.assertTableNotExists("i_love_ponies") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RunSQL") self.assertEqual(definition[1], []) self.assertEqual( sorted(definition[2]), ["reverse_sql", "sql", "state_operations"] ) # And elidable reduction self.assertIs(False, operation.reduce(operation, [])) elidable_operation = migrations.RunSQL("SELECT 1 FROM void;", elidable=True) self.assertEqual(elidable_operation.reduce(operation, []), [operation]) def test_run_sql_params(self): """ #23426 - RunSQL should accept parameters. """ project_state = self.set_up_test_model("test_runsql") # Create the operation operation = migrations.RunSQL( ["CREATE TABLE i_love_ponies (id int, special_thing varchar(15));"], ["DROP TABLE i_love_ponies"], ) param_operation = migrations.RunSQL( # forwards ( "INSERT INTO i_love_ponies (id, special_thing) VALUES (1, 'Django');", [ "INSERT INTO i_love_ponies (id, special_thing) VALUES (2, %s);", ["Ponies"], ], ( "INSERT INTO i_love_ponies (id, special_thing) VALUES (%s, %s);", ( 3, "Python", ), ), ), # backwards [ "DELETE FROM i_love_ponies WHERE special_thing = 'Django';", ["DELETE FROM i_love_ponies WHERE special_thing = 'Ponies';", None], ( "DELETE FROM i_love_ponies WHERE id = %s OR special_thing = %s;", [3, "Python"], ), ], ) # Make sure there's no table self.assertTableNotExists("i_love_ponies") new_state = project_state.clone() # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_runsql", editor, project_state, new_state) # Test parameter passing with connection.schema_editor() as editor: param_operation.database_forwards( "test_runsql", editor, project_state, new_state ) # Make sure all the SQL was processed with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM i_love_ponies") self.assertEqual(cursor.fetchall()[0][0], 3) with connection.schema_editor() as editor: param_operation.database_backwards( "test_runsql", editor, new_state, project_state ) with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM i_love_ponies") self.assertEqual(cursor.fetchall()[0][0], 0) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_runsql", editor, new_state, project_state ) self.assertTableNotExists("i_love_ponies") def test_run_sql_params_invalid(self): """ #23426 - RunSQL should fail when a list of statements with an incorrect number of tuples is given. """ project_state = self.set_up_test_model("test_runsql") new_state = project_state.clone() operation = migrations.RunSQL( # forwards [["INSERT INTO foo (bar) VALUES ('buz');"]], # backwards (("DELETE FROM foo WHERE bar = 'buz';", "invalid", "parameter count"),), ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 1"): operation.database_forwards( "test_runsql", editor, project_state, new_state ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 3"): operation.database_backwards( "test_runsql", editor, new_state, project_state ) def test_run_sql_noop(self): """ #24098 - Tests no-op RunSQL operations. """ operation = migrations.RunSQL(migrations.RunSQL.noop, migrations.RunSQL.noop) with connection.schema_editor() as editor: operation.database_forwards("test_runsql", editor, None, None) operation.database_backwards("test_runsql", editor, None, None) def test_run_sql_add_missing_semicolon_on_collect_sql(self): project_state = self.set_up_test_model("test_runsql") new_state = project_state.clone() tests = [ "INSERT INTO test_runsql_pony (pink, weight) VALUES (1, 1);\n", "INSERT INTO test_runsql_pony (pink, weight) VALUES (1, 1)\n", ] for sql in tests: with self.subTest(sql=sql): operation = migrations.RunSQL(sql, migrations.RunPython.noop) with connection.schema_editor(collect_sql=True) as editor: operation.database_forwards( "test_runsql", editor, project_state, new_state ) collected_sql = "\n".join(editor.collected_sql) self.assertEqual(collected_sql.count(";"), 1) def test_run_python(self): """ Tests the RunPython operation """ project_state = self.set_up_test_model("test_runpython", mti_model=True) # Create the operation def inner_method(models, schema_editor): Pony = models.get_model("test_runpython", "Pony") Pony.objects.create(pink=1, weight=3.55) Pony.objects.create(weight=5) def inner_method_reverse(models, schema_editor): Pony = models.get_model("test_runpython", "Pony") Pony.objects.filter(pink=1, weight=3.55).delete() Pony.objects.filter(weight=5).delete() operation = migrations.RunPython( inner_method, reverse_code=inner_method_reverse ) self.assertEqual(operation.describe(), "Raw Python operation") # Test the state alteration does nothing new_state = project_state.clone() operation.state_forwards("test_runpython", new_state) self.assertEqual(new_state, project_state) # Test the database alteration self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 0 ) with connection.schema_editor() as editor: operation.database_forwards( "test_runpython", editor, project_state, new_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 2 ) # Now test reversal self.assertTrue(operation.reversible) with connection.schema_editor() as editor: operation.database_backwards( "test_runpython", editor, project_state, new_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 0 ) # Now test we can't use a string with self.assertRaisesMessage( ValueError, "RunPython must be supplied with a callable" ): migrations.RunPython("print 'ahahaha'") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RunPython") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["code", "reverse_code"]) # Also test reversal fails, with an operation identical to above but # without reverse_code set. no_reverse_operation = migrations.RunPython(inner_method) self.assertFalse(no_reverse_operation.reversible) with connection.schema_editor() as editor: no_reverse_operation.database_forwards( "test_runpython", editor, project_state, new_state ) with self.assertRaises(NotImplementedError): no_reverse_operation.database_backwards( "test_runpython", editor, new_state, project_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 2 ) def create_ponies(models, schema_editor): Pony = models.get_model("test_runpython", "Pony") pony1 = Pony.objects.create(pink=1, weight=3.55) self.assertIsNot(pony1.pk, None) pony2 = Pony.objects.create(weight=5) self.assertIsNot(pony2.pk, None) self.assertNotEqual(pony1.pk, pony2.pk) operation = migrations.RunPython(create_ponies) with connection.schema_editor() as editor: operation.database_forwards( "test_runpython", editor, project_state, new_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 4 ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RunPython") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["code"]) def create_shetlandponies(models, schema_editor): ShetlandPony = models.get_model("test_runpython", "ShetlandPony") pony1 = ShetlandPony.objects.create(weight=4.0) self.assertIsNot(pony1.pk, None) pony2 = ShetlandPony.objects.create(weight=5.0) self.assertIsNot(pony2.pk, None) self.assertNotEqual(pony1.pk, pony2.pk) operation = migrations.RunPython(create_shetlandponies) with connection.schema_editor() as editor: operation.database_forwards( "test_runpython", editor, project_state, new_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 6 ) self.assertEqual( project_state.apps.get_model( "test_runpython", "ShetlandPony" ).objects.count(), 2, ) # And elidable reduction self.assertIs(False, operation.reduce(operation, [])) elidable_operation = migrations.RunPython(inner_method, elidable=True) self.assertEqual(elidable_operation.reduce(operation, []), [operation]) def test_run_python_atomic(self): """ Tests the RunPython operation correctly handles the "atomic" keyword """ project_state = self.set_up_test_model("test_runpythonatomic", mti_model=True) def inner_method(models, schema_editor): Pony = models.get_model("test_runpythonatomic", "Pony") Pony.objects.create(pink=1, weight=3.55) raise ValueError("Adrian hates ponies.") # Verify atomicity when applying. atomic_migration = Migration("test", "test_runpythonatomic") atomic_migration.operations = [ migrations.RunPython(inner_method, reverse_code=inner_method) ] non_atomic_migration = Migration("test", "test_runpythonatomic") non_atomic_migration.operations = [ migrations.RunPython(inner_method, reverse_code=inner_method, atomic=False) ] # If we're a fully-transactional database, both versions should rollback if connection.features.can_rollback_ddl: self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: atomic_migration.apply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: non_atomic_migration.apply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) # Otherwise, the non-atomic operation should leave a row there else: self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: atomic_migration.apply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: non_atomic_migration.apply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 1, ) # Reset object count to zero and verify atomicity when unapplying. project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.all().delete() # On a fully-transactional database, both versions rollback. if connection.features.can_rollback_ddl: self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: atomic_migration.unapply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: non_atomic_migration.unapply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) # Otherwise, the non-atomic operation leaves a row there. else: self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: atomic_migration.unapply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: non_atomic_migration.unapply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 1, ) # Verify deconstruction. definition = non_atomic_migration.operations[0].deconstruct() self.assertEqual(definition[0], "RunPython") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["atomic", "code", "reverse_code"]) def test_run_python_related_assignment(self): """ #24282 - Model changes to a FK reverse side update the model on the FK side as well. """ def inner_method(models, schema_editor): Author = models.get_model("test_authors", "Author") Book = models.get_model("test_books", "Book") author = Author.objects.create(name="Hemingway") Book.objects.create(title="Old Man and The Sea", author=author) create_author = migrations.CreateModel( "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ], options={}, ) create_book = migrations.CreateModel( "Book", [ ("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=100)), ("author", models.ForeignKey("test_authors.Author", models.CASCADE)), ], options={}, ) add_hometown = migrations.AddField( "Author", "hometown", models.CharField(max_length=100), ) create_old_man = migrations.RunPython(inner_method, inner_method) project_state = ProjectState() new_state = project_state.clone() with connection.schema_editor() as editor: create_author.state_forwards("test_authors", new_state) create_author.database_forwards( "test_authors", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: create_book.state_forwards("test_books", new_state) create_book.database_forwards( "test_books", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: add_hometown.state_forwards("test_authors", new_state) add_hometown.database_forwards( "test_authors", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: create_old_man.state_forwards("test_books", new_state) create_old_man.database_forwards( "test_books", editor, project_state, new_state ) def test_model_with_bigautofield(self): """ A model with BigAutoField can be created. """ def create_data(models, schema_editor): Author = models.get_model("test_author", "Author") Book = models.get_model("test_book", "Book") author1 = Author.objects.create(name="Hemingway") Book.objects.create(title="Old Man and The Sea", author=author1) Book.objects.create(id=2**33, title="A farewell to arms", author=author1) author2 = Author.objects.create(id=2**33, name="Remarque") Book.objects.create(title="All quiet on the western front", author=author2) Book.objects.create(title="Arc de Triomphe", author=author2) create_author = migrations.CreateModel( "Author", [ ("id", models.BigAutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ], options={}, ) create_book = migrations.CreateModel( "Book", [ ("id", models.BigAutoField(primary_key=True)), ("title", models.CharField(max_length=100)), ( "author", models.ForeignKey( to="test_author.Author", on_delete=models.CASCADE ), ), ], options={}, ) fill_data = migrations.RunPython(create_data) project_state = ProjectState() new_state = project_state.clone() with connection.schema_editor() as editor: create_author.state_forwards("test_author", new_state) create_author.database_forwards( "test_author", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: create_book.state_forwards("test_book", new_state) create_book.database_forwards("test_book", editor, project_state, new_state) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: fill_data.state_forwards("fill_data", new_state) fill_data.database_forwards("fill_data", editor, project_state, new_state) def _test_autofield_foreignfield_growth( self, source_field, target_field, target_value ): """ A field may be migrated in the following ways: - AutoField to BigAutoField - SmallAutoField to AutoField - SmallAutoField to BigAutoField """ def create_initial_data(models, schema_editor): Article = models.get_model("test_article", "Article") Blog = models.get_model("test_blog", "Blog") blog = Blog.objects.create(name="web development done right") Article.objects.create(name="Frameworks", blog=blog) Article.objects.create(name="Programming Languages", blog=blog) def create_big_data(models, schema_editor): Article = models.get_model("test_article", "Article") Blog = models.get_model("test_blog", "Blog") blog2 = Blog.objects.create(name="Frameworks", id=target_value) Article.objects.create(name="Django", blog=blog2) Article.objects.create(id=target_value, name="Django2", blog=blog2) create_blog = migrations.CreateModel( "Blog", [ ("id", source_field(primary_key=True)), ("name", models.CharField(max_length=100)), ], options={}, ) create_article = migrations.CreateModel( "Article", [ ("id", source_field(primary_key=True)), ( "blog", models.ForeignKey(to="test_blog.Blog", on_delete=models.CASCADE), ), ("name", models.CharField(max_length=100)), ("data", models.TextField(default="")), ], options={}, ) fill_initial_data = migrations.RunPython( create_initial_data, create_initial_data ) fill_big_data = migrations.RunPython(create_big_data, create_big_data) grow_article_id = migrations.AlterField( "Article", "id", target_field(primary_key=True) ) grow_blog_id = migrations.AlterField( "Blog", "id", target_field(primary_key=True) ) project_state = ProjectState() new_state = project_state.clone() with connection.schema_editor() as editor: create_blog.state_forwards("test_blog", new_state) create_blog.database_forwards("test_blog", editor, project_state, new_state) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: create_article.state_forwards("test_article", new_state) create_article.database_forwards( "test_article", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: fill_initial_data.state_forwards("fill_initial_data", new_state) fill_initial_data.database_forwards( "fill_initial_data", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: grow_article_id.state_forwards("test_article", new_state) grow_article_id.database_forwards( "test_article", editor, project_state, new_state ) state = new_state.clone() article = state.apps.get_model("test_article.Article") self.assertIsInstance(article._meta.pk, target_field) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: grow_blog_id.state_forwards("test_blog", new_state) grow_blog_id.database_forwards( "test_blog", editor, project_state, new_state ) state = new_state.clone() blog = state.apps.get_model("test_blog.Blog") self.assertIsInstance(blog._meta.pk, target_field) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: fill_big_data.state_forwards("fill_big_data", new_state) fill_big_data.database_forwards( "fill_big_data", editor, project_state, new_state ) def test_autofield__bigautofield_foreignfield_growth(self): """A field may be migrated from AutoField to BigAutoField.""" self._test_autofield_foreignfield_growth( models.AutoField, models.BigAutoField, 2**33, ) def test_smallfield_autofield_foreignfield_growth(self): """A field may be migrated from SmallAutoField to AutoField.""" self._test_autofield_foreignfield_growth( models.SmallAutoField, models.AutoField, 2**22, ) def test_smallfield_bigautofield_foreignfield_growth(self): """A field may be migrated from SmallAutoField to BigAutoField.""" self._test_autofield_foreignfield_growth( models.SmallAutoField, models.BigAutoField, 2**33, ) def test_run_python_noop(self): """ #24098 - Tests no-op RunPython operations. """ project_state = ProjectState() new_state = project_state.clone() operation = migrations.RunPython( migrations.RunPython.noop, migrations.RunPython.noop ) with connection.schema_editor() as editor: operation.database_forwards( "test_runpython", editor, project_state, new_state ) operation.database_backwards( "test_runpython", editor, new_state, project_state ) def test_separate_database_and_state(self): """ Tests the SeparateDatabaseAndState operation. """ project_state = self.set_up_test_model("test_separatedatabaseandstate") # Create the operation database_operation = migrations.RunSQL( "CREATE TABLE i_love_ponies (id int, special_thing int);", "DROP TABLE i_love_ponies;", ) state_operation = migrations.CreateModel( "SomethingElse", [("id", models.AutoField(primary_key=True))] ) operation = migrations.SeparateDatabaseAndState( state_operations=[state_operation], database_operations=[database_operation] ) self.assertEqual( operation.describe(), "Custom state/database change combination" ) # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_separatedatabaseandstate", new_state) self.assertEqual( len( new_state.models[ "test_separatedatabaseandstate", "somethingelse" ].fields ), 1, ) # Make sure there's no table self.assertTableNotExists("i_love_ponies") # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_separatedatabaseandstate", editor, project_state, new_state ) self.assertTableExists("i_love_ponies") # And test reversal self.assertTrue(operation.reversible) with connection.schema_editor() as editor: operation.database_backwards( "test_separatedatabaseandstate", editor, new_state, project_state ) self.assertTableNotExists("i_love_ponies") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "SeparateDatabaseAndState") self.assertEqual(definition[1], []) self.assertEqual( sorted(definition[2]), ["database_operations", "state_operations"] ) def test_separate_database_and_state2(self): """ A complex SeparateDatabaseAndState operation: Multiple operations both for state and database. Verify the state dependencies within each list and that state ops don't affect the database. """ app_label = "test_separatedatabaseandstate2" project_state = self.set_up_test_model(app_label) # Create the operation database_operations = [ migrations.CreateModel( "ILovePonies", [("id", models.AutoField(primary_key=True))], options={"db_table": "iloveponies"}, ), migrations.CreateModel( "ILoveMorePonies", # We use IntegerField and not AutoField because # the model is going to be deleted immediately # and with an AutoField this fails on Oracle [("id", models.IntegerField(primary_key=True))], options={"db_table": "ilovemoreponies"}, ), migrations.DeleteModel("ILoveMorePonies"), migrations.CreateModel( "ILoveEvenMorePonies", [("id", models.AutoField(primary_key=True))], options={"db_table": "iloveevenmoreponies"}, ), ] state_operations = [ migrations.CreateModel( "SomethingElse", [("id", models.AutoField(primary_key=True))], options={"db_table": "somethingelse"}, ), migrations.DeleteModel("SomethingElse"), migrations.CreateModel( "SomethingCompletelyDifferent", [("id", models.AutoField(primary_key=True))], options={"db_table": "somethingcompletelydifferent"}, ), ] operation = migrations.SeparateDatabaseAndState( state_operations=state_operations, database_operations=database_operations, ) # Test the state alteration new_state = project_state.clone() operation.state_forwards(app_label, new_state) def assertModelsAndTables(after_db): # Tables and models exist, or don't, as they should: self.assertNotIn((app_label, "somethingelse"), new_state.models) self.assertEqual( len(new_state.models[app_label, "somethingcompletelydifferent"].fields), 1, ) self.assertNotIn((app_label, "iloveponiesonies"), new_state.models) self.assertNotIn((app_label, "ilovemoreponies"), new_state.models) self.assertNotIn((app_label, "iloveevenmoreponies"), new_state.models) self.assertTableNotExists("somethingelse") self.assertTableNotExists("somethingcompletelydifferent") self.assertTableNotExists("ilovemoreponies") if after_db: self.assertTableExists("iloveponies") self.assertTableExists("iloveevenmoreponies") else: self.assertTableNotExists("iloveponies") self.assertTableNotExists("iloveevenmoreponies") assertModelsAndTables(after_db=False) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) assertModelsAndTables(after_db=True) # And test reversal self.assertTrue(operation.reversible) with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) assertModelsAndTables(after_db=False) class SwappableOperationTests(OperationTestBase): """ Key operations ignore swappable models (we don't want to replicate all of them here, as the functionality is in a common base class anyway) """ available_apps = ["migrations"] @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel") def test_create_ignore_swapped(self): """ The CreateTable operation ignores swapped models. """ operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=1)), ], options={ "swappable": "TEST_SWAP_MODEL", }, ) # Test the state alteration (it should still be there!) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crigsw", new_state) self.assertEqual(new_state.models["test_crigsw", "pony"].name, "Pony") self.assertEqual(len(new_state.models["test_crigsw", "pony"].fields), 2) # Test the database alteration self.assertTableNotExists("test_crigsw_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crigsw", editor, project_state, new_state) self.assertTableNotExists("test_crigsw_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crigsw", editor, new_state, project_state ) self.assertTableNotExists("test_crigsw_pony") @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel") def test_delete_ignore_swapped(self): """ Tests the DeleteModel operation ignores swapped models. """ operation = migrations.DeleteModel("Pony") project_state, new_state = self.make_test_state("test_dligsw", operation) # Test the database alteration self.assertTableNotExists("test_dligsw_pony") with connection.schema_editor() as editor: operation.database_forwards("test_dligsw", editor, project_state, new_state) self.assertTableNotExists("test_dligsw_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_dligsw", editor, new_state, project_state ) self.assertTableNotExists("test_dligsw_pony") @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel") def test_add_field_ignore_swapped(self): """ Tests the AddField operation. """ # Test the state alteration operation = migrations.AddField( "Pony", "height", models.FloatField(null=True, default=5), ) project_state, new_state = self.make_test_state("test_adfligsw", operation) # Test the database alteration self.assertTableNotExists("test_adfligsw_pony") with connection.schema_editor() as editor: operation.database_forwards( "test_adfligsw", editor, project_state, new_state ) self.assertTableNotExists("test_adfligsw_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_adfligsw", editor, new_state, project_state ) self.assertTableNotExists("test_adfligsw_pony") @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel") def test_indexes_ignore_swapped(self): """ Add/RemoveIndex operations ignore swapped models. """ operation = migrations.AddIndex( "Pony", models.Index(fields=["pink"], name="my_name_idx") ) project_state, new_state = self.make_test_state("test_adinigsw", operation) with connection.schema_editor() as editor: # No database queries should be run for swapped models operation.database_forwards( "test_adinigsw", editor, project_state, new_state ) operation.database_backwards( "test_adinigsw", editor, new_state, project_state ) operation = migrations.RemoveIndex( "Pony", models.Index(fields=["pink"], name="my_name_idx") ) project_state, new_state = self.make_test_state("test_rminigsw", operation) with connection.schema_editor() as editor: operation.database_forwards( "test_rminigsw", editor, project_state, new_state ) operation.database_backwards( "test_rminigsw", editor, new_state, project_state ) class TestCreateModel(SimpleTestCase): def test_references_model_mixin(self): migrations.CreateModel( "name", fields=[], bases=(Mixin, models.Model), ).references_model("other_model", "migrations") class FieldOperationTests(SimpleTestCase): def test_references_model(self): operation = FieldOperation( "MoDel", "field", models.ForeignKey("Other", models.CASCADE) ) # Model name match. self.assertIs(operation.references_model("mOdEl", "migrations"), True) # Referenced field. self.assertIs(operation.references_model("oTher", "migrations"), True) # Doesn't reference. self.assertIs(operation.references_model("Whatever", "migrations"), False) def test_references_field_by_name(self): operation = FieldOperation("MoDel", "field", models.BooleanField(default=False)) self.assertIs(operation.references_field("model", "field", "migrations"), True) def test_references_field_by_remote_field_model(self): operation = FieldOperation( "Model", "field", models.ForeignKey("Other", models.CASCADE) ) self.assertIs( operation.references_field("Other", "whatever", "migrations"), True ) self.assertIs( operation.references_field("Missing", "whatever", "migrations"), False ) def test_references_field_by_from_fields(self): operation = FieldOperation( "Model", "field", models.fields.related.ForeignObject( "Other", models.CASCADE, ["from"], ["to"] ), ) self.assertIs(operation.references_field("Model", "from", "migrations"), True) self.assertIs(operation.references_field("Model", "to", "migrations"), False) self.assertIs(operation.references_field("Other", "from", "migrations"), False) self.assertIs(operation.references_field("Model", "to", "migrations"), False) def test_references_field_by_to_fields(self): operation = FieldOperation( "Model", "field", models.ForeignKey("Other", models.CASCADE, to_field="field"), ) self.assertIs(operation.references_field("Other", "field", "migrations"), True) self.assertIs( operation.references_field("Other", "whatever", "migrations"), False ) self.assertIs( operation.references_field("Missing", "whatever", "migrations"), False ) def test_references_field_by_through(self): operation = FieldOperation( "Model", "field", models.ManyToManyField("Other", through="Through") ) self.assertIs( operation.references_field("Other", "whatever", "migrations"), True ) self.assertIs( operation.references_field("Through", "whatever", "migrations"), True ) self.assertIs( operation.references_field("Missing", "whatever", "migrations"), False ) def test_reference_field_by_through_fields(self): operation = FieldOperation( "Model", "field", models.ManyToManyField( "Other", through="Through", through_fields=("first", "second") ), ) self.assertIs( operation.references_field("Other", "whatever", "migrations"), True ) self.assertIs( operation.references_field("Through", "whatever", "migrations"), False ) self.assertIs( operation.references_field("Through", "first", "migrations"), True ) self.assertIs( operation.references_field("Through", "second", "migrations"), True )
7d4647649834712d4e02a878f094cde64154e67f6b467519fe4bb58c377913d1
import os import unittest import warnings from io import StringIO from unittest import mock from django.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles.finders import get_finder, get_finders from django.contrib.staticfiles.storage import staticfiles_storage from django.core.exceptions import ImproperlyConfigured from django.core.files.storage import default_storage from django.db import ( IntegrityError, connection, connections, models, router, transaction, ) from django.forms import ( CharField, EmailField, Form, IntegerField, ValidationError, formset_factory, ) from django.http import HttpResponse from django.template.loader import render_to_string from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.html import HTMLParseError, parse_html from django.test.testcases import DatabaseOperationForbidden from django.test.utils import ( CaptureQueriesContext, TestContextDecorator, ignore_warnings, isolate_apps, override_settings, setup_test_environment, ) from django.urls import NoReverseMatch, path, reverse, reverse_lazy from django.utils.deprecation import RemovedInDjango51Warning from django.utils.html import VOID_ELEMENTS from django.utils.version import PY311 from .models import Car, Person, PossessedCar from .views import empty_response class SkippingTestCase(SimpleTestCase): def _assert_skipping(self, func, expected_exc, msg=None): try: if msg is not None: with self.assertRaisesMessage(expected_exc, msg): func() else: with self.assertRaises(expected_exc): func() except unittest.SkipTest: self.fail("%s should not result in a skipped test." % func.__name__) def test_skip_unless_db_feature(self): """ Testing the django.test.skipUnlessDBFeature decorator. """ # Total hack, but it works, just want an attribute that's always true. @skipUnlessDBFeature("__class__") def test_func(): raise ValueError @skipUnlessDBFeature("notprovided") def test_func2(): raise ValueError @skipUnlessDBFeature("__class__", "__class__") def test_func3(): raise ValueError @skipUnlessDBFeature("__class__", "notprovided") def test_func4(): raise ValueError self._assert_skipping(test_func, ValueError) self._assert_skipping(test_func2, unittest.SkipTest) self._assert_skipping(test_func3, ValueError) self._assert_skipping(test_func4, unittest.SkipTest) class SkipTestCase(SimpleTestCase): @skipUnlessDBFeature("missing") def test_foo(self): pass self._assert_skipping( SkipTestCase("test_foo").test_foo, ValueError, "skipUnlessDBFeature cannot be used on test_foo (test_utils.tests." "SkippingTestCase.test_skip_unless_db_feature.<locals>.SkipTestCase%s) " "as SkippingTestCase.test_skip_unless_db_feature.<locals>.SkipTestCase " "doesn't allow queries against the 'default' database." # Python 3.11 uses fully qualified test name in the output. % (".test_foo" if PY311 else ""), ) def test_skip_if_db_feature(self): """ Testing the django.test.skipIfDBFeature decorator. """ @skipIfDBFeature("__class__") def test_func(): raise ValueError @skipIfDBFeature("notprovided") def test_func2(): raise ValueError @skipIfDBFeature("__class__", "__class__") def test_func3(): raise ValueError @skipIfDBFeature("__class__", "notprovided") def test_func4(): raise ValueError @skipIfDBFeature("notprovided", "notprovided") def test_func5(): raise ValueError self._assert_skipping(test_func, unittest.SkipTest) self._assert_skipping(test_func2, ValueError) self._assert_skipping(test_func3, unittest.SkipTest) self._assert_skipping(test_func4, unittest.SkipTest) self._assert_skipping(test_func5, ValueError) class SkipTestCase(SimpleTestCase): @skipIfDBFeature("missing") def test_foo(self): pass self._assert_skipping( SkipTestCase("test_foo").test_foo, ValueError, "skipIfDBFeature cannot be used on test_foo (test_utils.tests." "SkippingTestCase.test_skip_if_db_feature.<locals>.SkipTestCase%s) " "as SkippingTestCase.test_skip_if_db_feature.<locals>.SkipTestCase " "doesn't allow queries against the 'default' database." # Python 3.11 uses fully qualified test name in the output. % (".test_foo" if PY311 else ""), ) class SkippingClassTestCase(TestCase): def test_skip_class_unless_db_feature(self): @skipUnlessDBFeature("__class__") class NotSkippedTests(TestCase): def test_dummy(self): return @skipUnlessDBFeature("missing") @skipIfDBFeature("__class__") class SkippedTests(TestCase): def test_will_be_skipped(self): self.fail("We should never arrive here.") @skipIfDBFeature("__dict__") class SkippedTestsSubclass(SkippedTests): pass test_suite = unittest.TestSuite() test_suite.addTest(NotSkippedTests("test_dummy")) try: test_suite.addTest(SkippedTests("test_will_be_skipped")) test_suite.addTest(SkippedTestsSubclass("test_will_be_skipped")) except unittest.SkipTest: self.fail("SkipTest should not be raised here.") result = unittest.TextTestRunner(stream=StringIO()).run(test_suite) self.assertEqual(result.testsRun, 3) self.assertEqual(len(result.skipped), 2) self.assertEqual(result.skipped[0][1], "Database has feature(s) __class__") self.assertEqual(result.skipped[1][1], "Database has feature(s) __class__") def test_missing_default_databases(self): @skipIfDBFeature("missing") class MissingDatabases(SimpleTestCase): def test_assertion_error(self): pass suite = unittest.TestSuite() try: suite.addTest(MissingDatabases("test_assertion_error")) except unittest.SkipTest: self.fail("SkipTest should not be raised at this stage") runner = unittest.TextTestRunner(stream=StringIO()) msg = ( "skipIfDBFeature cannot be used on <class 'test_utils.tests." "SkippingClassTestCase.test_missing_default_databases.<locals>." "MissingDatabases'> as it doesn't allow queries against the " "'default' database." ) with self.assertRaisesMessage(ValueError, msg): runner.run(suite) @override_settings(ROOT_URLCONF="test_utils.urls") class AssertNumQueriesTests(TestCase): def test_assert_num_queries(self): def test_func(): raise ValueError with self.assertRaises(ValueError): self.assertNumQueries(2, test_func) def test_assert_num_queries_with_client(self): person = Person.objects.create(name="test") self.assertNumQueries( 1, self.client.get, "/test_utils/get_person/%s/" % person.pk ) self.assertNumQueries( 1, self.client.get, "/test_utils/get_person/%s/" % person.pk ) def test_func(): self.client.get("/test_utils/get_person/%s/" % person.pk) self.client.get("/test_utils/get_person/%s/" % person.pk) self.assertNumQueries(2, test_func) class AssertNumQueriesUponConnectionTests(TransactionTestCase): available_apps = [] def test_ignores_connection_configuration_queries(self): real_ensure_connection = connection.ensure_connection connection.close() def make_configuration_query(): is_opening_connection = connection.connection is None real_ensure_connection() if is_opening_connection: # Avoid infinite recursion. Creating a cursor calls # ensure_connection() which is currently mocked by this method. with connection.cursor() as cursor: cursor.execute("SELECT 1" + connection.features.bare_select_suffix) ensure_connection = ( "django.db.backends.base.base.BaseDatabaseWrapper.ensure_connection" ) with mock.patch(ensure_connection, side_effect=make_configuration_query): with self.assertNumQueries(1): list(Car.objects.all()) class AssertQuerySetEqualTests(TestCase): @classmethod def setUpTestData(cls): cls.p1 = Person.objects.create(name="p1") cls.p2 = Person.objects.create(name="p2") def test_rename_assertquerysetequal_deprecation_warning(self): msg = "assertQuerysetEqual() is deprecated in favor of assertQuerySetEqual()." with self.assertRaisesMessage(RemovedInDjango51Warning, msg): self.assertQuerysetEqual() @ignore_warnings(category=RemovedInDjango51Warning) def test_deprecated_assertquerysetequal(self): self.assertQuerysetEqual(Person.objects.filter(name="p3"), []) def test_empty(self): self.assertQuerySetEqual(Person.objects.filter(name="p3"), []) def test_ordered(self): self.assertQuerySetEqual( Person.objects.order_by("name"), [self.p1, self.p2], ) def test_unordered(self): self.assertQuerySetEqual( Person.objects.order_by("name"), [self.p2, self.p1], ordered=False ) def test_queryset(self): self.assertQuerySetEqual( Person.objects.order_by("name"), Person.objects.order_by("name"), ) def test_flat_values_list(self): self.assertQuerySetEqual( Person.objects.order_by("name").values_list("name", flat=True), ["p1", "p2"], ) def test_transform(self): self.assertQuerySetEqual( Person.objects.order_by("name"), [self.p1.pk, self.p2.pk], transform=lambda x: x.pk, ) def test_repr_transform(self): self.assertQuerySetEqual( Person.objects.order_by("name"), [repr(self.p1), repr(self.p2)], transform=repr, ) def test_undefined_order(self): # Using an unordered queryset with more than one ordered value # is an error. msg = ( "Trying to compare non-ordered queryset against more than one " "ordered value." ) with self.assertRaisesMessage(ValueError, msg): self.assertQuerySetEqual( Person.objects.all(), [self.p1, self.p2], ) # No error for one value. self.assertQuerySetEqual(Person.objects.filter(name="p1"), [self.p1]) def test_repeated_values(self): """ assertQuerySetEqual checks the number of appearance of each item when used with option ordered=False. """ batmobile = Car.objects.create(name="Batmobile") k2000 = Car.objects.create(name="K 2000") PossessedCar.objects.bulk_create( [ PossessedCar(car=batmobile, belongs_to=self.p1), PossessedCar(car=batmobile, belongs_to=self.p1), PossessedCar(car=k2000, belongs_to=self.p1), PossessedCar(car=k2000, belongs_to=self.p1), PossessedCar(car=k2000, belongs_to=self.p1), PossessedCar(car=k2000, belongs_to=self.p1), ] ) with self.assertRaises(AssertionError): self.assertQuerySetEqual( self.p1.cars.all(), [batmobile, k2000], ordered=False ) self.assertQuerySetEqual( self.p1.cars.all(), [batmobile] * 2 + [k2000] * 4, ordered=False ) def test_maxdiff(self): names = ["Joe Smith %s" % i for i in range(20)] Person.objects.bulk_create([Person(name=name) for name in names]) names.append("Extra Person") with self.assertRaises(AssertionError) as ctx: self.assertQuerySetEqual( Person.objects.filter(name__startswith="Joe"), names, ordered=False, transform=lambda p: p.name, ) self.assertIn("Set self.maxDiff to None to see it.", str(ctx.exception)) original = self.maxDiff self.maxDiff = None try: with self.assertRaises(AssertionError) as ctx: self.assertQuerySetEqual( Person.objects.filter(name__startswith="Joe"), names, ordered=False, transform=lambda p: p.name, ) finally: self.maxDiff = original exception_msg = str(ctx.exception) self.assertNotIn("Set self.maxDiff to None to see it.", exception_msg) for name in names: self.assertIn(name, exception_msg) @override_settings(ROOT_URLCONF="test_utils.urls") class CaptureQueriesContextManagerTests(TestCase): @classmethod def setUpTestData(cls): cls.person_pk = str(Person.objects.create(name="test").pk) def test_simple(self): with CaptureQueriesContext(connection) as captured_queries: Person.objects.get(pk=self.person_pk) self.assertEqual(len(captured_queries), 1) self.assertIn(self.person_pk, captured_queries[0]["sql"]) with CaptureQueriesContext(connection) as captured_queries: pass self.assertEqual(0, len(captured_queries)) def test_within(self): with CaptureQueriesContext(connection) as captured_queries: Person.objects.get(pk=self.person_pk) self.assertEqual(len(captured_queries), 1) self.assertIn(self.person_pk, captured_queries[0]["sql"]) def test_nested(self): with CaptureQueriesContext(connection) as captured_queries: Person.objects.count() with CaptureQueriesContext(connection) as nested_captured_queries: Person.objects.count() self.assertEqual(1, len(nested_captured_queries)) self.assertEqual(2, len(captured_queries)) def test_failure(self): with self.assertRaises(TypeError): with CaptureQueriesContext(connection): raise TypeError def test_with_client(self): with CaptureQueriesContext(connection) as captured_queries: self.client.get("/test_utils/get_person/%s/" % self.person_pk) self.assertEqual(len(captured_queries), 1) self.assertIn(self.person_pk, captured_queries[0]["sql"]) with CaptureQueriesContext(connection) as captured_queries: self.client.get("/test_utils/get_person/%s/" % self.person_pk) self.assertEqual(len(captured_queries), 1) self.assertIn(self.person_pk, captured_queries[0]["sql"]) with CaptureQueriesContext(connection) as captured_queries: self.client.get("/test_utils/get_person/%s/" % self.person_pk) self.client.get("/test_utils/get_person/%s/" % self.person_pk) self.assertEqual(len(captured_queries), 2) self.assertIn(self.person_pk, captured_queries[0]["sql"]) self.assertIn(self.person_pk, captured_queries[1]["sql"]) @override_settings(ROOT_URLCONF="test_utils.urls") class AssertNumQueriesContextManagerTests(TestCase): def test_simple(self): with self.assertNumQueries(0): pass with self.assertNumQueries(1): Person.objects.count() with self.assertNumQueries(2): Person.objects.count() Person.objects.count() def test_failure(self): msg = "1 != 2 : 1 queries executed, 2 expected\nCaptured queries were:\n1." with self.assertRaisesMessage(AssertionError, msg): with self.assertNumQueries(2): Person.objects.count() with self.assertRaises(TypeError): with self.assertNumQueries(4000): raise TypeError def test_with_client(self): person = Person.objects.create(name="test") with self.assertNumQueries(1): self.client.get("/test_utils/get_person/%s/" % person.pk) with self.assertNumQueries(1): self.client.get("/test_utils/get_person/%s/" % person.pk) with self.assertNumQueries(2): self.client.get("/test_utils/get_person/%s/" % person.pk) self.client.get("/test_utils/get_person/%s/" % person.pk) @override_settings(ROOT_URLCONF="test_utils.urls") class AssertTemplateUsedContextManagerTests(SimpleTestCase): def test_usage(self): with self.assertTemplateUsed("template_used/base.html"): render_to_string("template_used/base.html") with self.assertTemplateUsed(template_name="template_used/base.html"): render_to_string("template_used/base.html") with self.assertTemplateUsed("template_used/base.html"): render_to_string("template_used/include.html") with self.assertTemplateUsed("template_used/base.html"): render_to_string("template_used/extends.html") with self.assertTemplateUsed("template_used/base.html"): render_to_string("template_used/base.html") render_to_string("template_used/base.html") def test_nested_usage(self): with self.assertTemplateUsed("template_used/base.html"): with self.assertTemplateUsed("template_used/include.html"): render_to_string("template_used/include.html") with self.assertTemplateUsed("template_used/extends.html"): with self.assertTemplateUsed("template_used/base.html"): render_to_string("template_used/extends.html") with self.assertTemplateUsed("template_used/base.html"): with self.assertTemplateUsed("template_used/alternative.html"): render_to_string("template_used/alternative.html") render_to_string("template_used/base.html") with self.assertTemplateUsed("template_used/base.html"): render_to_string("template_used/extends.html") with self.assertTemplateNotUsed("template_used/base.html"): render_to_string("template_used/alternative.html") render_to_string("template_used/base.html") def test_not_used(self): with self.assertTemplateNotUsed("template_used/base.html"): pass with self.assertTemplateNotUsed("template_used/alternative.html"): pass def test_error_message(self): msg = "No templates used to render the response" with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed("template_used/base.html"): pass with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed(template_name="template_used/base.html"): pass msg2 = ( "Template 'template_used/base.html' was not a template used to render " "the response. Actual template(s) used: template_used/alternative.html" ) with self.assertRaisesMessage(AssertionError, msg2): with self.assertTemplateUsed("template_used/base.html"): render_to_string("template_used/alternative.html") with self.assertRaisesMessage( AssertionError, "No templates used to render the response" ): response = self.client.get("/test_utils/no_template_used/") self.assertTemplateUsed(response, "template_used/base.html") def test_msg_prefix(self): msg_prefix = "Prefix" msg = f"{msg_prefix}: No templates used to render the response" with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed( "template_used/base.html", msg_prefix=msg_prefix ): pass with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed( template_name="template_used/base.html", msg_prefix=msg_prefix, ): pass msg = ( f"{msg_prefix}: Template 'template_used/base.html' was not a " f"template used to render the response. Actual template(s) used: " f"template_used/alternative.html" ) with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed( "template_used/base.html", msg_prefix=msg_prefix ): render_to_string("template_used/alternative.html") def test_count(self): with self.assertTemplateUsed("template_used/base.html", count=2): render_to_string("template_used/base.html") render_to_string("template_used/base.html") msg = ( "Template 'template_used/base.html' was expected to be rendered " "3 time(s) but was actually rendered 2 time(s)." ) with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed("template_used/base.html", count=3): render_to_string("template_used/base.html") render_to_string("template_used/base.html") def test_failure(self): msg = "response and/or template_name argument must be provided" with self.assertRaisesMessage(TypeError, msg): with self.assertTemplateUsed(): pass msg = "No templates used to render the response" with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed(""): pass with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed(""): render_to_string("template_used/base.html") with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed(template_name=""): pass msg = ( "Template 'template_used/base.html' was not a template used to " "render the response. Actual template(s) used: " "template_used/alternative.html" ) with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed("template_used/base.html"): render_to_string("template_used/alternative.html") def test_assert_used_on_http_response(self): response = HttpResponse() msg = "%s() is only usable on responses fetched using the Django test Client." with self.assertRaisesMessage(ValueError, msg % "assertTemplateUsed"): self.assertTemplateUsed(response, "template.html") with self.assertRaisesMessage(ValueError, msg % "assertTemplateNotUsed"): self.assertTemplateNotUsed(response, "template.html") class HTMLEqualTests(SimpleTestCase): def test_html_parser(self): element = parse_html("<div><p>Hello</p></div>") self.assertEqual(len(element.children), 1) self.assertEqual(element.children[0].name, "p") self.assertEqual(element.children[0].children[0], "Hello") parse_html("<p>") parse_html("<p attr>") dom = parse_html("<p>foo") self.assertEqual(len(dom.children), 1) self.assertEqual(dom.name, "p") self.assertEqual(dom[0], "foo") def test_parse_html_in_script(self): parse_html('<script>var a = "<p" + ">";</script>') parse_html( """ <script> var js_sha_link='<p>***</p>'; </script> """ ) # script content will be parsed to text dom = parse_html( """ <script><p>foo</p> '</scr'+'ipt>' <span>bar</span></script> """ ) self.assertEqual(len(dom.children), 1) self.assertEqual(dom.children[0], "<p>foo</p> '</scr'+'ipt>' <span>bar</span>") def test_void_elements(self): for tag in VOID_ELEMENTS: with self.subTest(tag): dom = parse_html("<p>Hello <%s> world</p>" % tag) self.assertEqual(len(dom.children), 3) self.assertEqual(dom[0], "Hello") self.assertEqual(dom[1].name, tag) self.assertEqual(dom[2], "world") dom = parse_html("<p>Hello <%s /> world</p>" % tag) self.assertEqual(len(dom.children), 3) self.assertEqual(dom[0], "Hello") self.assertEqual(dom[1].name, tag) self.assertEqual(dom[2], "world") def test_simple_equal_html(self): self.assertHTMLEqual("", "") self.assertHTMLEqual("<p></p>", "<p></p>") self.assertHTMLEqual("<p></p>", " <p> </p> ") self.assertHTMLEqual("<div><p>Hello</p></div>", "<div><p>Hello</p></div>") self.assertHTMLEqual("<div><p>Hello</p></div>", "<div> <p>Hello</p> </div>") self.assertHTMLEqual("<div>\n<p>Hello</p></div>", "<div><p>Hello</p></div>\n") self.assertHTMLEqual( "<div><p>Hello\nWorld !</p></div>", "<div><p>Hello World\n!</p></div>" ) self.assertHTMLEqual( "<div><p>Hello\nWorld !</p></div>", "<div><p>Hello World\n!</p></div>" ) self.assertHTMLEqual("<p>Hello World !</p>", "<p>Hello World\n\n!</p>") self.assertHTMLEqual("<p> </p>", "<p></p>") self.assertHTMLEqual("<p/>", "<p></p>") self.assertHTMLEqual("<p />", "<p></p>") self.assertHTMLEqual("<input checked>", '<input checked="checked">') self.assertHTMLEqual("<p>Hello", "<p> Hello") self.assertHTMLEqual("<p>Hello</p>World", "<p>Hello</p> World") def test_ignore_comments(self): self.assertHTMLEqual( "<div>Hello<!-- this is a comment --> World!</div>", "<div>Hello World!</div>", ) def test_unequal_html(self): self.assertHTMLNotEqual("<p>Hello</p>", "<p>Hello!</p>") self.assertHTMLNotEqual("<p>foo&#20;bar</p>", "<p>foo&nbsp;bar</p>") self.assertHTMLNotEqual("<p>foo bar</p>", "<p>foo &nbsp;bar</p>") self.assertHTMLNotEqual("<p>foo nbsp</p>", "<p>foo &nbsp;</p>") self.assertHTMLNotEqual("<p>foo #20</p>", "<p>foo &#20;</p>") self.assertHTMLNotEqual( "<p><span>Hello</span><span>World</span></p>", "<p><span>Hello</span>World</p>", ) self.assertHTMLNotEqual( "<p><span>Hello</span>World</p>", "<p><span>Hello</span><span>World</span></p>", ) def test_attributes(self): self.assertHTMLEqual( '<input type="text" id="id_name" />', '<input id="id_name" type="text" />' ) self.assertHTMLEqual( """<input type='text' id="id_name" />""", '<input id="id_name" type="text" />', ) self.assertHTMLNotEqual( '<input type="text" id="id_name" />', '<input type="password" id="id_name" />', ) def test_class_attribute(self): pairs = [ ('<p class="foo bar"></p>', '<p class="bar foo"></p>'), ('<p class=" foo bar "></p>', '<p class="bar foo"></p>'), ('<p class=" foo bar "></p>', '<p class="bar foo"></p>'), ('<p class="foo\tbar"></p>', '<p class="bar foo"></p>'), ('<p class="\tfoo\tbar\t"></p>', '<p class="bar foo"></p>'), ('<p class="\t\t\tfoo\t\t\tbar\t\t\t"></p>', '<p class="bar foo"></p>'), ('<p class="\t \nfoo \t\nbar\n\t "></p>', '<p class="bar foo"></p>'), ] for html1, html2 in pairs: with self.subTest(html1): self.assertHTMLEqual(html1, html2) def test_boolean_attribute(self): html1 = "<input checked>" html2 = '<input checked="">' html3 = '<input checked="checked">' self.assertHTMLEqual(html1, html2) self.assertHTMLEqual(html1, html3) self.assertHTMLEqual(html2, html3) self.assertHTMLNotEqual(html1, '<input checked="invalid">') self.assertEqual(str(parse_html(html1)), "<input checked>") self.assertEqual(str(parse_html(html2)), "<input checked>") self.assertEqual(str(parse_html(html3)), "<input checked>") def test_non_boolean_attibutes(self): html1 = "<input value>" html2 = '<input value="">' html3 = '<input value="value">' self.assertHTMLEqual(html1, html2) self.assertHTMLNotEqual(html1, html3) self.assertEqual(str(parse_html(html1)), '<input value="">') self.assertEqual(str(parse_html(html2)), '<input value="">') def test_normalize_refs(self): pairs = [ ("&#39;", "&#x27;"), ("&#39;", "'"), ("&#x27;", "&#39;"), ("&#x27;", "'"), ("'", "&#39;"), ("'", "&#x27;"), ("&amp;", "&#38;"), ("&amp;", "&#x26;"), ("&amp;", "&"), ("&#38;", "&amp;"), ("&#38;", "&#x26;"), ("&#38;", "&"), ("&#x26;", "&amp;"), ("&#x26;", "&#38;"), ("&#x26;", "&"), ("&", "&amp;"), ("&", "&#38;"), ("&", "&#x26;"), ] for pair in pairs: with self.subTest(repr(pair)): self.assertHTMLEqual(*pair) def test_complex_examples(self): self.assertHTMLEqual( """<tr><th><label for="id_first_name">First name:</label></th> <td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr> <tr><th><label for="id_last_name">Last name:</label></th> <td><input type="text" id="id_last_name" name="last_name" value="Lennon" /></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th> <td><input type="text" value="1940-10-9" name="birthday" id="id_birthday" /></td></tr>""", # NOQA """ <tr><th> <label for="id_first_name">First name:</label></th><td> <input type="text" name="first_name" value="John" id="id_first_name" /> </td></tr> <tr><th> <label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" value="Lennon" id="id_last_name" /> </td></tr> <tr><th> <label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /> </td></tr> """, ) self.assertHTMLEqual( """<!DOCTYPE html> <html> <head> <link rel="stylesheet"> <title>Document</title> <meta attribute="value"> </head> <body> <p> This is a valid paragraph <div> this is a div AFTER the p</div> </body> </html>""", """ <html> <head> <link rel="stylesheet"> <title>Document</title> <meta attribute="value"> </head> <body> <p> This is a valid paragraph <!-- browsers would close the p tag here --> <div> this is a div AFTER the p</div> </p> <!-- this is invalid HTML parsing, but it should make no difference in most cases --> </body> </html>""", ) def test_html_contain(self): # equal html contains each other dom1 = parse_html("<p>foo") dom2 = parse_html("<p>foo</p>") self.assertIn(dom1, dom2) self.assertIn(dom2, dom1) dom2 = parse_html("<div><p>foo</p></div>") self.assertIn(dom1, dom2) self.assertNotIn(dom2, dom1) self.assertNotIn("<p>foo</p>", dom2) self.assertIn("foo", dom2) # when a root element is used ... dom1 = parse_html("<p>foo</p><p>bar</p>") dom2 = parse_html("<p>foo</p><p>bar</p>") self.assertIn(dom1, dom2) dom1 = parse_html("<p>foo</p>") self.assertIn(dom1, dom2) dom1 = parse_html("<p>bar</p>") self.assertIn(dom1, dom2) dom1 = parse_html("<div><p>foo</p><p>bar</p></div>") self.assertIn(dom2, dom1) def test_count(self): # equal html contains each other one time dom1 = parse_html("<p>foo") dom2 = parse_html("<p>foo</p>") self.assertEqual(dom1.count(dom2), 1) self.assertEqual(dom2.count(dom1), 1) dom2 = parse_html("<p>foo</p><p>bar</p>") self.assertEqual(dom2.count(dom1), 1) dom2 = parse_html("<p>foo foo</p><p>foo</p>") self.assertEqual(dom2.count("foo"), 3) dom2 = parse_html('<p class="bar">foo</p>') self.assertEqual(dom2.count("bar"), 0) self.assertEqual(dom2.count("class"), 0) self.assertEqual(dom2.count("p"), 0) self.assertEqual(dom2.count("o"), 2) dom2 = parse_html("<p>foo</p><p>foo</p>") self.assertEqual(dom2.count(dom1), 2) dom2 = parse_html('<div><p>foo<input type=""></p><p>foo</p></div>') self.assertEqual(dom2.count(dom1), 1) dom2 = parse_html("<div><div><p>foo</p></div></div>") self.assertEqual(dom2.count(dom1), 1) dom2 = parse_html("<p>foo<p>foo</p></p>") self.assertEqual(dom2.count(dom1), 1) dom2 = parse_html("<p>foo<p>bar</p></p>") self.assertEqual(dom2.count(dom1), 0) # HTML with a root element contains the same HTML with no root element. dom1 = parse_html("<p>foo</p><p>bar</p>") dom2 = parse_html("<div><p>foo</p><p>bar</p></div>") self.assertEqual(dom2.count(dom1), 1) # Target of search is a sequence of child elements and appears more # than once. dom2 = parse_html("<div><p>foo</p><p>bar</p><p>foo</p><p>bar</p></div>") self.assertEqual(dom2.count(dom1), 2) # Searched HTML has additional children. dom1 = parse_html("<a/><b/>") dom2 = parse_html("<a/><b/><c/>") self.assertEqual(dom2.count(dom1), 1) # No match found in children. dom1 = parse_html("<b/><a/>") self.assertEqual(dom2.count(dom1), 0) # Target of search found among children and grandchildren. dom1 = parse_html("<b/><b/>") dom2 = parse_html("<a><b/><b/></a><b/><b/>") self.assertEqual(dom2.count(dom1), 2) def test_root_element_escaped_html(self): html = "&lt;br&gt;" parsed = parse_html(html) self.assertEqual(str(parsed), html) def test_parsing_errors(self): with self.assertRaises(AssertionError): self.assertHTMLEqual("<p>", "") with self.assertRaises(AssertionError): self.assertHTMLEqual("", "<p>") error_msg = ( "First argument is not valid HTML:\n" "('Unexpected end tag `div` (Line 1, Column 6)', (1, 6))" ) with self.assertRaisesMessage(AssertionError, error_msg): self.assertHTMLEqual("< div></ div>", "<div></div>") with self.assertRaises(HTMLParseError): parse_html("</p>") def test_escaped_html_errors(self): msg = "<p>\n<foo>\n</p> != <p>\n&lt;foo&gt;\n</p>\n" with self.assertRaisesMessage(AssertionError, msg): self.assertHTMLEqual("<p><foo></p>", "<p>&lt;foo&gt;</p>") with self.assertRaisesMessage(AssertionError, msg): self.assertHTMLEqual("<p><foo></p>", "<p>&#60;foo&#62;</p>") def test_contains_html(self): response = HttpResponse( """<body> This is a form: <form method="get"> <input type="text" name="Hello" /> </form></body>""" ) self.assertNotContains(response, "<input name='Hello' type='text'>") self.assertContains(response, '<form method="get">') self.assertContains(response, "<input name='Hello' type='text'>", html=True) self.assertNotContains(response, '<form method="get">', html=True) invalid_response = HttpResponse("""<body <bad>>""") with self.assertRaises(AssertionError): self.assertContains(invalid_response, "<p></p>") with self.assertRaises(AssertionError): self.assertContains(response, '<p "whats" that>') def test_unicode_handling(self): response = HttpResponse( '<p class="help">Some help text for the title (with Unicode ŠĐĆŽćžšđ)</p>' ) self.assertContains( response, '<p class="help">Some help text for the title (with Unicode ŠĐĆŽćžšđ)</p>', html=True, ) class JSONEqualTests(SimpleTestCase): def test_simple_equal(self): json1 = '{"attr1": "foo", "attr2":"baz"}' json2 = '{"attr1": "foo", "attr2":"baz"}' self.assertJSONEqual(json1, json2) def test_simple_equal_unordered(self): json1 = '{"attr1": "foo", "attr2":"baz"}' json2 = '{"attr2":"baz", "attr1": "foo"}' self.assertJSONEqual(json1, json2) def test_simple_equal_raise(self): json1 = '{"attr1": "foo", "attr2":"baz"}' json2 = '{"attr2":"baz"}' with self.assertRaises(AssertionError): self.assertJSONEqual(json1, json2) def test_equal_parsing_errors(self): invalid_json = '{"attr1": "foo, "attr2":"baz"}' valid_json = '{"attr1": "foo", "attr2":"baz"}' with self.assertRaises(AssertionError): self.assertJSONEqual(invalid_json, valid_json) with self.assertRaises(AssertionError): self.assertJSONEqual(valid_json, invalid_json) def test_simple_not_equal(self): json1 = '{"attr1": "foo", "attr2":"baz"}' json2 = '{"attr2":"baz"}' self.assertJSONNotEqual(json1, json2) def test_simple_not_equal_raise(self): json1 = '{"attr1": "foo", "attr2":"baz"}' json2 = '{"attr1": "foo", "attr2":"baz"}' with self.assertRaises(AssertionError): self.assertJSONNotEqual(json1, json2) def test_not_equal_parsing_errors(self): invalid_json = '{"attr1": "foo, "attr2":"baz"}' valid_json = '{"attr1": "foo", "attr2":"baz"}' with self.assertRaises(AssertionError): self.assertJSONNotEqual(invalid_json, valid_json) with self.assertRaises(AssertionError): self.assertJSONNotEqual(valid_json, invalid_json) class XMLEqualTests(SimpleTestCase): def test_simple_equal(self): xml1 = "<elem attr1='a' attr2='b' />" xml2 = "<elem attr1='a' attr2='b' />" self.assertXMLEqual(xml1, xml2) def test_simple_equal_unordered(self): xml1 = "<elem attr1='a' attr2='b' />" xml2 = "<elem attr2='b' attr1='a' />" self.assertXMLEqual(xml1, xml2) def test_simple_equal_raise(self): xml1 = "<elem attr1='a' />" xml2 = "<elem attr2='b' attr1='a' />" with self.assertRaises(AssertionError): self.assertXMLEqual(xml1, xml2) def test_simple_equal_raises_message(self): xml1 = "<elem attr1='a' />" xml2 = "<elem attr2='b' attr1='a' />" msg = """{xml1} != {xml2} - <elem attr1='a' /> + <elem attr2='b' attr1='a' /> ? ++++++++++ """.format( xml1=repr(xml1), xml2=repr(xml2) ) with self.assertRaisesMessage(AssertionError, msg): self.assertXMLEqual(xml1, xml2) def test_simple_not_equal(self): xml1 = "<elem attr1='a' attr2='c' />" xml2 = "<elem attr1='a' attr2='b' />" self.assertXMLNotEqual(xml1, xml2) def test_simple_not_equal_raise(self): xml1 = "<elem attr1='a' attr2='b' />" xml2 = "<elem attr2='b' attr1='a' />" with self.assertRaises(AssertionError): self.assertXMLNotEqual(xml1, xml2) def test_parsing_errors(self): xml_unvalid = "<elem attr1='a attr2='b' />" xml2 = "<elem attr2='b' attr1='a' />" with self.assertRaises(AssertionError): self.assertXMLNotEqual(xml_unvalid, xml2) def test_comment_root(self): xml1 = "<?xml version='1.0'?><!-- comment1 --><elem attr1='a' attr2='b' />" xml2 = "<?xml version='1.0'?><!-- comment2 --><elem attr2='b' attr1='a' />" self.assertXMLEqual(xml1, xml2) def test_simple_equal_with_leading_or_trailing_whitespace(self): xml1 = "<elem>foo</elem> \t\n" xml2 = " \t\n<elem>foo</elem>" self.assertXMLEqual(xml1, xml2) def test_simple_not_equal_with_whitespace_in_the_middle(self): xml1 = "<elem>foo</elem><elem>bar</elem>" xml2 = "<elem>foo</elem> <elem>bar</elem>" self.assertXMLNotEqual(xml1, xml2) def test_doctype_root(self): xml1 = '<?xml version="1.0"?><!DOCTYPE root SYSTEM "example1.dtd"><root />' xml2 = '<?xml version="1.0"?><!DOCTYPE root SYSTEM "example2.dtd"><root />' self.assertXMLEqual(xml1, xml2) def test_processing_instruction(self): xml1 = ( '<?xml version="1.0"?>' '<?xml-model href="http://www.example1.com"?><root />' ) xml2 = ( '<?xml version="1.0"?>' '<?xml-model href="http://www.example2.com"?><root />' ) self.assertXMLEqual(xml1, xml2) self.assertXMLEqual( '<?xml-stylesheet href="style1.xslt" type="text/xsl"?><root />', '<?xml-stylesheet href="style2.xslt" type="text/xsl"?><root />', ) class SkippingExtraTests(TestCase): fixtures = ["should_not_be_loaded.json"] # HACK: This depends on internals of our TestCase subclasses def __call__(self, result=None): # Detect fixture loading by counting SQL queries, should be zero with self.assertNumQueries(0): super().__call__(result) @unittest.skip("Fixture loading should not be performed for skipped tests.") def test_fixtures_are_skipped(self): pass class AssertRaisesMsgTest(SimpleTestCase): def test_assert_raises_message(self): msg = "'Expected message' not found in 'Unexpected message'" # context manager form of assertRaisesMessage() with self.assertRaisesMessage(AssertionError, msg): with self.assertRaisesMessage(ValueError, "Expected message"): raise ValueError("Unexpected message") # callable form def func(): raise ValueError("Unexpected message") with self.assertRaisesMessage(AssertionError, msg): self.assertRaisesMessage(ValueError, "Expected message", func) def test_special_re_chars(self): """assertRaisesMessage shouldn't interpret RE special chars.""" def func1(): raise ValueError("[.*x+]y?") with self.assertRaisesMessage(ValueError, "[.*x+]y?"): func1() class AssertWarnsMessageTests(SimpleTestCase): def test_context_manager(self): with self.assertWarnsMessage(UserWarning, "Expected message"): warnings.warn("Expected message", UserWarning) def test_context_manager_failure(self): msg = "Expected message' not found in 'Unexpected message'" with self.assertRaisesMessage(AssertionError, msg): with self.assertWarnsMessage(UserWarning, "Expected message"): warnings.warn("Unexpected message", UserWarning) def test_callable(self): def func(): warnings.warn("Expected message", UserWarning) self.assertWarnsMessage(UserWarning, "Expected message", func) def test_special_re_chars(self): def func1(): warnings.warn("[.*x+]y?", UserWarning) with self.assertWarnsMessage(UserWarning, "[.*x+]y?"): func1() class AssertFieldOutputTests(SimpleTestCase): def test_assert_field_output(self): error_invalid = ["Enter a valid email address."] self.assertFieldOutput( EmailField, {"[email protected]": "[email protected]"}, {"aaa": error_invalid} ) with self.assertRaises(AssertionError): self.assertFieldOutput( EmailField, {"[email protected]": "[email protected]"}, {"aaa": error_invalid + ["Another error"]}, ) with self.assertRaises(AssertionError): self.assertFieldOutput( EmailField, {"[email protected]": "Wrong output"}, {"aaa": error_invalid} ) with self.assertRaises(AssertionError): self.assertFieldOutput( EmailField, {"[email protected]": "[email protected]"}, {"aaa": ["Come on, gimme some well formatted data, dude."]}, ) def test_custom_required_message(self): class MyCustomField(IntegerField): default_error_messages = { "required": "This is really required.", } self.assertFieldOutput(MyCustomField, {}, {}, empty_value=None) @override_settings(ROOT_URLCONF="test_utils.urls") class AssertURLEqualTests(SimpleTestCase): def test_equal(self): valid_tests = ( ("http://example.com/?", "http://example.com/"), ("http://example.com/?x=1&", "http://example.com/?x=1"), ("http://example.com/?x=1&y=2", "http://example.com/?y=2&x=1"), ("http://example.com/?x=1&y=2", "http://example.com/?y=2&x=1"), ( "http://example.com/?x=1&y=2&a=1&a=2", "http://example.com/?a=1&a=2&y=2&x=1", ), ("/path/to/?x=1&y=2&z=3", "/path/to/?z=3&y=2&x=1"), ("?x=1&y=2&z=3", "?z=3&y=2&x=1"), ("/test_utils/no_template_used/", reverse_lazy("no_template_used")), ) for url1, url2 in valid_tests: with self.subTest(url=url1): self.assertURLEqual(url1, url2) def test_not_equal(self): invalid_tests = ( # Protocol must be the same. ("http://example.com/", "https://example.com/"), ("http://example.com/?x=1&x=2", "https://example.com/?x=2&x=1"), ("http://example.com/?x=1&y=bar&x=2", "https://example.com/?y=bar&x=2&x=1"), # Parameters of the same name must be in the same order. ("/path/to?a=1&a=2", "/path/to/?a=2&a=1"), ) for url1, url2 in invalid_tests: with self.subTest(url=url1), self.assertRaises(AssertionError): self.assertURLEqual(url1, url2) def test_message(self): msg = ( "Expected 'http://example.com/?x=1&x=2' to equal " "'https://example.com/?x=2&x=1'" ) with self.assertRaisesMessage(AssertionError, msg): self.assertURLEqual( "http://example.com/?x=1&x=2", "https://example.com/?x=2&x=1" ) def test_msg_prefix(self): msg = ( "Prefix: Expected 'http://example.com/?x=1&x=2' to equal " "'https://example.com/?x=2&x=1'" ) with self.assertRaisesMessage(AssertionError, msg): self.assertURLEqual( "http://example.com/?x=1&x=2", "https://example.com/?x=2&x=1", msg_prefix="Prefix: ", ) class TestForm(Form): field = CharField() def clean_field(self): value = self.cleaned_data.get("field", "") if value == "invalid": raise ValidationError("invalid value") return value def clean(self): if self.cleaned_data.get("field") == "invalid_non_field": raise ValidationError("non-field error") return self.cleaned_data @classmethod def _get_cleaned_form(cls, field_value): form = cls({"field": field_value}) form.full_clean() return form @classmethod def valid(cls): return cls._get_cleaned_form("valid") @classmethod def invalid(cls, nonfield=False): return cls._get_cleaned_form("invalid_non_field" if nonfield else "invalid") class TestFormset(formset_factory(TestForm)): @classmethod def _get_cleaned_formset(cls, field_value): formset = cls( { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "0", "form-0-field": field_value, } ) formset.full_clean() return formset @classmethod def valid(cls): return cls._get_cleaned_formset("valid") @classmethod def invalid(cls, nonfield=False, nonform=False): if nonform: formset = cls({}, error_messages={"missing_management_form": "error"}) formset.full_clean() return formset return cls._get_cleaned_formset("invalid_non_field" if nonfield else "invalid") class AssertFormErrorTests(SimpleTestCase): def test_single_error(self): self.assertFormError(TestForm.invalid(), "field", "invalid value") def test_error_list(self): self.assertFormError(TestForm.invalid(), "field", ["invalid value"]) def test_empty_errors_valid_form(self): self.assertFormError(TestForm.valid(), "field", []) def test_empty_errors_valid_form_non_field_errors(self): self.assertFormError(TestForm.valid(), None, []) def test_field_not_in_form(self): msg = ( "The form <TestForm bound=True, valid=False, fields=(field)> does not " "contain the field 'other_field'." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormError(TestForm.invalid(), "other_field", "invalid value") msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormError( TestForm.invalid(), "other_field", "invalid value", msg_prefix=msg_prefix, ) def test_field_with_no_errors(self): msg = ( "The errors of field 'field' on form <TestForm bound=True, valid=True, " "fields=(field)> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormError(TestForm.valid(), "field", "invalid value") self.assertIn("[] != ['invalid value']", str(ctx.exception)) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormError( TestForm.valid(), "field", "invalid value", msg_prefix=msg_prefix ) def test_field_with_different_error(self): msg = ( "The errors of field 'field' on form <TestForm bound=True, valid=False, " "fields=(field)> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormError(TestForm.invalid(), "field", "other error") self.assertIn("['invalid value'] != ['other error']", str(ctx.exception)) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormError( TestForm.invalid(), "field", "other error", msg_prefix=msg_prefix ) def test_unbound_form(self): msg = ( "The form <TestForm bound=False, valid=Unknown, fields=(field)> is not " "bound, it will never have any errors." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormError(TestForm(), "field", []) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormError(TestForm(), "field", [], msg_prefix=msg_prefix) def test_empty_errors_invalid_form(self): msg = ( "The errors of field 'field' on form <TestForm bound=True, valid=False, " "fields=(field)> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormError(TestForm.invalid(), "field", []) self.assertIn("['invalid value'] != []", str(ctx.exception)) def test_non_field_errors(self): self.assertFormError(TestForm.invalid(nonfield=True), None, "non-field error") def test_different_non_field_errors(self): msg = ( "The non-field errors of form <TestForm bound=True, valid=False, " "fields=(field)> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormError( TestForm.invalid(nonfield=True), None, "other non-field error" ) self.assertIn( "['non-field error'] != ['other non-field error']", str(ctx.exception) ) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormError( TestForm.invalid(nonfield=True), None, "other non-field error", msg_prefix=msg_prefix, ) class AssertFormSetErrorTests(SimpleTestCase): def test_rename_assertformseterror_deprecation_warning(self): msg = "assertFormsetError() is deprecated in favor of assertFormSetError()." with self.assertRaisesMessage(RemovedInDjango51Warning, msg): self.assertFormsetError() @ignore_warnings(category=RemovedInDjango51Warning) def test_deprecated_assertformseterror(self): self.assertFormsetError(TestFormset.invalid(), 0, "field", "invalid value") def test_single_error(self): self.assertFormSetError(TestFormset.invalid(), 0, "field", "invalid value") def test_error_list(self): self.assertFormSetError(TestFormset.invalid(), 0, "field", ["invalid value"]) def test_empty_errors_valid_formset(self): self.assertFormSetError(TestFormset.valid(), 0, "field", []) def test_multiple_forms(self): formset = TestFormset( { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "0", "form-0-field": "valid", "form-1-field": "invalid", } ) formset.full_clean() self.assertFormSetError(formset, 0, "field", []) self.assertFormSetError(formset, 1, "field", ["invalid value"]) def test_field_not_in_form(self): msg = ( "The form 0 of formset <TestFormset: bound=True valid=False total_forms=1> " "does not contain the field 'other_field'." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormSetError( TestFormset.invalid(), 0, "other_field", "invalid value" ) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormSetError( TestFormset.invalid(), 0, "other_field", "invalid value", msg_prefix=msg_prefix, ) def test_field_with_no_errors(self): msg = ( "The errors of field 'field' on form 0 of formset <TestFormset: bound=True " "valid=True total_forms=1> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormSetError(TestFormset.valid(), 0, "field", "invalid value") self.assertIn("[] != ['invalid value']", str(ctx.exception)) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormSetError( TestFormset.valid(), 0, "field", "invalid value", msg_prefix=msg_prefix ) def test_field_with_different_error(self): msg = ( "The errors of field 'field' on form 0 of formset <TestFormset: bound=True " "valid=False total_forms=1> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormSetError(TestFormset.invalid(), 0, "field", "other error") self.assertIn("['invalid value'] != ['other error']", str(ctx.exception)) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormSetError( TestFormset.invalid(), 0, "field", "other error", msg_prefix=msg_prefix ) def test_unbound_formset(self): msg = ( "The formset <TestFormset: bound=False valid=Unknown total_forms=1> is not " "bound, it will never have any errors." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormSetError(TestFormset(), 0, "field", []) def test_empty_errors_invalid_formset(self): msg = ( "The errors of field 'field' on form 0 of formset <TestFormset: bound=True " "valid=False total_forms=1> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormSetError(TestFormset.invalid(), 0, "field", []) self.assertIn("['invalid value'] != []", str(ctx.exception)) def test_non_field_errors(self): self.assertFormSetError( TestFormset.invalid(nonfield=True), 0, None, "non-field error" ) def test_different_non_field_errors(self): msg = ( "The non-field errors of form 0 of formset <TestFormset: bound=True " "valid=False total_forms=1> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormSetError( TestFormset.invalid(nonfield=True), 0, None, "other non-field error" ) self.assertIn( "['non-field error'] != ['other non-field error']", str(ctx.exception) ) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormSetError( TestFormset.invalid(nonfield=True), 0, None, "other non-field error", msg_prefix=msg_prefix, ) def test_no_non_field_errors(self): msg = ( "The non-field errors of form 0 of formset <TestFormset: bound=True " "valid=False total_forms=1> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormSetError(TestFormset.invalid(), 0, None, "non-field error") self.assertIn("[] != ['non-field error']", str(ctx.exception)) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormSetError( TestFormset.invalid(), 0, None, "non-field error", msg_prefix=msg_prefix ) def test_non_form_errors(self): self.assertFormSetError(TestFormset.invalid(nonform=True), None, None, "error") def test_different_non_form_errors(self): msg = ( "The non-form errors of formset <TestFormset: bound=True valid=False " "total_forms=0> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormSetError( TestFormset.invalid(nonform=True), None, None, "other error" ) self.assertIn("['error'] != ['other error']", str(ctx.exception)) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormSetError( TestFormset.invalid(nonform=True), None, None, "other error", msg_prefix=msg_prefix, ) def test_no_non_form_errors(self): msg = ( "The non-form errors of formset <TestFormset: bound=True valid=False " "total_forms=1> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormSetError(TestFormset.invalid(), None, None, "error") self.assertIn("[] != ['error']", str(ctx.exception)) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormSetError( TestFormset.invalid(), None, None, "error", msg_prefix=msg_prefix, ) def test_non_form_errors_with_field(self): msg = "You must use field=None with form_index=None." with self.assertRaisesMessage(ValueError, msg): self.assertFormSetError( TestFormset.invalid(nonform=True), None, "field", "error" ) def test_form_index_too_big(self): msg = ( "The formset <TestFormset: bound=True valid=False total_forms=1> only has " "1 form." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormSetError(TestFormset.invalid(), 2, "field", "error") def test_form_index_too_big_plural(self): formset = TestFormset( { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "0", "form-0-field": "valid", "form-1-field": "valid", } ) formset.full_clean() msg = ( "The formset <TestFormset: bound=True valid=True total_forms=2> only has 2 " "forms." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormSetError(formset, 2, "field", "error") class FirstUrls: urlpatterns = [path("first/", empty_response, name="first")] class SecondUrls: urlpatterns = [path("second/", empty_response, name="second")] class SetupTestEnvironmentTests(SimpleTestCase): def test_setup_test_environment_calling_more_than_once(self): with self.assertRaisesMessage( RuntimeError, "setup_test_environment() was already called" ): setup_test_environment() def test_allowed_hosts(self): for type_ in (list, tuple): with self.subTest(type_=type_): allowed_hosts = type_("*") with mock.patch("django.test.utils._TestState") as x: del x.saved_data with self.settings(ALLOWED_HOSTS=allowed_hosts): setup_test_environment() self.assertEqual(settings.ALLOWED_HOSTS, ["*", "testserver"]) class OverrideSettingsTests(SimpleTestCase): # #21518 -- If neither override_settings nor a setting_changed receiver # clears the URL cache between tests, then one of test_first or # test_second will fail. @override_settings(ROOT_URLCONF=FirstUrls) def test_urlconf_first(self): reverse("first") @override_settings(ROOT_URLCONF=SecondUrls) def test_urlconf_second(self): reverse("second") def test_urlconf_cache(self): with self.assertRaises(NoReverseMatch): reverse("first") with self.assertRaises(NoReverseMatch): reverse("second") with override_settings(ROOT_URLCONF=FirstUrls): self.client.get(reverse("first")) with self.assertRaises(NoReverseMatch): reverse("second") with override_settings(ROOT_URLCONF=SecondUrls): with self.assertRaises(NoReverseMatch): reverse("first") self.client.get(reverse("second")) self.client.get(reverse("first")) with self.assertRaises(NoReverseMatch): reverse("second") with self.assertRaises(NoReverseMatch): reverse("first") with self.assertRaises(NoReverseMatch): reverse("second") def test_override_media_root(self): """ Overriding the MEDIA_ROOT setting should be reflected in the base_location attribute of django.core.files.storage.default_storage. """ self.assertEqual(default_storage.base_location, "") with self.settings(MEDIA_ROOT="test_value"): self.assertEqual(default_storage.base_location, "test_value") def test_override_media_url(self): """ Overriding the MEDIA_URL setting should be reflected in the base_url attribute of django.core.files.storage.default_storage. """ self.assertEqual(default_storage.base_location, "") with self.settings(MEDIA_URL="/test_value/"): self.assertEqual(default_storage.base_url, "/test_value/") def test_override_file_upload_permissions(self): """ Overriding the FILE_UPLOAD_PERMISSIONS setting should be reflected in the file_permissions_mode attribute of django.core.files.storage.default_storage. """ self.assertEqual(default_storage.file_permissions_mode, 0o644) with self.settings(FILE_UPLOAD_PERMISSIONS=0o777): self.assertEqual(default_storage.file_permissions_mode, 0o777) def test_override_file_upload_directory_permissions(self): """ Overriding the FILE_UPLOAD_DIRECTORY_PERMISSIONS setting should be reflected in the directory_permissions_mode attribute of django.core.files.storage.default_storage. """ self.assertIsNone(default_storage.directory_permissions_mode) with self.settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o777): self.assertEqual(default_storage.directory_permissions_mode, 0o777) def test_override_database_routers(self): """ Overriding DATABASE_ROUTERS should update the base router. """ test_routers = [object()] with self.settings(DATABASE_ROUTERS=test_routers): self.assertEqual(router.routers, test_routers) def test_override_static_url(self): """ Overriding the STATIC_URL setting should be reflected in the base_url attribute of django.contrib.staticfiles.storage.staticfiles_storage. """ with self.settings(STATIC_URL="/test/"): self.assertEqual(staticfiles_storage.base_url, "/test/") def test_override_static_root(self): """ Overriding the STATIC_ROOT setting should be reflected in the location attribute of django.contrib.staticfiles.storage.staticfiles_storage. """ with self.settings(STATIC_ROOT="/tmp/test"): self.assertEqual(staticfiles_storage.location, os.path.abspath("/tmp/test")) def test_override_staticfiles_storage(self): """ Overriding the STORAGES setting should be reflected in the value of django.contrib.staticfiles.storage.staticfiles_storage. """ new_class = "ManifestStaticFilesStorage" new_storage = "django.contrib.staticfiles.storage." + new_class with self.settings( STORAGES={STATICFILES_STORAGE_ALIAS: {"BACKEND": new_storage}} ): self.assertEqual(staticfiles_storage.__class__.__name__, new_class) def test_override_staticfiles_finders(self): """ Overriding the STATICFILES_FINDERS setting should be reflected in the return value of django.contrib.staticfiles.finders.get_finders. """ current = get_finders() self.assertGreater(len(list(current)), 1) finders = ["django.contrib.staticfiles.finders.FileSystemFinder"] with self.settings(STATICFILES_FINDERS=finders): self.assertEqual(len(list(get_finders())), len(finders)) def test_override_staticfiles_dirs(self): """ Overriding the STATICFILES_DIRS setting should be reflected in the locations attribute of the django.contrib.staticfiles.finders.FileSystemFinder instance. """ finder = get_finder("django.contrib.staticfiles.finders.FileSystemFinder") test_path = "/tmp/test" expected_location = ("", test_path) self.assertNotIn(expected_location, finder.locations) with self.settings(STATICFILES_DIRS=[test_path]): finder = get_finder("django.contrib.staticfiles.finders.FileSystemFinder") self.assertIn(expected_location, finder.locations) @skipUnlessDBFeature("supports_transactions") class TestBadSetUpTestData(TestCase): """ An exception in setUpTestData() shouldn't leak a transaction which would cascade across the rest of the test suite. """ class MyException(Exception): pass @classmethod def setUpClass(cls): try: super().setUpClass() except cls.MyException: cls._in_atomic_block = connection.in_atomic_block @classmethod def tearDownClass(Cls): # override to avoid a second cls._rollback_atomics() which would fail. # Normal setUpClass() methods won't have exception handling so this # method wouldn't typically be run. pass @classmethod def setUpTestData(cls): # Simulate a broken setUpTestData() method. raise cls.MyException() def test_failure_in_setUpTestData_should_rollback_transaction(self): # setUpTestData() should call _rollback_atomics() so that the # transaction doesn't leak. self.assertFalse(self._in_atomic_block) @skipUnlessDBFeature("supports_transactions") class CaptureOnCommitCallbacksTests(TestCase): databases = {"default", "other"} callback_called = False def enqueue_callback(self, using="default"): def hook(): self.callback_called = True transaction.on_commit(hook, using=using) def test_no_arguments(self): with self.captureOnCommitCallbacks() as callbacks: self.enqueue_callback() self.assertEqual(len(callbacks), 1) self.assertIs(self.callback_called, False) callbacks[0]() self.assertIs(self.callback_called, True) def test_using(self): with self.captureOnCommitCallbacks(using="other") as callbacks: self.enqueue_callback(using="other") self.assertEqual(len(callbacks), 1) self.assertIs(self.callback_called, False) callbacks[0]() self.assertIs(self.callback_called, True) def test_different_using(self): with self.captureOnCommitCallbacks(using="default") as callbacks: self.enqueue_callback(using="other") self.assertEqual(callbacks, []) def test_execute(self): with self.captureOnCommitCallbacks(execute=True) as callbacks: self.enqueue_callback() self.assertEqual(len(callbacks), 1) self.assertIs(self.callback_called, True) def test_pre_callback(self): def pre_hook(): pass transaction.on_commit(pre_hook, using="default") with self.captureOnCommitCallbacks() as callbacks: self.enqueue_callback() self.assertEqual(len(callbacks), 1) self.assertNotEqual(callbacks[0], pre_hook) def test_with_rolled_back_savepoint(self): with self.captureOnCommitCallbacks() as callbacks: try: with transaction.atomic(): self.enqueue_callback() raise IntegrityError except IntegrityError: # Inner transaction.atomic() has been rolled back. pass self.assertEqual(callbacks, []) def test_execute_recursive(self): with self.captureOnCommitCallbacks(execute=True) as callbacks: transaction.on_commit(self.enqueue_callback) self.assertEqual(len(callbacks), 2) self.assertIs(self.callback_called, True) def test_execute_tree(self): """ A visualisation of the callback tree tested. Each node is expected to be visited only once: └─branch_1 ├─branch_2 │ ├─leaf_1 │ └─leaf_2 └─leaf_3 """ branch_1_call_counter = 0 branch_2_call_counter = 0 leaf_1_call_counter = 0 leaf_2_call_counter = 0 leaf_3_call_counter = 0 def leaf_1(): nonlocal leaf_1_call_counter leaf_1_call_counter += 1 def leaf_2(): nonlocal leaf_2_call_counter leaf_2_call_counter += 1 def leaf_3(): nonlocal leaf_3_call_counter leaf_3_call_counter += 1 def branch_1(): nonlocal branch_1_call_counter branch_1_call_counter += 1 transaction.on_commit(branch_2) transaction.on_commit(leaf_3) def branch_2(): nonlocal branch_2_call_counter branch_2_call_counter += 1 transaction.on_commit(leaf_1) transaction.on_commit(leaf_2) with self.captureOnCommitCallbacks(execute=True) as callbacks: transaction.on_commit(branch_1) self.assertEqual(branch_1_call_counter, 1) self.assertEqual(branch_2_call_counter, 1) self.assertEqual(leaf_1_call_counter, 1) self.assertEqual(leaf_2_call_counter, 1) self.assertEqual(leaf_3_call_counter, 1) self.assertEqual(callbacks, [branch_1, branch_2, leaf_3, leaf_1, leaf_2]) def test_execute_robust(self): class MyException(Exception): pass def hook(): self.callback_called = True raise MyException("robust callback") with self.assertLogs("django.test", "ERROR") as cm: with self.captureOnCommitCallbacks(execute=True) as callbacks: transaction.on_commit(hook, robust=True) self.assertEqual(len(callbacks), 1) self.assertIs(self.callback_called, True) log_record = cm.records[0] self.assertEqual( log_record.getMessage(), "Error calling CaptureOnCommitCallbacksTests.test_execute_robust.<locals>." "hook in on_commit() (robust callback).", ) self.assertIsNotNone(log_record.exc_info) raised_exception = log_record.exc_info[1] self.assertIsInstance(raised_exception, MyException) self.assertEqual(str(raised_exception), "robust callback") class DisallowedDatabaseQueriesTests(SimpleTestCase): def test_disallowed_database_connections(self): expected_message = ( "Database connections to 'default' are not allowed in SimpleTestCase " "subclasses. Either subclass TestCase or TransactionTestCase to " "ensure proper test isolation or add 'default' to " "test_utils.tests.DisallowedDatabaseQueriesTests.databases to " "silence this failure." ) with self.assertRaisesMessage(DatabaseOperationForbidden, expected_message): connection.connect() with self.assertRaisesMessage(DatabaseOperationForbidden, expected_message): connection.temporary_connection() def test_disallowed_database_queries(self): expected_message = ( "Database queries to 'default' are not allowed in SimpleTestCase " "subclasses. Either subclass TestCase or TransactionTestCase to " "ensure proper test isolation or add 'default' to " "test_utils.tests.DisallowedDatabaseQueriesTests.databases to " "silence this failure." ) with self.assertRaisesMessage(DatabaseOperationForbidden, expected_message): Car.objects.first() def test_disallowed_database_chunked_cursor_queries(self): expected_message = ( "Database queries to 'default' are not allowed in SimpleTestCase " "subclasses. Either subclass TestCase or TransactionTestCase to " "ensure proper test isolation or add 'default' to " "test_utils.tests.DisallowedDatabaseQueriesTests.databases to " "silence this failure." ) with self.assertRaisesMessage(DatabaseOperationForbidden, expected_message): next(Car.objects.iterator()) class AllowedDatabaseQueriesTests(SimpleTestCase): databases = {"default"} def test_allowed_database_queries(self): Car.objects.first() def test_allowed_database_chunked_cursor_queries(self): next(Car.objects.iterator(), None) class DatabaseAliasTests(SimpleTestCase): def setUp(self): self.addCleanup(setattr, self.__class__, "databases", self.databases) def test_no_close_match(self): self.__class__.databases = {"void"} message = ( "test_utils.tests.DatabaseAliasTests.databases refers to 'void' which is " "not defined in settings.DATABASES." ) with self.assertRaisesMessage(ImproperlyConfigured, message): self._validate_databases() def test_close_match(self): self.__class__.databases = {"defualt"} message = ( "test_utils.tests.DatabaseAliasTests.databases refers to 'defualt' which " "is not defined in settings.DATABASES. Did you mean 'default'?" ) with self.assertRaisesMessage(ImproperlyConfigured, message): self._validate_databases() def test_match(self): self.__class__.databases = {"default", "other"} self.assertEqual(self._validate_databases(), frozenset({"default", "other"})) def test_all(self): self.__class__.databases = "__all__" self.assertEqual(self._validate_databases(), frozenset(connections)) @isolate_apps("test_utils", attr_name="class_apps") class IsolatedAppsTests(SimpleTestCase): def test_installed_apps(self): self.assertEqual( [app_config.label for app_config in self.class_apps.get_app_configs()], ["test_utils"], ) def test_class_decoration(self): class ClassDecoration(models.Model): pass self.assertEqual(ClassDecoration._meta.apps, self.class_apps) @isolate_apps("test_utils", kwarg_name="method_apps") def test_method_decoration(self, method_apps): class MethodDecoration(models.Model): pass self.assertEqual(MethodDecoration._meta.apps, method_apps) def test_context_manager(self): with isolate_apps("test_utils") as context_apps: class ContextManager(models.Model): pass self.assertEqual(ContextManager._meta.apps, context_apps) @isolate_apps("test_utils", kwarg_name="method_apps") def test_nested(self, method_apps): class MethodDecoration(models.Model): pass with isolate_apps("test_utils") as context_apps: class ContextManager(models.Model): pass with isolate_apps("test_utils") as nested_context_apps: class NestedContextManager(models.Model): pass self.assertEqual(MethodDecoration._meta.apps, method_apps) self.assertEqual(ContextManager._meta.apps, context_apps) self.assertEqual(NestedContextManager._meta.apps, nested_context_apps) class DoNothingDecorator(TestContextDecorator): def enable(self): pass def disable(self): pass class TestContextDecoratorTests(SimpleTestCase): @mock.patch.object(DoNothingDecorator, "disable") def test_exception_in_setup(self, mock_disable): """An exception is setUp() is reraised after disable() is called.""" class ExceptionInSetUp(unittest.TestCase): def setUp(self): raise NotImplementedError("reraised") decorator = DoNothingDecorator() decorated_test_class = decorator.__call__(ExceptionInSetUp)() self.assertFalse(mock_disable.called) with self.assertRaisesMessage(NotImplementedError, "reraised"): decorated_test_class.setUp() decorated_test_class.doCleanups() self.assertTrue(mock_disable.called) def test_cleanups_run_after_tearDown(self): calls = [] class SaveCallsDecorator(TestContextDecorator): def enable(self): calls.append("enable") def disable(self): calls.append("disable") class AddCleanupInSetUp(unittest.TestCase): def setUp(self): calls.append("setUp") self.addCleanup(lambda: calls.append("cleanup")) decorator = SaveCallsDecorator() decorated_test_class = decorator.__call__(AddCleanupInSetUp)() decorated_test_class.setUp() decorated_test_class.tearDown() decorated_test_class.doCleanups() self.assertEqual(calls, ["enable", "setUp", "cleanup", "disable"])
74736bac52cae7f1a6e21a73bebfd3e924c170670dbaa1a965705a7af19b7a4a
import datetime import json from contextlib import contextmanager from django.contrib import admin from django.contrib.admin.exceptions import NotRegistered from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.admin.views.autocomplete import AutocompleteJsonView from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.core.exceptions import PermissionDenied from django.http import Http404 from django.test import RequestFactory, override_settings from django.urls import reverse, reverse_lazy from .admin import AnswerAdmin, QuestionAdmin from .models import ( Answer, Author, Authorship, Bonus, Book, Employee, Manager, Parent, PKChild, Question, Toy, WorkHour, ) from .tests import AdminViewBasicTestCase PAGINATOR_SIZE = AutocompleteJsonView.paginate_by class AuthorAdmin(admin.ModelAdmin): ordering = ["id"] search_fields = ["id"] class AuthorshipInline(admin.TabularInline): model = Authorship autocomplete_fields = ["author"] class BookAdmin(admin.ModelAdmin): inlines = [AuthorshipInline] site = admin.AdminSite(name="autocomplete_admin") site.register(Question, QuestionAdmin) site.register(Answer, AnswerAdmin) site.register(Author, AuthorAdmin) site.register(Book, BookAdmin) site.register(Employee, search_fields=["name"]) site.register(WorkHour, autocomplete_fields=["employee"]) site.register(Manager, search_fields=["name"]) site.register(Bonus, autocomplete_fields=["recipient"]) site.register(PKChild, search_fields=["name"]) site.register(Toy, autocomplete_fields=["child"]) @contextmanager def model_admin(model, model_admin, admin_site=site): try: org_admin = admin_site.get_model_admin(model) except NotRegistered: org_admin = None else: admin_site.unregister(model) admin_site.register(model, model_admin) try: yield finally: if org_admin: admin_site._registry[model] = org_admin class AutocompleteJsonViewTests(AdminViewBasicTestCase): as_view_args = {"admin_site": site} opts = { "app_label": Answer._meta.app_label, "model_name": Answer._meta.model_name, "field_name": "question", } factory = RequestFactory() url = reverse_lazy("autocomplete_admin:autocomplete") @classmethod def setUpTestData(cls): cls.user = User.objects.create_user( username="user", password="secret", email="[email protected]", is_staff=True, ) super().setUpTestData() def test_success(self): q = Question.objects.create(question="Is this a question?") request = self.factory.get(self.url, {"term": "is", **self.opts}) request.user = self.superuser response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.content.decode("utf-8")) self.assertEqual( data, { "results": [{"id": str(q.pk), "text": q.question}], "pagination": {"more": False}, }, ) def test_custom_to_field(self): q = Question.objects.create(question="Is this a question?") request = self.factory.get( self.url, {"term": "is", **self.opts, "field_name": "question_with_to_field"}, ) request.user = self.superuser response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.content.decode("utf-8")) self.assertEqual( data, { "results": [{"id": str(q.uuid), "text": q.question}], "pagination": {"more": False}, }, ) def test_custom_to_field_permission_denied(self): Question.objects.create(question="Is this a question?") request = self.factory.get( self.url, {"term": "is", **self.opts, "field_name": "question_with_to_field"}, ) request.user = self.user with self.assertRaises(PermissionDenied): AutocompleteJsonView.as_view(**self.as_view_args)(request) def test_custom_to_field_custom_pk(self): q = Question.objects.create(question="Is this a question?") opts = { "app_label": Question._meta.app_label, "model_name": Question._meta.model_name, "field_name": "related_questions", } request = self.factory.get(self.url, {"term": "is", **opts}) request.user = self.superuser response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.content.decode("utf-8")) self.assertEqual( data, { "results": [{"id": str(q.big_id), "text": q.question}], "pagination": {"more": False}, }, ) def test_to_field_resolution_with_mti(self): """ to_field resolution should correctly resolve for target models using MTI. Tests for single and multi-level cases. """ tests = [ (Employee, WorkHour, "employee"), (Manager, Bonus, "recipient"), ] for Target, Remote, related_name in tests: with self.subTest( target_model=Target, remote_model=Remote, related_name=related_name ): o = Target.objects.create( name="Frida Kahlo", gender=2, code="painter", alive=False ) opts = { "app_label": Remote._meta.app_label, "model_name": Remote._meta.model_name, "field_name": related_name, } request = self.factory.get(self.url, {"term": "frida", **opts}) request.user = self.superuser response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.content.decode("utf-8")) self.assertEqual( data, { "results": [{"id": str(o.pk), "text": o.name}], "pagination": {"more": False}, }, ) def test_to_field_resolution_with_fk_pk(self): p = Parent.objects.create(name="Bertie") c = PKChild.objects.create(parent=p, name="Anna") opts = { "app_label": Toy._meta.app_label, "model_name": Toy._meta.model_name, "field_name": "child", } request = self.factory.get(self.url, {"term": "anna", **opts}) request.user = self.superuser response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.content.decode("utf-8")) self.assertEqual( data, { "results": [{"id": str(c.pk), "text": c.name}], "pagination": {"more": False}, }, ) def test_field_does_not_exist(self): request = self.factory.get( self.url, {"term": "is", **self.opts, "field_name": "does_not_exist"} ) request.user = self.superuser with self.assertRaises(PermissionDenied): AutocompleteJsonView.as_view(**self.as_view_args)(request) def test_field_no_related_field(self): request = self.factory.get( self.url, {"term": "is", **self.opts, "field_name": "answer"} ) request.user = self.superuser with self.assertRaises(PermissionDenied): AutocompleteJsonView.as_view(**self.as_view_args)(request) def test_field_does_not_allowed(self): request = self.factory.get( self.url, {"term": "is", **self.opts, "field_name": "related_questions"} ) request.user = self.superuser with self.assertRaises(PermissionDenied): AutocompleteJsonView.as_view(**self.as_view_args)(request) def test_limit_choices_to(self): # Answer.question_with_to_field defines limit_choices_to to "those not # starting with 'not'". q = Question.objects.create(question="Is this a question?") Question.objects.create(question="Not a question.") request = self.factory.get( self.url, {"term": "is", **self.opts, "field_name": "question_with_to_field"}, ) request.user = self.superuser response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.content.decode("utf-8")) self.assertEqual( data, { "results": [{"id": str(q.uuid), "text": q.question}], "pagination": {"more": False}, }, ) def test_must_be_logged_in(self): response = self.client.get(self.url, {"term": "", **self.opts}) self.assertEqual(response.status_code, 200) self.client.logout() response = self.client.get(self.url, {"term": "", **self.opts}) self.assertEqual(response.status_code, 302) def test_has_view_or_change_permission_required(self): """ Users require the change permission for the related model to the autocomplete view for it. """ request = self.factory.get(self.url, {"term": "is", **self.opts}) request.user = self.user with self.assertRaises(PermissionDenied): AutocompleteJsonView.as_view(**self.as_view_args)(request) for permission in ("view", "change"): with self.subTest(permission=permission): self.user.user_permissions.clear() p = Permission.objects.get( content_type=ContentType.objects.get_for_model(Question), codename="%s_question" % permission, ) self.user.user_permissions.add(p) request.user = User.objects.get(pk=self.user.pk) response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) def test_search_use_distinct(self): """ Searching across model relations use QuerySet.distinct() to avoid duplicates. """ q1 = Question.objects.create(question="question 1") q2 = Question.objects.create(question="question 2") q2.related_questions.add(q1) q3 = Question.objects.create(question="question 3") q3.related_questions.add(q1) request = self.factory.get(self.url, {"term": "question", **self.opts}) request.user = self.superuser class DistinctQuestionAdmin(QuestionAdmin): search_fields = ["related_questions__question", "question"] with model_admin(Question, DistinctQuestionAdmin): response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.content.decode("utf-8")) self.assertEqual(len(data["results"]), 3) def test_missing_search_fields(self): class EmptySearchAdmin(QuestionAdmin): search_fields = [] with model_admin(Question, EmptySearchAdmin): msg = "EmptySearchAdmin must have search_fields for the autocomplete_view." with self.assertRaisesMessage(Http404, msg): site.autocomplete_view( self.factory.get(self.url, {"term": "", **self.opts}) ) def test_get_paginator(self): """Search results are paginated.""" class PKOrderingQuestionAdmin(QuestionAdmin): ordering = ["pk"] Question.objects.bulk_create( Question(question=str(i)) for i in range(PAGINATOR_SIZE + 10) ) # The first page of results. request = self.factory.get(self.url, {"term": "", **self.opts}) request.user = self.superuser with model_admin(Question, PKOrderingQuestionAdmin): response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.content.decode("utf-8")) self.assertEqual( data, { "results": [ {"id": str(q.pk), "text": q.question} for q in Question.objects.all()[:PAGINATOR_SIZE] ], "pagination": {"more": True}, }, ) # The second page of results. request = self.factory.get(self.url, {"term": "", "page": "2", **self.opts}) request.user = self.superuser with model_admin(Question, PKOrderingQuestionAdmin): response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.content.decode("utf-8")) self.assertEqual( data, { "results": [ {"id": str(q.pk), "text": q.question} for q in Question.objects.all()[PAGINATOR_SIZE:] ], "pagination": {"more": False}, }, ) def test_serialize_result(self): class AutocompleteJsonSerializeResultView(AutocompleteJsonView): def serialize_result(self, obj, to_field_name): return { **super().serialize_result(obj, to_field_name), "posted": str(obj.posted), } Question.objects.create(question="Question 1", posted=datetime.date(2021, 8, 9)) Question.objects.create(question="Question 2", posted=datetime.date(2021, 8, 7)) request = self.factory.get(self.url, {"term": "question", **self.opts}) request.user = self.superuser response = AutocompleteJsonSerializeResultView.as_view(**self.as_view_args)( request ) self.assertEqual(response.status_code, 200) data = json.loads(response.content.decode("utf-8")) self.assertEqual( data, { "results": [ {"id": str(q.pk), "text": q.question, "posted": str(q.posted)} for q in Question.objects.order_by("-posted") ], "pagination": {"more": False}, }, ) @override_settings(ROOT_URLCONF="admin_views.urls") class SeleniumTests(AdminSeleniumTestCase): available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]", ) self.admin_login( username="super", password="secret", login_url=reverse("autocomplete_admin:index"), ) @contextmanager def select2_ajax_wait(self, timeout=10): from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ec yield with self.disable_implicit_wait(): try: loading_element = self.selenium.find_element( By.CSS_SELECTOR, "li.select2-results__option.loading-results" ) except NoSuchElementException: pass else: self.wait_until(ec.staleness_of(loading_element), timeout=timeout) def test_select(self): from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select self.selenium.get( self.live_server_url + reverse("autocomplete_admin:admin_views_answer_add") ) elem = self.selenium.find_element(By.CSS_SELECTOR, ".select2-selection") with self.select2_ajax_wait(): elem.click() # Open the autocomplete dropdown. results = self.selenium.find_element(By.CSS_SELECTOR, ".select2-results") self.assertTrue(results.is_displayed()) option = self.selenium.find_element(By.CSS_SELECTOR, ".select2-results__option") self.assertEqual(option.text, "No results found") with self.select2_ajax_wait(): elem.click() # Close the autocomplete dropdown. q1 = Question.objects.create(question="Who am I?") Question.objects.bulk_create( Question(question=str(i)) for i in range(PAGINATOR_SIZE + 10) ) with self.select2_ajax_wait(): elem.click() # Reopen the dropdown now that some objects exist. result_container = self.selenium.find_element( By.CSS_SELECTOR, ".select2-results" ) self.assertTrue(result_container.is_displayed()) # PAGINATOR_SIZE results and "Loading more results". self.assertCountSeleniumElements( ".select2-results__option", PAGINATOR_SIZE + 1, root_element=result_container, ) search = self.selenium.find_element(By.CSS_SELECTOR, ".select2-search__field") # Load next page of results by scrolling to the bottom of the list. with self.select2_ajax_wait(): for _ in range(PAGINATOR_SIZE + 1): search.send_keys(Keys.ARROW_DOWN) # All objects are now loaded. self.assertCountSeleniumElements( ".select2-results__option", PAGINATOR_SIZE + 11, root_element=result_container, ) # Limit the results with the search field. with self.select2_ajax_wait(): search.send_keys("Who") # Ajax request is delayed. self.assertTrue(result_container.is_displayed()) self.assertCountSeleniumElements( ".select2-results__option", PAGINATOR_SIZE + 12, root_element=result_container, ) self.assertTrue(result_container.is_displayed()) self.assertCountSeleniumElements( ".select2-results__option", 1, root_element=result_container ) # Select the result. with self.select2_ajax_wait(): search.send_keys(Keys.RETURN) select = Select(self.selenium.find_element(By.ID, "id_question")) self.assertEqual( select.first_selected_option.get_attribute("value"), str(q1.pk) ) def test_select_multiple(self): from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select self.selenium.get( self.live_server_url + reverse("autocomplete_admin:admin_views_question_add") ) elem = self.selenium.find_element(By.CSS_SELECTOR, ".select2-selection") with self.select2_ajax_wait(): elem.click() # Open the autocomplete dropdown. results = self.selenium.find_element(By.CSS_SELECTOR, ".select2-results") self.assertTrue(results.is_displayed()) option = self.selenium.find_element(By.CSS_SELECTOR, ".select2-results__option") self.assertEqual(option.text, "No results found") with self.select2_ajax_wait(): elem.click() # Close the autocomplete dropdown. Question.objects.create(question="Who am I?") Question.objects.bulk_create( Question(question=str(i)) for i in range(PAGINATOR_SIZE + 10) ) with self.select2_ajax_wait(): elem.click() # Reopen the dropdown now that some objects exist. result_container = self.selenium.find_element( By.CSS_SELECTOR, ".select2-results" ) self.assertTrue(result_container.is_displayed()) self.assertCountSeleniumElements( ".select2-results__option", PAGINATOR_SIZE + 1, root_element=result_container, ) search = self.selenium.find_element(By.CSS_SELECTOR, ".select2-search__field") # Load next page of results by scrolling to the bottom of the list. with self.select2_ajax_wait(): for _ in range(PAGINATOR_SIZE + 1): search.send_keys(Keys.ARROW_DOWN) self.assertCountSeleniumElements( ".select2-results__option", 31, root_element=result_container ) # Limit the results with the search field. with self.select2_ajax_wait(): search.send_keys("Who") # Ajax request is delayed. self.assertTrue(result_container.is_displayed()) self.assertCountSeleniumElements( ".select2-results__option", 32, root_element=result_container ) self.assertTrue(result_container.is_displayed()) self.assertCountSeleniumElements( ".select2-results__option", 1, root_element=result_container ) with self.select2_ajax_wait(): # Select the result. search.send_keys(Keys.RETURN) # Reopen the dropdown and add the first result to the selection. elem.click() search.send_keys(Keys.ARROW_DOWN) search.send_keys(Keys.RETURN) select = Select(self.selenium.find_element(By.ID, "id_related_questions")) self.assertEqual(len(select.all_selected_options), 2) def test_inline_add_another_widgets(self): from selenium.webdriver.common.by import By def assertNoResults(row): elem = row.find_element(By.CSS_SELECTOR, ".select2-selection") elem.click() # Open the autocomplete dropdown. results = self.selenium.find_element(By.CSS_SELECTOR, ".select2-results") self.assertTrue(results.is_displayed()) option = self.selenium.find_element( By.CSS_SELECTOR, ".select2-results__option" ) self.assertEqual(option.text, "No results found") # Autocomplete works in rows present when the page loads. self.selenium.get( self.live_server_url + reverse("autocomplete_admin:admin_views_book_add") ) rows = self.selenium.find_elements(By.CSS_SELECTOR, ".dynamic-authorship_set") self.assertEqual(len(rows), 3) assertNoResults(rows[0]) # Autocomplete works in rows added using the "Add another" button. self.selenium.find_element(By.LINK_TEXT, "Add another Authorship").click() rows = self.selenium.find_elements(By.CSS_SELECTOR, ".dynamic-authorship_set") self.assertEqual(len(rows), 4) assertNoResults(rows[-1])
0099f1b6677f95930ac217313a384bdc754d01a2282bbd15a034c26005286230
import platform import unittest from datetime import datetime, timezone from unittest import mock from django.test import SimpleTestCase from django.utils.datastructures import MultiValueDict from django.utils.http import ( base36_to_int, content_disposition_header, escape_leading_slashes, http_date, int_to_base36, is_same_domain, parse_etags, parse_header_parameters, parse_http_date, quote_etag, url_has_allowed_host_and_scheme, urlencode, urlsafe_base64_decode, urlsafe_base64_encode, ) class URLEncodeTests(SimpleTestCase): cannot_encode_none_msg = ( "Cannot encode None for key 'a' in a query string. Did you mean to " "pass an empty string or omit the value?" ) def test_tuples(self): self.assertEqual(urlencode((("a", 1), ("b", 2), ("c", 3))), "a=1&b=2&c=3") def test_dict(self): result = urlencode({"a": 1, "b": 2, "c": 3}) self.assertEqual(result, "a=1&b=2&c=3") def test_dict_containing_sequence_not_doseq(self): self.assertEqual(urlencode({"a": [1, 2]}, doseq=False), "a=%5B1%2C+2%5D") def test_dict_containing_tuple_not_doseq(self): self.assertEqual(urlencode({"a": (1, 2)}, doseq=False), "a=%281%2C+2%29") def test_custom_iterable_not_doseq(self): class IterableWithStr: def __str__(self): return "custom" def __iter__(self): yield from range(0, 3) self.assertEqual(urlencode({"a": IterableWithStr()}, doseq=False), "a=custom") def test_dict_containing_sequence_doseq(self): self.assertEqual(urlencode({"a": [1, 2]}, doseq=True), "a=1&a=2") def test_dict_containing_empty_sequence_doseq(self): self.assertEqual(urlencode({"a": []}, doseq=True), "") def test_multivaluedict(self): result = urlencode( MultiValueDict( { "name": ["Adrian", "Simon"], "position": ["Developer"], } ), doseq=True, ) self.assertEqual(result, "name=Adrian&name=Simon&position=Developer") def test_dict_with_bytes_values(self): self.assertEqual(urlencode({"a": b"abc"}, doseq=True), "a=abc") def test_dict_with_sequence_of_bytes(self): self.assertEqual( urlencode({"a": [b"spam", b"eggs", b"bacon"]}, doseq=True), "a=spam&a=eggs&a=bacon", ) def test_dict_with_bytearray(self): self.assertEqual(urlencode({"a": bytearray(range(2))}, doseq=True), "a=0&a=1") def test_generator(self): self.assertEqual(urlencode({"a": range(2)}, doseq=True), "a=0&a=1") self.assertEqual(urlencode({"a": range(2)}, doseq=False), "a=range%280%2C+2%29") def test_none(self): with self.assertRaisesMessage(TypeError, self.cannot_encode_none_msg): urlencode({"a": None}) def test_none_in_sequence(self): with self.assertRaisesMessage(TypeError, self.cannot_encode_none_msg): urlencode({"a": [None]}, doseq=True) def test_none_in_generator(self): def gen(): yield None with self.assertRaisesMessage(TypeError, self.cannot_encode_none_msg): urlencode({"a": gen()}, doseq=True) class Base36IntTests(SimpleTestCase): def test_roundtrip(self): for n in [0, 1, 1000, 1000000]: self.assertEqual(n, base36_to_int(int_to_base36(n))) def test_negative_input(self): with self.assertRaisesMessage(ValueError, "Negative base36 conversion input."): int_to_base36(-1) def test_to_base36_errors(self): for n in ["1", "foo", {1: 2}, (1, 2, 3), 3.141]: with self.assertRaises(TypeError): int_to_base36(n) def test_invalid_literal(self): for n in ["#", " "]: with self.assertRaisesMessage( ValueError, "invalid literal for int() with base 36: '%s'" % n ): base36_to_int(n) def test_input_too_large(self): with self.assertRaisesMessage(ValueError, "Base36 input too large"): base36_to_int("1" * 14) def test_to_int_errors(self): for n in [123, {1: 2}, (1, 2, 3), 3.141]: with self.assertRaises(TypeError): base36_to_int(n) def test_values(self): for n, b36 in [(0, "0"), (1, "1"), (42, "16"), (818469960, "django")]: self.assertEqual(int_to_base36(n), b36) self.assertEqual(base36_to_int(b36), n) class URLHasAllowedHostAndSchemeTests(unittest.TestCase): def test_bad_urls(self): bad_urls = ( "http://example.com", "http:///example.com", "https://example.com", "ftp://example.com", r"\\example.com", r"\\\example.com", r"/\\/example.com", r"\\\example.com", r"\\example.com", r"\\//example.com", r"/\/example.com", r"\/example.com", r"/\example.com", "http:///example.com", r"http:/\//example.com", r"http:\/example.com", r"http:/\example.com", 'javascript:alert("XSS")', "\njavascript:alert(x)", "java\nscript:alert(x)", "\x08//example.com", r"http://otherserver\@example.com", r"http:\\testserver\@example.com", r"http://testserver\me:[email protected]", r"http://testserver\@example.com", r"http:\\testserver\confirm\[email protected]", "http:999999999", "ftp:9999999999", "\n", "http://[2001:cdba:0000:0000:0000:0000:3257:9652/", "http://2001:cdba:0000:0000:0000:0000:3257:9652]/", ) for bad_url in bad_urls: with self.subTest(url=bad_url): self.assertIs( url_has_allowed_host_and_scheme( bad_url, allowed_hosts={"testserver", "testserver2"} ), False, ) def test_good_urls(self): good_urls = ( "/view/?param=http://example.com", "/view/?param=https://example.com", "/view?param=ftp://example.com", "view/?param=//example.com", "https://testserver/", "HTTPS://testserver/", "//testserver/", "http://testserver/[email protected]", "/url%20with%20spaces/", "path/http:2222222222", ) for good_url in good_urls: with self.subTest(url=good_url): self.assertIs( url_has_allowed_host_and_scheme( good_url, allowed_hosts={"otherserver", "testserver"} ), True, ) def test_basic_auth(self): # Valid basic auth credentials are allowed. self.assertIs( url_has_allowed_host_and_scheme( r"http://user:pass@testserver/", allowed_hosts={"user:pass@testserver"} ), True, ) def test_no_allowed_hosts(self): # A path without host is allowed. self.assertIs( url_has_allowed_host_and_scheme( "/confirm/[email protected]", allowed_hosts=None ), True, ) # Basic auth without host is not allowed. self.assertIs( url_has_allowed_host_and_scheme( r"http://testserver\@example.com", allowed_hosts=None ), False, ) def test_allowed_hosts_str(self): self.assertIs( url_has_allowed_host_and_scheme( "http://good.com/good", allowed_hosts="good.com" ), True, ) self.assertIs( url_has_allowed_host_and_scheme( "http://good.co/evil", allowed_hosts="good.com" ), False, ) def test_secure_param_https_urls(self): secure_urls = ( "https://example.com/p", "HTTPS://example.com/p", "/view/?param=http://example.com", ) for url in secure_urls: with self.subTest(url=url): self.assertIs( url_has_allowed_host_and_scheme( url, allowed_hosts={"example.com"}, require_https=True ), True, ) def test_secure_param_non_https_urls(self): insecure_urls = ( "http://example.com/p", "ftp://example.com/p", "//example.com/p", ) for url in insecure_urls: with self.subTest(url=url): self.assertIs( url_has_allowed_host_and_scheme( url, allowed_hosts={"example.com"}, require_https=True ), False, ) class URLSafeBase64Tests(unittest.TestCase): def test_roundtrip(self): bytestring = b"foo" encoded = urlsafe_base64_encode(bytestring) decoded = urlsafe_base64_decode(encoded) self.assertEqual(bytestring, decoded) class IsSameDomainTests(unittest.TestCase): def test_good(self): for pair in ( ("example.com", "example.com"), ("example.com", ".example.com"), ("foo.example.com", ".example.com"), ("example.com:8888", "example.com:8888"), ("example.com:8888", ".example.com:8888"), ("foo.example.com:8888", ".example.com:8888"), ): self.assertIs(is_same_domain(*pair), True) def test_bad(self): for pair in ( ("example2.com", "example.com"), ("foo.example.com", "example.com"), ("example.com:9999", "example.com:8888"), ("foo.example.com:8888", ""), ): self.assertIs(is_same_domain(*pair), False) class ETagProcessingTests(unittest.TestCase): def test_parsing(self): self.assertEqual( parse_etags(r'"" , "etag", "e\\tag", W/"weak"'), ['""', '"etag"', r'"e\\tag"', 'W/"weak"'], ) self.assertEqual(parse_etags("*"), ["*"]) # Ignore RFC 2616 ETags that are invalid according to RFC 9110. self.assertEqual(parse_etags(r'"etag", "e\"t\"ag"'), ['"etag"']) def test_quoting(self): self.assertEqual(quote_etag("etag"), '"etag"') # unquoted self.assertEqual(quote_etag('"etag"'), '"etag"') # quoted self.assertEqual(quote_etag('W/"etag"'), 'W/"etag"') # quoted, weak class HttpDateProcessingTests(unittest.TestCase): def test_http_date(self): t = 1167616461.0 self.assertEqual(http_date(t), "Mon, 01 Jan 2007 01:54:21 GMT") def test_parsing_rfc1123(self): parsed = parse_http_date("Sun, 06 Nov 1994 08:49:37 GMT") self.assertEqual( datetime.fromtimestamp(parsed, timezone.utc), datetime(1994, 11, 6, 8, 49, 37, tzinfo=timezone.utc), ) @unittest.skipIf(platform.architecture()[0] == "32bit", "The Year 2038 problem.") @mock.patch("django.utils.http.datetime.datetime") def test_parsing_rfc850(self, mocked_datetime): mocked_datetime.side_effect = datetime mocked_datetime.now = mock.Mock() now_1 = datetime(2019, 11, 6, 8, 49, 37, tzinfo=timezone.utc) now_2 = datetime(2020, 11, 6, 8, 49, 37, tzinfo=timezone.utc) now_3 = datetime(2048, 11, 6, 8, 49, 37, tzinfo=timezone.utc) tests = ( ( now_1, "Tuesday, 31-Dec-69 08:49:37 GMT", datetime(2069, 12, 31, 8, 49, 37, tzinfo=timezone.utc), ), ( now_1, "Tuesday, 10-Nov-70 08:49:37 GMT", datetime(1970, 11, 10, 8, 49, 37, tzinfo=timezone.utc), ), ( now_1, "Sunday, 06-Nov-94 08:49:37 GMT", datetime(1994, 11, 6, 8, 49, 37, tzinfo=timezone.utc), ), ( now_2, "Wednesday, 31-Dec-70 08:49:37 GMT", datetime(2070, 12, 31, 8, 49, 37, tzinfo=timezone.utc), ), ( now_2, "Friday, 31-Dec-71 08:49:37 GMT", datetime(1971, 12, 31, 8, 49, 37, tzinfo=timezone.utc), ), ( now_3, "Sunday, 31-Dec-00 08:49:37 GMT", datetime(2000, 12, 31, 8, 49, 37, tzinfo=timezone.utc), ), ( now_3, "Friday, 31-Dec-99 08:49:37 GMT", datetime(1999, 12, 31, 8, 49, 37, tzinfo=timezone.utc), ), ) for now, rfc850str, expected_date in tests: with self.subTest(rfc850str=rfc850str): mocked_datetime.now.return_value = now parsed = parse_http_date(rfc850str) mocked_datetime.now.assert_called_once_with(tz=timezone.utc) self.assertEqual( datetime.fromtimestamp(parsed, timezone.utc), expected_date, ) mocked_datetime.reset_mock() def test_parsing_asctime(self): parsed = parse_http_date("Sun Nov 6 08:49:37 1994") self.assertEqual( datetime.fromtimestamp(parsed, timezone.utc), datetime(1994, 11, 6, 8, 49, 37, tzinfo=timezone.utc), ) def test_parsing_asctime_nonascii_digits(self): """Non-ASCII unicode decimals raise an error.""" with self.assertRaises(ValueError): parse_http_date("Sun Nov 6 08:49:37 1994") with self.assertRaises(ValueError): parse_http_date("Sun Nov 12 08:49:37 1994") def test_parsing_year_less_than_70(self): parsed = parse_http_date("Sun Nov 6 08:49:37 0037") self.assertEqual( datetime.fromtimestamp(parsed, timezone.utc), datetime(2037, 11, 6, 8, 49, 37, tzinfo=timezone.utc), ) class EscapeLeadingSlashesTests(unittest.TestCase): def test(self): tests = ( ("//example.com", "/%2Fexample.com"), ("//", "/%2F"), ) for url, expected in tests: with self.subTest(url=url): self.assertEqual(escape_leading_slashes(url), expected) class ParseHeaderParameterTests(unittest.TestCase): def test_basic(self): tests = [ ("text/plain", ("text/plain", {})), ("text/vnd.just.made.this.up ; ", ("text/vnd.just.made.this.up", {})), ("text/plain;charset=us-ascii", ("text/plain", {"charset": "us-ascii"})), ( 'text/plain ; charset="us-ascii"', ("text/plain", {"charset": "us-ascii"}), ), ( 'text/plain ; charset="us-ascii"; another=opt', ("text/plain", {"charset": "us-ascii", "another": "opt"}), ), ( 'attachment; filename="silly.txt"', ("attachment", {"filename": "silly.txt"}), ), ( 'attachment; filename="strange;name"', ("attachment", {"filename": "strange;name"}), ), ( 'attachment; filename="strange;name";size=123;', ("attachment", {"filename": "strange;name", "size": "123"}), ), ( 'form-data; name="files"; filename="fo\\"o;bar"', ("form-data", {"name": "files", "filename": 'fo"o;bar'}), ), ] for header, expected in tests: with self.subTest(header=header): self.assertEqual(parse_header_parameters(header), expected) def test_rfc2231_parsing(self): test_data = ( ( "Content-Type: application/x-stuff; " "title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A", "This is ***fun***", ), ( "Content-Type: application/x-stuff; title*=UTF-8''foo-%c3%a4.html", "foo-ä.html", ), ( "Content-Type: application/x-stuff; title*=iso-8859-1''foo-%E4.html", "foo-ä.html", ), ) for raw_line, expected_title in test_data: parsed = parse_header_parameters(raw_line) self.assertEqual(parsed[1]["title"], expected_title) def test_rfc2231_wrong_title(self): """ Test wrongly formatted RFC 2231 headers (missing double single quotes). Parsing should not crash (#24209). """ test_data = ( ( "Content-Type: application/x-stuff; " "title*='This%20is%20%2A%2A%2Afun%2A%2A%2A", "'This%20is%20%2A%2A%2Afun%2A%2A%2A", ), ("Content-Type: application/x-stuff; title*='foo.html", "'foo.html"), ("Content-Type: application/x-stuff; title*=bar.html", "bar.html"), ) for raw_line, expected_title in test_data: parsed = parse_header_parameters(raw_line) self.assertEqual(parsed[1]["title"], expected_title) class ContentDispositionHeaderTests(unittest.TestCase): def test_basic(self): tests = ( ((False, None), None), ((False, "example"), 'inline; filename="example"'), ((True, None), "attachment"), ((True, "example"), 'attachment; filename="example"'), ( (True, '"example" file\\name'), 'attachment; filename="\\"example\\" file\\\\name"', ), ((True, "espécimen"), "attachment; filename*=utf-8''esp%C3%A9cimen"), ( (True, '"espécimen" filename'), "attachment; filename*=utf-8''%22esp%C3%A9cimen%22%20filename", ), ) for (is_attachment, filename), expected in tests: with self.subTest(is_attachment=is_attachment, filename=filename): self.assertEqual( content_disposition_header(is_attachment, filename), expected )
6ea680bc568f77b97404d7fe944c202b5c6f9a92f8ddfc9bdd6dec920685bc5d
from django.forms.models import inlineformset_factory from django.test import TestCase from .models import ( AutoPKChildOfUUIDPKParent, AutoPKParent, ChildRelatedViaAK, ChildWithEditablePK, ParentWithUUIDAlternateKey, UUIDPKChild, UUIDPKChildOfAutoPKParent, UUIDPKParent, ) class InlineFormsetTests(TestCase): def test_inlineformset_factory_nulls_default_pks(self): """ #24377 - If we're adding a new object, a parent's auto-generated pk from the model field default should be ignored as it's regenerated on the save request. Tests the case where both the parent and child have a UUID primary key. """ FormSet = inlineformset_factory(UUIDPKParent, UUIDPKChild, fields="__all__") formset = FormSet() self.assertIsNone(formset.forms[0].fields["parent"].initial) def test_inlineformset_factory_ignores_default_pks_on_submit(self): """ #24377 - Inlines with a model field default should ignore that default value to avoid triggering validation on empty forms. """ FormSet = inlineformset_factory(UUIDPKParent, UUIDPKChild, fields="__all__") formset = FormSet( { "uuidpkchild_set-TOTAL_FORMS": 3, "uuidpkchild_set-INITIAL_FORMS": 0, "uuidpkchild_set-MAX_NUM_FORMS": "", "uuidpkchild_set-0-name": "Foo", "uuidpkchild_set-1-name": "", "uuidpkchild_set-2-name": "", } ) self.assertTrue(formset.is_valid()) self.assertIsNone(formset.instance.uuid) self.assertIsNone(formset.forms[0].instance.parent_id) def test_inlineformset_factory_nulls_default_pks_uuid_parent_auto_child(self): """ #24958 - Variant of test_inlineformset_factory_nulls_default_pks for the case of a parent object with a UUID primary key and a child object with an AutoField primary key. """ FormSet = inlineformset_factory( UUIDPKParent, AutoPKChildOfUUIDPKParent, fields="__all__" ) formset = FormSet() self.assertIsNone(formset.forms[0].fields["parent"].initial) def test_inlineformset_factory_nulls_default_pks_auto_parent_uuid_child(self): """ #24958 - Variant of test_inlineformset_factory_nulls_default_pks for the case of a parent object with an AutoField primary key and a child object with a UUID primary key. """ FormSet = inlineformset_factory( AutoPKParent, UUIDPKChildOfAutoPKParent, fields="__all__" ) formset = FormSet() self.assertIsNone(formset.forms[0].fields["parent"].initial) def test_inlineformset_factory_nulls_default_pks_child_editable_pk(self): """ #24958 - Variant of test_inlineformset_factory_nulls_default_pks for the case of a parent object with a UUID primary key and a child object with an editable natural key for a primary key. """ FormSet = inlineformset_factory( UUIDPKParent, ChildWithEditablePK, fields="__all__" ) formset = FormSet() self.assertIsNone(formset.forms[0].fields["parent"].initial) def test_inlineformset_factory_nulls_default_pks_alternate_key_relation(self): """ #24958 - Variant of test_inlineformset_factory_nulls_default_pks for the case of a parent object with a UUID alternate key and a child object that relates to that alternate key. """ FormSet = inlineformset_factory( ParentWithUUIDAlternateKey, ChildRelatedViaAK, fields="__all__" ) formset = FormSet() self.assertIsNone(formset.forms[0].fields["parent"].initial) def test_inlineformset_factory_nulls_default_pks_alternate_key_relation_data(self): """ If form data is provided, a parent's auto-generated alternate key is set. """ FormSet = inlineformset_factory( ParentWithUUIDAlternateKey, ChildRelatedViaAK, fields="__all__" ) formset = FormSet( { "childrelatedviaak_set-TOTAL_FORMS": 3, "childrelatedviaak_set-INITIAL_FORMS": 0, "childrelatedviaak_set-MAX_NUM_FORMS": "", "childrelatedviaak_set-0-name": "Test", "childrelatedviaak_set-1-name": "", "childrelatedviaak_set-2-name": "", } ) self.assertIs(formset.is_valid(), True) self.assertIsNotNone(formset.instance.uuid) self.assertEqual(formset.forms[0].instance.parent_id, formset.instance.uuid)
be143ff8f752f9c5c1c206400249a026ebfe586bd4791f49f80d7763b29706e7
from django.conf import settings from django.core.checks.messages import Error, Warning from django.core.checks.security import base, csrf, sessions from django.core.management.utils import get_random_secret_key from django.test import SimpleTestCase from django.test.utils import override_settings from django.views.generic import View class CheckSessionCookieSecureTest(SimpleTestCase): @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_secure_with_installed_app(self): """ Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions" is in INSTALLED_APPS. """ self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W010]) @override_settings( SESSION_COOKIE_SECURE="1", INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_secure_with_installed_app_truthy(self): """SESSION_COOKIE_SECURE must be boolean.""" self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W010]) @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=[], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_secure_with_middleware(self): """ Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions.middleware.SessionMiddleware" is in MIDDLEWARE. """ self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W011]) @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_secure_both(self): """ If SESSION_COOKIE_SECURE is off and we find both the session app and the middleware, provide one common warning. """ self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W012]) @override_settings( SESSION_COOKIE_SECURE=True, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_secure_true(self): """ If SESSION_COOKIE_SECURE is on, there's no warning about it. """ self.assertEqual(sessions.check_session_cookie_secure(None), []) class CheckSessionCookieHttpOnlyTest(SimpleTestCase): @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_httponly_with_installed_app(self): """ Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions" is in INSTALLED_APPS. """ self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W013]) @override_settings( SESSION_COOKIE_HTTPONLY="1", INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_httponly_with_installed_app_truthy(self): """SESSION_COOKIE_HTTPONLY must be boolean.""" self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W013]) @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=[], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_httponly_with_middleware(self): """ Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions.middleware.SessionMiddleware" is in MIDDLEWARE. """ self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W014]) @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_httponly_both(self): """ If SESSION_COOKIE_HTTPONLY is off and we find both the session app and the middleware, provide one common warning. """ self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W015]) @override_settings( SESSION_COOKIE_HTTPONLY=True, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_httponly_true(self): """ If SESSION_COOKIE_HTTPONLY is on, there's no warning about it. """ self.assertEqual(sessions.check_session_cookie_httponly(None), []) class CheckCSRFMiddlewareTest(SimpleTestCase): @override_settings(MIDDLEWARE=[]) def test_no_csrf_middleware(self): """ Warn if CsrfViewMiddleware isn't in MIDDLEWARE. """ self.assertEqual(csrf.check_csrf_middleware(None), [csrf.W003]) @override_settings(MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"]) def test_with_csrf_middleware(self): self.assertEqual(csrf.check_csrf_middleware(None), []) class CheckCSRFCookieSecureTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_COOKIE_SECURE=False, ) def test_with_csrf_cookie_secure_false(self): """ Warn if CsrfViewMiddleware is in MIDDLEWARE but CSRF_COOKIE_SECURE isn't True. """ self.assertEqual(csrf.check_csrf_cookie_secure(None), [csrf.W016]) @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_COOKIE_SECURE="1", ) def test_with_csrf_cookie_secure_truthy(self): """CSRF_COOKIE_SECURE must be boolean.""" self.assertEqual(csrf.check_csrf_cookie_secure(None), [csrf.W016]) @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_USE_SESSIONS=True, CSRF_COOKIE_SECURE=False, ) def test_use_sessions_with_csrf_cookie_secure_false(self): """ No warning if CSRF_COOKIE_SECURE isn't True while CSRF_USE_SESSIONS is True. """ self.assertEqual(csrf.check_csrf_cookie_secure(None), []) @override_settings(MIDDLEWARE=[], CSRF_COOKIE_SECURE=False) def test_with_csrf_cookie_secure_false_no_middleware(self): """ No warning if CsrfViewMiddleware isn't in MIDDLEWARE, even if CSRF_COOKIE_SECURE is False. """ self.assertEqual(csrf.check_csrf_cookie_secure(None), []) @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_COOKIE_SECURE=True, ) def test_with_csrf_cookie_secure_true(self): self.assertEqual(csrf.check_csrf_cookie_secure(None), []) class CheckSecurityMiddlewareTest(SimpleTestCase): @override_settings(MIDDLEWARE=[]) def test_no_security_middleware(self): """ Warn if SecurityMiddleware isn't in MIDDLEWARE. """ self.assertEqual(base.check_security_middleware(None), [base.W001]) @override_settings(MIDDLEWARE=["django.middleware.security.SecurityMiddleware"]) def test_with_security_middleware(self): self.assertEqual(base.check_security_middleware(None), []) class CheckStrictTransportSecurityTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_SECONDS=0, ) def test_no_sts(self): """ Warn if SECURE_HSTS_SECONDS isn't > 0. """ self.assertEqual(base.check_sts(None), [base.W004]) @override_settings(MIDDLEWARE=[], SECURE_HSTS_SECONDS=0) def test_no_sts_no_middleware(self): """ Don't warn if SECURE_HSTS_SECONDS isn't > 0 and SecurityMiddleware isn't installed. """ self.assertEqual(base.check_sts(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_SECONDS=3600, ) def test_with_sts(self): self.assertEqual(base.check_sts(None), []) class CheckStrictTransportSecuritySubdomainsTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_INCLUDE_SUBDOMAINS=False, SECURE_HSTS_SECONDS=3600, ) def test_no_sts_subdomains(self): """ Warn if SECURE_HSTS_INCLUDE_SUBDOMAINS isn't True. """ self.assertEqual(base.check_sts_include_subdomains(None), [base.W005]) @override_settings( MIDDLEWARE=[], SECURE_HSTS_INCLUDE_SUBDOMAINS=False, SECURE_HSTS_SECONDS=3600, ) def test_no_sts_subdomains_no_middleware(self): """ Don't warn if SecurityMiddleware isn't installed. """ self.assertEqual(base.check_sts_include_subdomains(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=False, SECURE_HSTS_SECONDS=None, ) def test_no_sts_subdomains_no_seconds(self): """ Don't warn if SECURE_HSTS_SECONDS isn't set. """ self.assertEqual(base.check_sts_include_subdomains(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_INCLUDE_SUBDOMAINS=True, SECURE_HSTS_SECONDS=3600, ) def test_with_sts_subdomains(self): self.assertEqual(base.check_sts_include_subdomains(None), []) class CheckStrictTransportSecurityPreloadTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_PRELOAD=False, SECURE_HSTS_SECONDS=3600, ) def test_no_sts_preload(self): """ Warn if SECURE_HSTS_PRELOAD isn't True. """ self.assertEqual(base.check_sts_preload(None), [base.W021]) @override_settings( MIDDLEWARE=[], SECURE_HSTS_PRELOAD=False, SECURE_HSTS_SECONDS=3600 ) def test_no_sts_preload_no_middleware(self): """ Don't warn if SecurityMiddleware isn't installed. """ self.assertEqual(base.check_sts_preload(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=False, SECURE_HSTS_SECONDS=None, ) def test_no_sts_preload_no_seconds(self): """ Don't warn if SECURE_HSTS_SECONDS isn't set. """ self.assertEqual(base.check_sts_preload(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_PRELOAD=True, SECURE_HSTS_SECONDS=3600, ) def test_with_sts_preload(self): self.assertEqual(base.check_sts_preload(None), []) class CheckXFrameOptionsMiddlewareTest(SimpleTestCase): @override_settings(MIDDLEWARE=[]) def test_middleware_not_installed(self): """ Warn if XFrameOptionsMiddleware isn't in MIDDLEWARE. """ self.assertEqual(base.check_xframe_options_middleware(None), [base.W002]) @override_settings( MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"] ) def test_middleware_installed(self): self.assertEqual(base.check_xframe_options_middleware(None), []) class CheckXFrameOptionsDenyTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"], X_FRAME_OPTIONS="SAMEORIGIN", ) def test_x_frame_options_not_deny(self): """ Warn if XFrameOptionsMiddleware is in MIDDLEWARE but X_FRAME_OPTIONS isn't 'DENY'. """ self.assertEqual(base.check_xframe_deny(None), [base.W019]) @override_settings(MIDDLEWARE=[], X_FRAME_OPTIONS="SAMEORIGIN") def test_middleware_not_installed(self): """ No error if XFrameOptionsMiddleware isn't in MIDDLEWARE even if X_FRAME_OPTIONS isn't 'DENY'. """ self.assertEqual(base.check_xframe_deny(None), []) @override_settings( MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"], X_FRAME_OPTIONS="DENY", ) def test_xframe_deny(self): self.assertEqual(base.check_xframe_deny(None), []) class CheckContentTypeNosniffTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_CONTENT_TYPE_NOSNIFF=False, ) def test_no_content_type_nosniff(self): """ Warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True. """ self.assertEqual(base.check_content_type_nosniff(None), [base.W006]) @override_settings(MIDDLEWARE=[], SECURE_CONTENT_TYPE_NOSNIFF=False) def test_no_content_type_nosniff_no_middleware(self): """ Don't warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True and SecurityMiddleware isn't in MIDDLEWARE. """ self.assertEqual(base.check_content_type_nosniff(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_CONTENT_TYPE_NOSNIFF=True, ) def test_with_content_type_nosniff(self): self.assertEqual(base.check_content_type_nosniff(None), []) class CheckSSLRedirectTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=False, ) def test_no_ssl_redirect(self): """ Warn if SECURE_SSL_REDIRECT isn't True. """ self.assertEqual(base.check_ssl_redirect(None), [base.W008]) @override_settings(MIDDLEWARE=[], SECURE_SSL_REDIRECT=False) def test_no_ssl_redirect_no_middleware(self): """ Don't warn if SECURE_SSL_REDIRECT is False and SecurityMiddleware isn't installed. """ self.assertEqual(base.check_ssl_redirect(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=True, ) def test_with_ssl_redirect(self): self.assertEqual(base.check_ssl_redirect(None), []) class CheckSecretKeyTest(SimpleTestCase): @override_settings(SECRET_KEY=("abcdefghijklmnopqrstuvwx" * 2) + "ab") def test_okay_secret_key(self): self.assertEqual(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH) self.assertGreater( len(set(settings.SECRET_KEY)), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS ) self.assertEqual(base.check_secret_key(None), []) @override_settings(SECRET_KEY="") def test_empty_secret_key(self): self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings(SECRET_KEY=None) def test_missing_secret_key(self): del settings.SECRET_KEY self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings(SECRET_KEY=None) def test_none_secret_key(self): self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings( SECRET_KEY=base.SECRET_KEY_INSECURE_PREFIX + get_random_secret_key() ) def test_insecure_secret_key(self): self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings(SECRET_KEY=("abcdefghijklmnopqrstuvwx" * 2) + "a") def test_low_length_secret_key(self): self.assertEqual(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH - 1) self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings(SECRET_KEY="abcd" * 20) def test_low_entropy_secret_key(self): self.assertGreater(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH) self.assertLess( len(set(settings.SECRET_KEY)), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS ) self.assertEqual(base.check_secret_key(None), [base.W009]) class CheckSecretKeyFallbacksTest(SimpleTestCase): @override_settings(SECRET_KEY_FALLBACKS=[("abcdefghijklmnopqrstuvwx" * 2) + "ab"]) def test_okay_secret_key_fallbacks(self): self.assertEqual( len(settings.SECRET_KEY_FALLBACKS[0]), base.SECRET_KEY_MIN_LENGTH, ) self.assertGreater( len(set(settings.SECRET_KEY_FALLBACKS[0])), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS, ) self.assertEqual(base.check_secret_key_fallbacks(None), []) def test_no_secret_key_fallbacks(self): with self.settings(SECRET_KEY_FALLBACKS=None): del settings.SECRET_KEY_FALLBACKS self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS", id=base.W025.id), ], ) @override_settings( SECRET_KEY_FALLBACKS=[base.SECRET_KEY_INSECURE_PREFIX + get_random_secret_key()] ) def test_insecure_secret_key_fallbacks(self): self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[0]", id=base.W025.id), ], ) @override_settings(SECRET_KEY_FALLBACKS=[("abcdefghijklmnopqrstuvwx" * 2) + "a"]) def test_low_length_secret_key_fallbacks(self): self.assertEqual( len(settings.SECRET_KEY_FALLBACKS[0]), base.SECRET_KEY_MIN_LENGTH - 1, ) self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[0]", id=base.W025.id), ], ) @override_settings(SECRET_KEY_FALLBACKS=["abcd" * 20]) def test_low_entropy_secret_key_fallbacks(self): self.assertGreater( len(settings.SECRET_KEY_FALLBACKS[0]), base.SECRET_KEY_MIN_LENGTH, ) self.assertLess( len(set(settings.SECRET_KEY_FALLBACKS[0])), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS, ) self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[0]", id=base.W025.id), ], ) @override_settings( SECRET_KEY_FALLBACKS=[ ("abcdefghijklmnopqrstuvwx" * 2) + "ab", "badkey", ] ) def test_multiple_keys(self): self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[1]", id=base.W025.id), ], ) @override_settings( SECRET_KEY_FALLBACKS=[ ("abcdefghijklmnopqrstuvwx" * 2) + "ab", "badkey1", "badkey2", ] ) def test_multiple_bad_keys(self): self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[1]", id=base.W025.id), Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[2]", id=base.W025.id), ], ) class CheckDebugTest(SimpleTestCase): @override_settings(DEBUG=True) def test_debug_true(self): """ Warn if DEBUG is True. """ self.assertEqual(base.check_debug(None), [base.W018]) @override_settings(DEBUG=False) def test_debug_false(self): self.assertEqual(base.check_debug(None), []) class CheckAllowedHostsTest(SimpleTestCase): @override_settings(ALLOWED_HOSTS=[]) def test_allowed_hosts_empty(self): self.assertEqual(base.check_allowed_hosts(None), [base.W020]) @override_settings(ALLOWED_HOSTS=[".example.com"]) def test_allowed_hosts_set(self): self.assertEqual(base.check_allowed_hosts(None), []) class CheckReferrerPolicyTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_REFERRER_POLICY=None, ) def test_no_referrer_policy(self): self.assertEqual(base.check_referrer_policy(None), [base.W022]) @override_settings(MIDDLEWARE=[], SECURE_REFERRER_POLICY=None) def test_no_referrer_policy_no_middleware(self): """ Don't warn if SECURE_REFERRER_POLICY is None and SecurityMiddleware isn't in MIDDLEWARE. """ self.assertEqual(base.check_referrer_policy(None), []) @override_settings(MIDDLEWARE=["django.middleware.security.SecurityMiddleware"]) def test_with_referrer_policy(self): tests = ( "strict-origin", "strict-origin,origin", "strict-origin, origin", ["strict-origin", "origin"], ("strict-origin", "origin"), ) for value in tests: with self.subTest(value=value), override_settings( SECURE_REFERRER_POLICY=value ): self.assertEqual(base.check_referrer_policy(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_REFERRER_POLICY="invalid-value", ) def test_with_invalid_referrer_policy(self): self.assertEqual(base.check_referrer_policy(None), [base.E023]) def failure_view_with_invalid_signature(): pass good_class_based_csrf_failure_view = View.as_view() class CSRFFailureViewTest(SimpleTestCase): @override_settings(CSRF_FAILURE_VIEW="") def test_failure_view_import_error(self): self.assertEqual( csrf.check_csrf_failure_view(None), [ Error( "The CSRF failure view '' could not be imported.", id="security.E102", ) ], ) @override_settings( CSRF_FAILURE_VIEW=( "check_framework.test_security.failure_view_with_invalid_signature" ), ) def test_failure_view_invalid_signature(self): msg = ( "The CSRF failure view " "'check_framework.test_security.failure_view_with_invalid_signature' " "does not take the correct number of arguments." ) self.assertEqual( csrf.check_csrf_failure_view(None), [Error(msg, id="security.E101")], ) @override_settings( CSRF_FAILURE_VIEW=( "check_framework.test_security.good_class_based_csrf_failure_view" ), ) def test_failure_view_valid_class_based(self): self.assertEqual(csrf.check_csrf_failure_view(None), []) class CheckCrossOriginOpenerPolicyTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_CROSS_ORIGIN_OPENER_POLICY=None, ) def test_no_coop(self): self.assertEqual(base.check_cross_origin_opener_policy(None), []) @override_settings(MIDDLEWARE=["django.middleware.security.SecurityMiddleware"]) def test_with_coop(self): tests = ["same-origin", "same-origin-allow-popups", "unsafe-none"] for value in tests: with self.subTest(value=value), override_settings( SECURE_CROSS_ORIGIN_OPENER_POLICY=value, ): self.assertEqual(base.check_cross_origin_opener_policy(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_CROSS_ORIGIN_OPENER_POLICY="invalid-value", ) def test_with_invalid_coop(self): self.assertEqual(base.check_cross_origin_opener_policy(None), [base.E024])
1dd2c35716a36e841837fd7117c96cef28ded327cb68b77c27a7b93dccb81299
from django.conf import settings from django.core.checks.messages import Error, Warning from django.core.checks.urls import ( E006, check_url_config, check_url_namespaces_unique, check_url_settings, get_warning_for_invalid_pattern, ) from django.test import SimpleTestCase from django.test.utils import override_settings class CheckUrlConfigTests(SimpleTestCase): @override_settings(ROOT_URLCONF="check_framework.urls.no_warnings") def test_no_warnings(self): result = check_url_config(None) self.assertEqual(result, []) @override_settings(ROOT_URLCONF="check_framework.urls.no_warnings_i18n") def test_no_warnings_i18n(self): self.assertEqual(check_url_config(None), []) @override_settings(ROOT_URLCONF="check_framework.urls.warning_in_include") def test_check_resolver_recursive(self): # The resolver is checked recursively (examining URL patterns in include()). result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "urls.W001") @override_settings(ROOT_URLCONF="check_framework.urls.include_with_dollar") def test_include_with_dollar(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "urls.W001") self.assertEqual( warning.msg, ( "Your URL pattern '^include-with-dollar$' uses include with a " "route ending with a '$'. Remove the dollar from the route to " "avoid problems including URLs." ), ) @override_settings(ROOT_URLCONF="check_framework.urls.contains_tuple") def test_contains_tuple_not_url_instance(self): result = check_url_config(None) warning = result[0] self.assertEqual(warning.id, "urls.E004") self.assertRegex( warning.msg, ( r"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) " r"is invalid. Ensure that urlpatterns is a list of path\(\) and/or " r"re_path\(\) instances\.$" ), ) @override_settings(ROOT_URLCONF="check_framework.urls.include_contains_tuple") def test_contains_included_tuple(self): result = check_url_config(None) warning = result[0] self.assertEqual(warning.id, "urls.E004") self.assertRegex( warning.msg, ( r"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) " r"is invalid. Ensure that urlpatterns is a list of path\(\) and/or " r"re_path\(\) instances\.$" ), ) @override_settings(ROOT_URLCONF="check_framework.urls.beginning_with_slash") def test_beginning_with_slash(self): msg = ( "Your URL pattern '%s' has a route beginning with a '/'. Remove " "this slash as it is unnecessary. If this pattern is targeted in " "an include(), ensure the include() pattern has a trailing '/'." ) warning1, warning2 = check_url_config(None) self.assertEqual(warning1.id, "urls.W002") self.assertEqual(warning1.msg, msg % "/path-starting-with-slash/") self.assertEqual(warning2.id, "urls.W002") self.assertEqual(warning2.msg, msg % "/url-starting-with-slash/$") @override_settings( ROOT_URLCONF="check_framework.urls.beginning_with_slash", APPEND_SLASH=False, ) def test_beginning_with_slash_append_slash(self): # It can be useful to start a URL pattern with a slash when # APPEND_SLASH=False (#27238). result = check_url_config(None) self.assertEqual(result, []) @override_settings(ROOT_URLCONF="check_framework.urls.name_with_colon") def test_name_with_colon(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "urls.W003") expected_msg = ( "Your URL pattern '^$' [name='name_with:colon'] has a name including a ':'." ) self.assertIn(expected_msg, warning.msg) @override_settings(ROOT_URLCONF=None) def test_no_root_urlconf_in_settings(self): delattr(settings, "ROOT_URLCONF") result = check_url_config(None) self.assertEqual(result, []) def test_get_warning_for_invalid_pattern_string(self): warning = get_warning_for_invalid_pattern("")[0] self.assertEqual( warning.hint, "Try removing the string ''. The list of urlpatterns should " "not have a prefix string as the first element.", ) def test_get_warning_for_invalid_pattern_tuple(self): warning = get_warning_for_invalid_pattern((r"^$", lambda x: x))[0] self.assertEqual(warning.hint, "Try using path() instead of a tuple.") def test_get_warning_for_invalid_pattern_other(self): warning = get_warning_for_invalid_pattern(object())[0] self.assertIsNone(warning.hint) @override_settings(ROOT_URLCONF="check_framework.urls.non_unique_namespaces") def test_check_non_unique_namespaces(self): result = check_url_namespaces_unique(None) self.assertEqual(len(result), 2) non_unique_namespaces = ["app-ns1", "app-1"] warning_messages = [ "URL namespace '{}' isn't unique. You may not be able to reverse " "all URLs in this namespace".format(namespace) for namespace in non_unique_namespaces ] for warning in result: self.assertIsInstance(warning, Warning) self.assertEqual("urls.W005", warning.id) self.assertIn(warning.msg, warning_messages) @override_settings(ROOT_URLCONF="check_framework.urls.unique_namespaces") def test_check_unique_namespaces(self): result = check_url_namespaces_unique(None) self.assertEqual(result, []) @override_settings(ROOT_URLCONF="check_framework.urls.cbv_as_view") def test_check_view_not_class(self): self.assertEqual( check_url_config(None), [ Error( "Your URL pattern 'missing_as_view' has an invalid view, pass " "EmptyCBV.as_view() instead of EmptyCBV.", id="urls.E009", ), ], ) @override_settings( ROOT_URLCONF="check_framework.urls.path_compatibility.matched_angle_brackets" ) def test_no_warnings_matched_angle_brackets(self): self.assertEqual(check_url_config(None), []) @override_settings( ROOT_URLCONF="check_framework.urls.path_compatibility.unmatched_angle_brackets" ) def test_warning_unmatched_angle_brackets(self): self.assertEqual( check_url_config(None), [ Warning( "Your URL pattern 'beginning-with/<angle_bracket' has an unmatched " "'<' bracket.", id="urls.W010", ), Warning( "Your URL pattern 'ending-with/angle_bracket>' has an unmatched " "'>' bracket.", id="urls.W010", ), Warning( "Your URL pattern 'closed_angle>/x/<opened_angle' has an unmatched " "'>' bracket.", id="urls.W010", ), Warning( "Your URL pattern 'closed_angle>/x/<opened_angle' has an unmatched " "'<' bracket.", id="urls.W010", ), Warning( "Your URL pattern '<mixed>angle_bracket>' has an unmatched '>' " "bracket.", id="urls.W010", ), ], ) class UpdatedToPathTests(SimpleTestCase): @override_settings( ROOT_URLCONF="check_framework.urls.path_compatibility.contains_re_named_group" ) def test_contains_re_named_group(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "2_0.W001") expected_msg = "Your URL pattern '(?P<named_group>\\d+)' has a route" self.assertIn(expected_msg, warning.msg) @override_settings( ROOT_URLCONF="check_framework.urls.path_compatibility.beginning_with_caret" ) def test_beginning_with_caret(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "2_0.W001") expected_msg = "Your URL pattern '^beginning-with-caret' has a route" self.assertIn(expected_msg, warning.msg) @override_settings( ROOT_URLCONF="check_framework.urls.path_compatibility.ending_with_dollar" ) def test_ending_with_dollar(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "2_0.W001") expected_msg = "Your URL pattern 'ending-with-dollar$' has a route" self.assertIn(expected_msg, warning.msg) class CheckCustomErrorHandlersTests(SimpleTestCase): @override_settings( ROOT_URLCONF="check_framework.urls.bad_function_based_error_handlers", ) def test_bad_function_based_handlers(self): result = check_url_config(None) self.assertEqual(len(result), 4) for code, num_params, error in zip([400, 403, 404, 500], [2, 2, 2, 1], result): with self.subTest("handler{}".format(code)): self.assertEqual( error, Error( "The custom handler{} view 'check_framework.urls." "bad_function_based_error_handlers.bad_handler' " "does not take the correct number of arguments " "(request{}).".format( code, ", exception" if num_params == 2 else "" ), id="urls.E007", ), ) @override_settings( ROOT_URLCONF="check_framework.urls.bad_class_based_error_handlers", ) def test_bad_class_based_handlers(self): result = check_url_config(None) self.assertEqual(len(result), 4) for code, num_params, error in zip([400, 403, 404, 500], [2, 2, 2, 1], result): with self.subTest("handler%s" % code): self.assertEqual( error, Error( "The custom handler%s view 'check_framework.urls." "bad_class_based_error_handlers.HandlerView.as_view." "<locals>.view' does not take the correct number of " "arguments (request%s)." % ( code, ", exception" if num_params == 2 else "", ), id="urls.E007", ), ) @override_settings( ROOT_URLCONF="check_framework.urls.bad_error_handlers_invalid_path" ) def test_bad_handlers_invalid_path(self): result = check_url_config(None) paths = [ "django.views.bad_handler", "django.invalid_module.bad_handler", "invalid_module.bad_handler", "django", ] hints = [ "Could not import '{}'. View does not exist in module django.views.", "Could not import '{}'. Parent module django.invalid_module does not " "exist.", "No module named 'invalid_module'", "Could not import '{}'. The path must be fully qualified.", ] for code, path, hint, error in zip([400, 403, 404, 500], paths, hints, result): with self.subTest("handler{}".format(code)): self.assertEqual( error, Error( "The custom handler{} view '{}' could not be imported.".format( code, path ), hint=hint.format(path), id="urls.E008", ), ) @override_settings( ROOT_URLCONF="check_framework.urls.good_function_based_error_handlers", ) def test_good_function_based_handlers(self): result = check_url_config(None) self.assertEqual(result, []) @override_settings( ROOT_URLCONF="check_framework.urls.good_class_based_error_handlers", ) def test_good_class_based_handlers(self): result = check_url_config(None) self.assertEqual(result, []) class CheckURLSettingsTests(SimpleTestCase): @override_settings(STATIC_URL="a/", MEDIA_URL="b/") def test_slash_no_errors(self): self.assertEqual(check_url_settings(None), []) @override_settings(STATIC_URL="", MEDIA_URL="") def test_empty_string_no_errors(self): self.assertEqual(check_url_settings(None), []) @override_settings(STATIC_URL="noslash") def test_static_url_no_slash(self): self.assertEqual(check_url_settings(None), [E006("STATIC_URL")]) @override_settings(STATIC_URL="slashes//") def test_static_url_double_slash_allowed(self): # The check allows for a double slash, presuming the user knows what # they are doing. self.assertEqual(check_url_settings(None), []) @override_settings(MEDIA_URL="noslash") def test_media_url_no_slash(self): self.assertEqual(check_url_settings(None), [E006("MEDIA_URL")])
7daa7eb375710dfedd7046b27e45db49eddb107611686b625a057cd571b21d5e
from asgiref.sync import iscoroutinefunction from django.http import HttpRequest, HttpResponse from django.test import SimpleTestCase from django.views.decorators.csrf import csrf_exempt class CsrfExemptTests(SimpleTestCase): def test_wrapped_sync_function_is_not_coroutine_function(self): def sync_view(request): return HttpResponse() wrapped_view = csrf_exempt(sync_view) self.assertIs(iscoroutinefunction(wrapped_view), False) def test_wrapped_async_function_is_coroutine_function(self): async def async_view(request): return HttpResponse() wrapped_view = csrf_exempt(async_view) self.assertIs(iscoroutinefunction(wrapped_view), True) def test_csrf_exempt_decorator(self): @csrf_exempt def sync_view(request): return HttpResponse() self.assertIs(sync_view.csrf_exempt, True) self.assertIsInstance(sync_view(HttpRequest()), HttpResponse) async def test_csrf_exempt_decorator_async_view(self): @csrf_exempt async def async_view(request): return HttpResponse() self.assertIs(async_view.csrf_exempt, True) self.assertIsInstance(await async_view(HttpRequest()), HttpResponse)
706ec27f50ed78f5d491eb576bd445479420ef904fe5480b5a4cfe0a7231ec0c
from asgiref.sync import iscoroutinefunction from django.http import HttpRequest, HttpResponse from django.test import SimpleTestCase from django.views.decorators.vary import vary_on_cookie, vary_on_headers class VaryOnHeadersTests(SimpleTestCase): def test_wrapped_sync_function_is_not_coroutine_function(self): def sync_view(request): return HttpResponse() wrapped_view = vary_on_headers()(sync_view) self.assertIs(iscoroutinefunction(wrapped_view), False) def test_wrapped_async_function_is_coroutine_function(self): async def async_view(request): return HttpResponse() wrapped_view = vary_on_headers()(async_view) self.assertIs(iscoroutinefunction(wrapped_view), True) def test_vary_on_headers_decorator(self): @vary_on_headers("Header", "Another-header") def sync_view(request): return HttpResponse() response = sync_view(HttpRequest()) self.assertEqual(response.get("Vary"), "Header, Another-header") async def test_vary_on_headers_decorator_async_view(self): @vary_on_headers("Header", "Another-header") async def async_view(request): return HttpResponse() response = await async_view(HttpRequest()) self.assertEqual(response.get("Vary"), "Header, Another-header") class VaryOnCookieTests(SimpleTestCase): def test_wrapped_sync_function_is_not_coroutine_function(self): def sync_view(request): return HttpResponse() wrapped_view = vary_on_cookie(sync_view) self.assertIs(iscoroutinefunction(wrapped_view), False) def test_wrapped_async_function_is_coroutine_function(self): async def async_view(request): return HttpResponse() wrapped_view = vary_on_cookie(async_view) self.assertIs(iscoroutinefunction(wrapped_view), True) def test_vary_on_cookie_decorator(self): @vary_on_cookie def sync_view(request): return HttpResponse() response = sync_view(HttpRequest()) self.assertEqual(response.get("Vary"), "Cookie") async def test_vary_on_cookie_decorator_async_view(self): @vary_on_cookie async def async_view(request): return HttpResponse() response = await async_view(HttpRequest()) self.assertEqual(response.get("Vary"), "Cookie")
747c7d5e06894dc137d68655defd544092903ea0bfa03fca6dd30de81af5c8ac
from math import ceil from operator import attrgetter from django.core.exceptions import FieldDoesNotExist from django.db import ( IntegrityError, NotSupportedError, OperationalError, ProgrammingError, connection, ) from django.db.models import FileField, Value from django.db.models.functions import Lower, Now from django.test import ( TestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from .models import ( BigAutoFieldModel, Country, FieldsWithDbColumns, NoFields, NullableFields, Pizzeria, ProxyCountry, ProxyMultiCountry, ProxyMultiProxyCountry, ProxyProxyCountry, RelatedModel, Restaurant, SmallAutoFieldModel, State, TwoFields, UpsertConflict, ) class BulkCreateTests(TestCase): def setUp(self): self.data = [ Country(name="United States of America", iso_two_letter="US"), Country(name="The Netherlands", iso_two_letter="NL"), Country(name="Germany", iso_two_letter="DE"), Country(name="Czech Republic", iso_two_letter="CZ"), ] def test_simple(self): created = Country.objects.bulk_create(self.data) self.assertEqual(created, self.data) self.assertQuerySetEqual( Country.objects.order_by("-name"), [ "United States of America", "The Netherlands", "Germany", "Czech Republic", ], attrgetter("name"), ) created = Country.objects.bulk_create([]) self.assertEqual(created, []) self.assertEqual(Country.objects.count(), 4) @skipUnlessDBFeature("has_bulk_insert") def test_efficiency(self): with self.assertNumQueries(1): Country.objects.bulk_create(self.data) @skipUnlessDBFeature("has_bulk_insert") def test_long_non_ascii_text(self): """ Inserting non-ASCII values with a length in the range 2001 to 4000 characters, i.e. 4002 to 8000 bytes, must be set as a CLOB on Oracle (#22144). """ Country.objects.bulk_create([Country(description="Ж" * 3000)]) self.assertEqual(Country.objects.count(), 1) @skipUnlessDBFeature("has_bulk_insert") def test_long_and_short_text(self): Country.objects.bulk_create( [ Country(description="a" * 4001, iso_two_letter="A"), Country(description="a", iso_two_letter="B"), Country(description="Ж" * 2001, iso_two_letter="C"), Country(description="Ж", iso_two_letter="D"), ] ) self.assertEqual(Country.objects.count(), 4) def test_multi_table_inheritance_unsupported(self): expected_message = "Can't bulk create a multi-table inherited model" with self.assertRaisesMessage(ValueError, expected_message): Pizzeria.objects.bulk_create( [ Pizzeria(name="The Art of Pizza"), ] ) with self.assertRaisesMessage(ValueError, expected_message): ProxyMultiCountry.objects.bulk_create( [ ProxyMultiCountry(name="Fillory", iso_two_letter="FL"), ] ) with self.assertRaisesMessage(ValueError, expected_message): ProxyMultiProxyCountry.objects.bulk_create( [ ProxyMultiProxyCountry(name="Fillory", iso_two_letter="FL"), ] ) def test_proxy_inheritance_supported(self): ProxyCountry.objects.bulk_create( [ ProxyCountry(name="Qwghlm", iso_two_letter="QW"), Country(name="Tortall", iso_two_letter="TA"), ] ) self.assertQuerySetEqual( ProxyCountry.objects.all(), {"Qwghlm", "Tortall"}, attrgetter("name"), ordered=False, ) ProxyProxyCountry.objects.bulk_create( [ ProxyProxyCountry(name="Netherlands", iso_two_letter="NT"), ] ) self.assertQuerySetEqual( ProxyProxyCountry.objects.all(), { "Qwghlm", "Tortall", "Netherlands", }, attrgetter("name"), ordered=False, ) def test_non_auto_increment_pk(self): State.objects.bulk_create( [State(two_letter_code=s) for s in ["IL", "NY", "CA", "ME"]] ) self.assertQuerySetEqual( State.objects.order_by("two_letter_code"), [ "CA", "IL", "ME", "NY", ], attrgetter("two_letter_code"), ) @skipUnlessDBFeature("has_bulk_insert") def test_non_auto_increment_pk_efficiency(self): with self.assertNumQueries(1): State.objects.bulk_create( [State(two_letter_code=s) for s in ["IL", "NY", "CA", "ME"]] ) self.assertQuerySetEqual( State.objects.order_by("two_letter_code"), [ "CA", "IL", "ME", "NY", ], attrgetter("two_letter_code"), ) @skipIfDBFeature("allows_auto_pk_0") def test_zero_as_autoval(self): """ Zero as id for AutoField should raise exception in MySQL, because MySQL does not allow zero for automatic primary key if the NO_AUTO_VALUE_ON_ZERO SQL mode is not enabled. """ valid_country = Country(name="Germany", iso_two_letter="DE") invalid_country = Country(id=0, name="Poland", iso_two_letter="PL") msg = "The database backend does not accept 0 as a value for AutoField." with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create([valid_country, invalid_country]) def test_batch_same_vals(self): # SQLite had a problem where all the same-valued models were # collapsed to one insert. Restaurant.objects.bulk_create([Restaurant(name="foo") for i in range(0, 2)]) self.assertEqual(Restaurant.objects.count(), 2) def test_large_batch(self): TwoFields.objects.bulk_create( [TwoFields(f1=i, f2=i + 1) for i in range(0, 1001)] ) self.assertEqual(TwoFields.objects.count(), 1001) self.assertEqual( TwoFields.objects.filter(f1__gte=450, f1__lte=550).count(), 101 ) self.assertEqual(TwoFields.objects.filter(f2__gte=901).count(), 101) @skipUnlessDBFeature("has_bulk_insert") def test_large_single_field_batch(self): # SQLite had a problem with more than 500 UNIONed selects in single # query. Restaurant.objects.bulk_create([Restaurant() for i in range(0, 501)]) @skipUnlessDBFeature("has_bulk_insert") def test_large_batch_efficiency(self): with override_settings(DEBUG=True): connection.queries_log.clear() TwoFields.objects.bulk_create( [TwoFields(f1=i, f2=i + 1) for i in range(0, 1001)] ) self.assertLess(len(connection.queries), 10) def test_large_batch_mixed(self): """ Test inserting a large batch with objects having primary key set mixed together with objects without PK set. """ TwoFields.objects.bulk_create( [ TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1) for i in range(100000, 101000) ] ) self.assertEqual(TwoFields.objects.count(), 1000) # We can't assume much about the ID's created, except that the above # created IDs must exist. id_range = range(100000, 101000, 2) self.assertEqual(TwoFields.objects.filter(id__in=id_range).count(), 500) self.assertEqual(TwoFields.objects.exclude(id__in=id_range).count(), 500) @skipUnlessDBFeature("has_bulk_insert") def test_large_batch_mixed_efficiency(self): """ Test inserting a large batch with objects having primary key set mixed together with objects without PK set. """ with override_settings(DEBUG=True): connection.queries_log.clear() TwoFields.objects.bulk_create( [ TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1) for i in range(100000, 101000) ] ) self.assertLess(len(connection.queries), 10) def test_explicit_batch_size(self): objs = [TwoFields(f1=i, f2=i) for i in range(0, 4)] num_objs = len(objs) TwoFields.objects.bulk_create(objs, batch_size=1) self.assertEqual(TwoFields.objects.count(), num_objs) TwoFields.objects.all().delete() TwoFields.objects.bulk_create(objs, batch_size=2) self.assertEqual(TwoFields.objects.count(), num_objs) TwoFields.objects.all().delete() TwoFields.objects.bulk_create(objs, batch_size=3) self.assertEqual(TwoFields.objects.count(), num_objs) TwoFields.objects.all().delete() TwoFields.objects.bulk_create(objs, batch_size=num_objs) self.assertEqual(TwoFields.objects.count(), num_objs) def test_empty_model(self): NoFields.objects.bulk_create([NoFields() for i in range(2)]) self.assertEqual(NoFields.objects.count(), 2) @skipUnlessDBFeature("has_bulk_insert") def test_explicit_batch_size_efficiency(self): objs = [TwoFields(f1=i, f2=i) for i in range(0, 100)] with self.assertNumQueries(2): TwoFields.objects.bulk_create(objs, 50) TwoFields.objects.all().delete() with self.assertNumQueries(1): TwoFields.objects.bulk_create(objs, len(objs)) @skipUnlessDBFeature("has_bulk_insert") def test_explicit_batch_size_respects_max_batch_size(self): objs = [Country(name=f"Country {i}") for i in range(1000)] fields = ["name", "iso_two_letter", "description"] max_batch_size = max(connection.ops.bulk_batch_size(fields, objs), 1) with self.assertNumQueries(ceil(len(objs) / max_batch_size)): Country.objects.bulk_create(objs, batch_size=max_batch_size + 1) @skipUnlessDBFeature("has_bulk_insert") def test_bulk_insert_expressions(self): Restaurant.objects.bulk_create( [ Restaurant(name="Sam's Shake Shack"), Restaurant(name=Lower(Value("Betty's Beetroot Bar"))), ] ) bbb = Restaurant.objects.filter(name="betty's beetroot bar") self.assertEqual(bbb.count(), 1) @skipUnlessDBFeature("has_bulk_insert") def test_bulk_insert_now(self): NullableFields.objects.bulk_create( [ NullableFields(datetime_field=Now()), NullableFields(datetime_field=Now()), ] ) self.assertEqual( NullableFields.objects.filter(datetime_field__isnull=False).count(), 2, ) @skipUnlessDBFeature("has_bulk_insert") def test_bulk_insert_nullable_fields(self): fk_to_auto_fields = { "auto_field": NoFields.objects.create(), "small_auto_field": SmallAutoFieldModel.objects.create(), "big_auto_field": BigAutoFieldModel.objects.create(), } # NULL can be mixed with other values in nullable fields nullable_fields = [ field for field in NullableFields._meta.get_fields() if field.name != "id" ] NullableFields.objects.bulk_create( [ NullableFields(**{**fk_to_auto_fields, field.name: None}) for field in nullable_fields ] ) self.assertEqual(NullableFields.objects.count(), len(nullable_fields)) for field in nullable_fields: with self.subTest(field=field): field_value = "" if isinstance(field, FileField) else None self.assertEqual( NullableFields.objects.filter(**{field.name: field_value}).count(), 1, ) @skipUnlessDBFeature("can_return_rows_from_bulk_insert") def test_set_pk_and_insert_single_item(self): with self.assertNumQueries(1): countries = Country.objects.bulk_create([self.data[0]]) self.assertEqual(len(countries), 1) self.assertEqual(Country.objects.get(pk=countries[0].pk), countries[0]) @skipUnlessDBFeature("can_return_rows_from_bulk_insert") def test_set_pk_and_query_efficiency(self): with self.assertNumQueries(1): countries = Country.objects.bulk_create(self.data) self.assertEqual(len(countries), 4) self.assertEqual(Country.objects.get(pk=countries[0].pk), countries[0]) self.assertEqual(Country.objects.get(pk=countries[1].pk), countries[1]) self.assertEqual(Country.objects.get(pk=countries[2].pk), countries[2]) self.assertEqual(Country.objects.get(pk=countries[3].pk), countries[3]) @skipUnlessDBFeature("can_return_rows_from_bulk_insert") def test_set_state(self): country_nl = Country(name="Netherlands", iso_two_letter="NL") country_be = Country(name="Belgium", iso_two_letter="BE") Country.objects.bulk_create([country_nl]) country_be.save() # Objects save via bulk_create() and save() should have equal state. self.assertEqual(country_nl._state.adding, country_be._state.adding) self.assertEqual(country_nl._state.db, country_be._state.db) def test_set_state_with_pk_specified(self): state_ca = State(two_letter_code="CA") state_ny = State(two_letter_code="NY") State.objects.bulk_create([state_ca]) state_ny.save() # Objects save via bulk_create() and save() should have equal state. self.assertEqual(state_ca._state.adding, state_ny._state.adding) self.assertEqual(state_ca._state.db, state_ny._state.db) @skipIfDBFeature("supports_ignore_conflicts") def test_ignore_conflicts_value_error(self): message = "This database backend does not support ignoring conflicts." with self.assertRaisesMessage(NotSupportedError, message): TwoFields.objects.bulk_create(self.data, ignore_conflicts=True) @skipUnlessDBFeature("supports_ignore_conflicts") def test_ignore_conflicts_ignore(self): data = [ TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2), TwoFields(f1=3, f2=3), ] TwoFields.objects.bulk_create(data) self.assertEqual(TwoFields.objects.count(), 3) # With ignore_conflicts=True, conflicts are ignored. conflicting_objects = [ TwoFields(f1=2, f2=2), TwoFields(f1=3, f2=3), ] TwoFields.objects.bulk_create([conflicting_objects[0]], ignore_conflicts=True) TwoFields.objects.bulk_create(conflicting_objects, ignore_conflicts=True) self.assertEqual(TwoFields.objects.count(), 3) self.assertIsNone(conflicting_objects[0].pk) self.assertIsNone(conflicting_objects[1].pk) # New objects are created and conflicts are ignored. new_object = TwoFields(f1=4, f2=4) TwoFields.objects.bulk_create( conflicting_objects + [new_object], ignore_conflicts=True ) self.assertEqual(TwoFields.objects.count(), 4) self.assertIsNone(new_object.pk) # Without ignore_conflicts=True, there's a problem. with self.assertRaises(IntegrityError): TwoFields.objects.bulk_create(conflicting_objects) def test_nullable_fk_after_parent(self): parent = NoFields() child = NullableFields(auto_field=parent, integer_field=88) parent.save() NullableFields.objects.bulk_create([child]) child = NullableFields.objects.get(integer_field=88) self.assertEqual(child.auto_field, parent) @skipUnlessDBFeature("can_return_rows_from_bulk_insert") def test_nullable_fk_after_parent_bulk_create(self): parent = NoFields() child = NullableFields(auto_field=parent, integer_field=88) NoFields.objects.bulk_create([parent]) NullableFields.objects.bulk_create([child]) child = NullableFields.objects.get(integer_field=88) self.assertEqual(child.auto_field, parent) def test_unsaved_parent(self): parent = NoFields() msg = ( "bulk_create() prohibited to prevent data loss due to unsaved " "related object 'auto_field'." ) with self.assertRaisesMessage(ValueError, msg): NullableFields.objects.bulk_create([NullableFields(auto_field=parent)]) def test_invalid_batch_size_exception(self): msg = "Batch size must be a positive integer." with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create([], batch_size=-1) @skipIfDBFeature("supports_update_conflicts") def test_update_conflicts_unsupported(self): msg = "This database backend does not support updating conflicts." with self.assertRaisesMessage(NotSupportedError, msg): Country.objects.bulk_create(self.data, update_conflicts=True) @skipUnlessDBFeature("supports_ignore_conflicts", "supports_update_conflicts") def test_ignore_update_conflicts_exclusive(self): msg = "ignore_conflicts and update_conflicts are mutually exclusive" with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create( self.data, ignore_conflicts=True, update_conflicts=True, ) @skipUnlessDBFeature("supports_update_conflicts") def test_update_conflicts_no_update_fields(self): msg = ( "Fields that will be updated when a row insertion fails on " "conflicts must be provided." ) with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create(self.data, update_conflicts=True) @skipUnlessDBFeature("supports_update_conflicts") @skipIfDBFeature("supports_update_conflicts_with_target") def test_update_conflicts_unique_field_unsupported(self): msg = ( "This database backend does not support updating conflicts with " "specifying unique fields that can trigger the upsert." ) with self.assertRaisesMessage(NotSupportedError, msg): TwoFields.objects.bulk_create( [TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2)], update_conflicts=True, update_fields=["f2"], unique_fields=["f1"], ) @skipUnlessDBFeature("supports_update_conflicts") def test_update_conflicts_nonexistent_update_fields(self): unique_fields = None if connection.features.supports_update_conflicts_with_target: unique_fields = ["f1"] msg = "TwoFields has no field named 'nonexistent'" with self.assertRaisesMessage(FieldDoesNotExist, msg): TwoFields.objects.bulk_create( [TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2)], update_conflicts=True, update_fields=["nonexistent"], unique_fields=unique_fields, ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target", ) def test_update_conflicts_unique_fields_required(self): msg = "Unique fields that can trigger the upsert must be provided." with self.assertRaisesMessage(ValueError, msg): TwoFields.objects.bulk_create( [TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2)], update_conflicts=True, update_fields=["f1"], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target", ) def test_update_conflicts_invalid_update_fields(self): msg = "bulk_create() can only be used with concrete fields in update_fields." # Reverse one-to-one relationship. with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create( self.data, update_conflicts=True, update_fields=["relatedmodel"], unique_fields=["pk"], ) # Many-to-many relationship. with self.assertRaisesMessage(ValueError, msg): RelatedModel.objects.bulk_create( [RelatedModel(country=self.data[0])], update_conflicts=True, update_fields=["big_auto_fields"], unique_fields=["country"], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target", ) def test_update_conflicts_pk_in_update_fields(self): msg = "bulk_create() cannot be used with primary keys in update_fields." with self.assertRaisesMessage(ValueError, msg): BigAutoFieldModel.objects.bulk_create( [BigAutoFieldModel()], update_conflicts=True, update_fields=["id"], unique_fields=["id"], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target", ) def test_update_conflicts_invalid_unique_fields(self): msg = "bulk_create() can only be used with concrete fields in unique_fields." # Reverse one-to-one relationship. with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create( self.data, update_conflicts=True, update_fields=["name"], unique_fields=["relatedmodel"], ) # Many-to-many relationship. with self.assertRaisesMessage(ValueError, msg): RelatedModel.objects.bulk_create( [RelatedModel(country=self.data[0])], update_conflicts=True, update_fields=["name"], unique_fields=["big_auto_fields"], ) def _test_update_conflicts_two_fields(self, unique_fields): TwoFields.objects.bulk_create( [ TwoFields(f1=1, f2=1, name="a"), TwoFields(f1=2, f2=2, name="b"), ] ) self.assertEqual(TwoFields.objects.count(), 2) conflicting_objects = [ TwoFields(f1=1, f2=1, name="c"), TwoFields(f1=2, f2=2, name="d"), ] results = TwoFields.objects.bulk_create( conflicting_objects, update_conflicts=True, unique_fields=unique_fields, update_fields=["name"], ) self.assertEqual(len(results), len(conflicting_objects)) if connection.features.can_return_rows_from_bulk_insert: for instance in results: self.assertIsNotNone(instance.pk) self.assertEqual(TwoFields.objects.count(), 2) self.assertCountEqual( TwoFields.objects.values("f1", "f2", "name"), [ {"f1": 1, "f2": 1, "name": "c"}, {"f1": 2, "f2": 2, "name": "d"}, ], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_two_fields_unique_fields_first(self): self._test_update_conflicts_two_fields(["f1"]) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_two_fields_unique_fields_second(self): self._test_update_conflicts_two_fields(["f2"]) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_unique_fields_pk(self): TwoFields.objects.bulk_create( [ TwoFields(f1=1, f2=1, name="a"), TwoFields(f1=2, f2=2, name="b"), ] ) obj1 = TwoFields.objects.get(f1=1) obj2 = TwoFields.objects.get(f1=2) conflicting_objects = [ TwoFields(pk=obj1.pk, f1=3, f2=3, name="c"), TwoFields(pk=obj2.pk, f1=4, f2=4, name="d"), ] results = TwoFields.objects.bulk_create( conflicting_objects, update_conflicts=True, unique_fields=["pk"], update_fields=["name"], ) self.assertEqual(len(results), len(conflicting_objects)) if connection.features.can_return_rows_from_bulk_insert: for instance in results: self.assertIsNotNone(instance.pk) self.assertEqual(TwoFields.objects.count(), 2) self.assertCountEqual( TwoFields.objects.values("f1", "f2", "name"), [ {"f1": 1, "f2": 1, "name": "c"}, {"f1": 2, "f2": 2, "name": "d"}, ], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_two_fields_unique_fields_both(self): with self.assertRaises((OperationalError, ProgrammingError)): self._test_update_conflicts_two_fields(["f1", "f2"]) @skipUnlessDBFeature("supports_update_conflicts") @skipIfDBFeature("supports_update_conflicts_with_target") def test_update_conflicts_two_fields_no_unique_fields(self): self._test_update_conflicts_two_fields([]) def _test_update_conflicts_unique_two_fields(self, unique_fields): Country.objects.bulk_create(self.data) self.assertEqual(Country.objects.count(), 4) new_data = [ # Conflicting countries. Country( name="Germany", iso_two_letter="DE", description=("Germany is a country in Central Europe."), ), Country( name="Czech Republic", iso_two_letter="CZ", description=( "The Czech Republic is a landlocked country in Central Europe." ), ), # New countries. Country(name="Australia", iso_two_letter="AU"), Country( name="Japan", iso_two_letter="JP", description=("Japan is an island country in East Asia."), ), ] results = Country.objects.bulk_create( new_data, update_conflicts=True, update_fields=["description"], unique_fields=unique_fields, ) self.assertEqual(len(results), len(new_data)) if connection.features.can_return_rows_from_bulk_insert: for instance in results: self.assertIsNotNone(instance.pk) self.assertEqual(Country.objects.count(), 6) self.assertCountEqual( Country.objects.values("iso_two_letter", "description"), [ {"iso_two_letter": "US", "description": ""}, {"iso_two_letter": "NL", "description": ""}, { "iso_two_letter": "DE", "description": ("Germany is a country in Central Europe."), }, { "iso_two_letter": "CZ", "description": ( "The Czech Republic is a landlocked country in Central Europe." ), }, {"iso_two_letter": "AU", "description": ""}, { "iso_two_letter": "JP", "description": ("Japan is an island country in East Asia."), }, ], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_unique_two_fields_unique_fields_both(self): self._test_update_conflicts_unique_two_fields(["iso_two_letter", "name"]) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_unique_two_fields_unique_fields_one(self): with self.assertRaises((OperationalError, ProgrammingError)): self._test_update_conflicts_unique_two_fields(["iso_two_letter"]) @skipUnlessDBFeature("supports_update_conflicts") @skipIfDBFeature("supports_update_conflicts_with_target") def test_update_conflicts_unique_two_fields_unique_no_unique_fields(self): self._test_update_conflicts_unique_two_fields([]) def _test_update_conflicts(self, unique_fields): UpsertConflict.objects.bulk_create( [ UpsertConflict(number=1, rank=1, name="John"), UpsertConflict(number=2, rank=2, name="Mary"), UpsertConflict(number=3, rank=3, name="Hannah"), ] ) self.assertEqual(UpsertConflict.objects.count(), 3) conflicting_objects = [ UpsertConflict(number=1, rank=4, name="Steve"), UpsertConflict(number=2, rank=2, name="Olivia"), UpsertConflict(number=3, rank=1, name="Hannah"), ] results = UpsertConflict.objects.bulk_create( conflicting_objects, update_conflicts=True, update_fields=["name", "rank"], unique_fields=unique_fields, ) self.assertEqual(len(results), len(conflicting_objects)) if connection.features.can_return_rows_from_bulk_insert: for instance in results: self.assertIsNotNone(instance.pk) self.assertEqual(UpsertConflict.objects.count(), 3) self.assertCountEqual( UpsertConflict.objects.values("number", "rank", "name"), [ {"number": 1, "rank": 4, "name": "Steve"}, {"number": 2, "rank": 2, "name": "Olivia"}, {"number": 3, "rank": 1, "name": "Hannah"}, ], ) results = UpsertConflict.objects.bulk_create( conflicting_objects + [UpsertConflict(number=4, rank=4, name="Mark")], update_conflicts=True, update_fields=["name", "rank"], unique_fields=unique_fields, ) self.assertEqual(len(results), 4) if connection.features.can_return_rows_from_bulk_insert: for instance in results: self.assertIsNotNone(instance.pk) self.assertEqual(UpsertConflict.objects.count(), 4) self.assertCountEqual( UpsertConflict.objects.values("number", "rank", "name"), [ {"number": 1, "rank": 4, "name": "Steve"}, {"number": 2, "rank": 2, "name": "Olivia"}, {"number": 3, "rank": 1, "name": "Hannah"}, {"number": 4, "rank": 4, "name": "Mark"}, ], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_unique_fields(self): self._test_update_conflicts(unique_fields=["number"]) @skipUnlessDBFeature("supports_update_conflicts") @skipIfDBFeature("supports_update_conflicts_with_target") def test_update_conflicts_no_unique_fields(self): self._test_update_conflicts([]) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_unique_fields_update_fields_db_column(self): FieldsWithDbColumns.objects.bulk_create( [ FieldsWithDbColumns(rank=1, name="a"), FieldsWithDbColumns(rank=2, name="b"), ] ) self.assertEqual(FieldsWithDbColumns.objects.count(), 2) conflicting_objects = [ FieldsWithDbColumns(rank=1, name="c"), FieldsWithDbColumns(rank=2, name="d"), ] results = FieldsWithDbColumns.objects.bulk_create( conflicting_objects, update_conflicts=True, unique_fields=["rank"], update_fields=["name"], ) self.assertEqual(len(results), len(conflicting_objects)) if connection.features.can_return_rows_from_bulk_insert: for instance in results: self.assertIsNotNone(instance.pk) self.assertEqual(FieldsWithDbColumns.objects.count(), 2) self.assertCountEqual( FieldsWithDbColumns.objects.values("rank", "name"), [ {"rank": 1, "name": "c"}, {"rank": 2, "name": "d"}, ], )
e280bdc7e3161bbbea448d5157c25123189dc944a603fba396e47f0b27326ba4
import mimetypes import os import shutil import socket import sys import tempfile from email import charset, message_from_binary_file, message_from_bytes from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr from io import StringIO from pathlib import Path from smtplib import SMTP, SMTPException from ssl import SSLError from unittest import mock, skipUnless from django.core import mail from django.core.mail import ( DNS_NAME, EmailMessage, EmailMultiAlternatives, mail_admins, mail_managers, send_mail, send_mass_mail, ) from django.core.mail.backends import console, dummy, filebased, locmem, smtp from django.core.mail.message import BadHeaderError, sanitize_address from django.test import SimpleTestCase, override_settings from django.test.utils import requires_tz_support from django.utils.translation import gettext_lazy from django.utils.version import PY311 try: from aiosmtpd.controller import Controller HAS_AIOSMTPD = True except ImportError: HAS_AIOSMTPD = False class HeadersCheckMixin: def assertMessageHasHeaders(self, message, headers): """ Asserts that the `message` has all `headers`. message: can be an instance of an email.Message subclass or a string with the contents of an email message. headers: should be a set of (header-name, header-value) tuples. """ if isinstance(message, bytes): message = message_from_bytes(message) msg_headers = set(message.items()) self.assertTrue( headers.issubset(msg_headers), msg="Message is missing " "the following headers: %s" % (headers - msg_headers), ) class MailTests(HeadersCheckMixin, SimpleTestCase): """ Non-backend specific tests. """ def get_decoded_attachments(self, django_message): """ Encode the specified django.core.mail.message.EmailMessage, then decode it using Python's email.parser module and, for each attachment of the message, return a list of tuples with (filename, content, mimetype). """ msg_bytes = django_message.message().as_bytes() email_message = message_from_bytes(msg_bytes) def iter_attachments(): for i in email_message.walk(): if i.get_content_disposition() == "attachment": filename = i.get_filename() content = i.get_payload(decode=True) mimetype = i.get_content_type() yield filename, content, mimetype return list(iter_attachments()) def test_ascii(self): email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"] ) message = email.message() self.assertEqual(message["Subject"], "Subject") self.assertEqual(message.get_payload(), "Content") self.assertEqual(message["From"], "[email protected]") self.assertEqual(message["To"], "[email protected]") def test_multiple_recipients(self): email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]", "[email protected]"], ) message = email.message() self.assertEqual(message["Subject"], "Subject") self.assertEqual(message.get_payload(), "Content") self.assertEqual(message["From"], "[email protected]") self.assertEqual(message["To"], "[email protected], [email protected]") def test_header_omitted_for_no_to_recipients(self): message = EmailMessage( "Subject", "Content", "[email protected]", cc=["[email protected]"] ).message() self.assertNotIn("To", message) def test_recipients_with_empty_strings(self): """ Empty strings in various recipient arguments are always stripped off the final recipient list. """ email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]", ""], cc=["[email protected]", ""], bcc=["", "[email protected]"], reply_to=["", None], ) self.assertEqual( email.recipients(), ["[email protected]", "[email protected]", "[email protected]"] ) def test_cc(self): """Regression test for #7722""" email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"], cc=["[email protected]"], ) message = email.message() self.assertEqual(message["Cc"], "[email protected]") self.assertEqual(email.recipients(), ["[email protected]", "[email protected]"]) # Test multiple CC with multiple To email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]", "[email protected]"], cc=["[email protected]", "[email protected]"], ) message = email.message() self.assertEqual(message["Cc"], "[email protected], [email protected]") self.assertEqual( email.recipients(), [ "[email protected]", "[email protected]", "[email protected]", "[email protected]", ], ) # Testing with Bcc email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]", "[email protected]"], cc=["[email protected]", "[email protected]"], bcc=["[email protected]"], ) message = email.message() self.assertEqual(message["Cc"], "[email protected], [email protected]") self.assertEqual( email.recipients(), [ "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", ], ) def test_cc_headers(self): message = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"], cc=["[email protected]"], headers={"Cc": "[email protected]"}, ).message() self.assertEqual(message["Cc"], "[email protected]") def test_cc_in_headers_only(self): message = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"], headers={"Cc": "[email protected]"}, ).message() self.assertEqual(message["Cc"], "[email protected]") def test_reply_to(self): email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"], reply_to=["[email protected]"], ) message = email.message() self.assertEqual(message["Reply-To"], "[email protected]") email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"], reply_to=["[email protected]", "[email protected]"], ) message = email.message() self.assertEqual( message["Reply-To"], "[email protected], [email protected]" ) def test_recipients_as_tuple(self): email = EmailMessage( "Subject", "Content", "[email protected]", ("[email protected]", "[email protected]"), cc=("[email protected]", "[email protected]"), bcc=("[email protected]",), ) message = email.message() self.assertEqual(message["Cc"], "[email protected], [email protected]") self.assertEqual( email.recipients(), [ "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", ], ) def test_recipients_as_string(self): with self.assertRaisesMessage( TypeError, '"to" argument must be a list or tuple' ): EmailMessage(to="[email protected]") with self.assertRaisesMessage( TypeError, '"cc" argument must be a list or tuple' ): EmailMessage(cc="[email protected]") with self.assertRaisesMessage( TypeError, '"bcc" argument must be a list or tuple' ): EmailMessage(bcc="[email protected]") with self.assertRaisesMessage( TypeError, '"reply_to" argument must be a list or tuple' ): EmailMessage(reply_to="[email protected]") def test_header_injection(self): msg = "Header values can't contain newlines " email = EmailMessage( "Subject\nInjection Test", "Content", "[email protected]", ["[email protected]"] ) with self.assertRaisesMessage(BadHeaderError, msg): email.message() email = EmailMessage( gettext_lazy("Subject\nInjection Test"), "Content", "[email protected]", ["[email protected]"], ) with self.assertRaisesMessage(BadHeaderError, msg): email.message() with self.assertRaisesMessage(BadHeaderError, msg): EmailMessage( "Subject", "Content", "[email protected]", ["Name\nInjection test <[email protected]>"], ).message() def test_space_continuation(self): """ Test for space continuation character in long (ASCII) subject headers (#7747) """ email = EmailMessage( "Long subject lines that get wrapped should contain a space continuation " "character to get expected behavior in Outlook and Thunderbird", "Content", "[email protected]", ["[email protected]"], ) message = email.message() self.assertEqual( message["Subject"].encode(), b"Long subject lines that get wrapped should contain a space continuation\n" b" character to get expected behavior in Outlook and Thunderbird", ) def test_message_header_overrides(self): """ Specifying dates or message-ids in the extra headers overrides the default values (#9233) """ headers = {"date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} email = EmailMessage( "subject", "content", "[email protected]", ["[email protected]"], headers=headers, ) self.assertMessageHasHeaders( email.message(), { ("Content-Transfer-Encoding", "7bit"), ("Content-Type", 'text/plain; charset="utf-8"'), ("From", "[email protected]"), ("MIME-Version", "1.0"), ("Message-ID", "foo"), ("Subject", "subject"), ("To", "[email protected]"), ("date", "Fri, 09 Nov 2001 01:08:47 -0000"), }, ) def test_from_header(self): """ Make sure we can manually set the From header (#9214) """ email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"], headers={"From": "[email protected]"}, ) message = email.message() self.assertEqual(message["From"], "[email protected]") def test_to_header(self): """ Make sure we can manually set the To header (#17444) """ email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]", "[email protected]"], headers={"To": "[email protected]"}, ) message = email.message() self.assertEqual(message["To"], "[email protected]") self.assertEqual( email.to, ["[email protected]", "[email protected]"] ) # If we don't set the To header manually, it should default to the `to` # argument to the constructor. email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]", "[email protected]"], ) message = email.message() self.assertEqual( message["To"], "[email protected], [email protected]" ) self.assertEqual( email.to, ["[email protected]", "[email protected]"] ) def test_to_in_headers_only(self): message = EmailMessage( "Subject", "Content", "[email protected]", headers={"To": "[email protected]"}, ).message() self.assertEqual(message["To"], "[email protected]") def test_reply_to_header(self): """ Specifying 'Reply-To' in headers should override reply_to. """ email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"], reply_to=["[email protected]"], headers={"Reply-To": "[email protected]"}, ) message = email.message() self.assertEqual(message["Reply-To"], "[email protected]") def test_reply_to_in_headers_only(self): message = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"], headers={"Reply-To": "[email protected]"}, ).message() self.assertEqual(message["Reply-To"], "[email protected]") def test_multiple_message_call(self): """ Regression for #13259 - Make sure that headers are not changed when calling EmailMessage.message() """ email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"], headers={"From": "[email protected]"}, ) message = email.message() self.assertEqual(message["From"], "[email protected]") message = email.message() self.assertEqual(message["From"], "[email protected]") def test_unicode_address_header(self): """ Regression for #11144 - When a to/from/cc header contains Unicode, make sure the email addresses are parsed correctly (especially with regards to commas) """ email = EmailMessage( "Subject", "Content", "[email protected]", ['"Firstname Sürname" <[email protected]>', "[email protected]"], ) self.assertEqual( email.message()["To"], "=?utf-8?q?Firstname_S=C3=BCrname?= <[email protected]>, [email protected]", ) email = EmailMessage( "Subject", "Content", "[email protected]", ['"Sürname, Firstname" <[email protected]>', "[email protected]"], ) self.assertEqual( email.message()["To"], "=?utf-8?q?S=C3=BCrname=2C_Firstname?= <[email protected]>, [email protected]", ) def test_unicode_headers(self): email = EmailMessage( "Gżegżółka", "Content", "[email protected]", ["[email protected]"], headers={ "Sender": '"Firstname Sürname" <[email protected]>', "Comments": "My Sürname is non-ASCII", }, ) message = email.message() self.assertEqual(message["Subject"], "=?utf-8?b?R8W8ZWfFvMOzxYJrYQ==?=") self.assertEqual( message["Sender"], "=?utf-8?q?Firstname_S=C3=BCrname?= <[email protected]>" ) self.assertEqual( message["Comments"], "=?utf-8?q?My_S=C3=BCrname_is_non-ASCII?=" ) def test_safe_mime_multipart(self): """ Make sure headers can be set with a different encoding than utf-8 in SafeMIMEMultipart as well """ headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} from_email, to = "[email protected]", '"Sürname, Firstname" <[email protected]>' text_content = "This is an important message." html_content = "<p>This is an <strong>important</strong> message.</p>" msg = EmailMultiAlternatives( "Message from Firstname Sürname", text_content, from_email, [to], headers=headers, ) msg.attach_alternative(html_content, "text/html") msg.encoding = "iso-8859-1" self.assertEqual( msg.message()["To"], "=?iso-8859-1?q?S=FCrname=2C_Firstname?= <[email protected]>", ) self.assertEqual( msg.message()["Subject"], "=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=", ) def test_safe_mime_multipart_with_attachments(self): """ EmailMultiAlternatives includes alternatives if the body is empty and it has attachments. """ msg = EmailMultiAlternatives(body="") html_content = "<p>This is <strong>html</strong></p>" msg.attach_alternative(html_content, "text/html") msg.attach("example.txt", "Text file content", "text/plain") self.assertIn(html_content, msg.message().as_string()) def test_none_body(self): msg = EmailMessage("subject", None, "[email protected]", ["[email protected]"]) self.assertEqual(msg.body, "") self.assertEqual(msg.message().get_payload(), "") @mock.patch("socket.getfqdn", return_value="漢字") def test_non_ascii_dns_non_unicode_email(self, mocked_getfqdn): delattr(DNS_NAME, "_fqdn") email = EmailMessage( "subject", "content", "[email protected]", ["[email protected]"] ) email.encoding = "iso-8859-1" self.assertIn("@xn--p8s937b>", email.message()["Message-ID"]) def test_encoding(self): """ Regression for #12791 - Encode body correctly with other encodings than utf-8 """ email = EmailMessage( "Subject", "Firstname Sürname is a great guy.", "[email protected]", ["[email protected]"], ) email.encoding = "iso-8859-1" message = email.message() self.assertMessageHasHeaders( message, { ("MIME-Version", "1.0"), ("Content-Type", 'text/plain; charset="iso-8859-1"'), ("Content-Transfer-Encoding", "quoted-printable"), ("Subject", "Subject"), ("From", "[email protected]"), ("To", "[email protected]"), }, ) self.assertEqual(message.get_payload(), "Firstname S=FCrname is a great guy.") # MIME attachments works correctly with other encodings than utf-8. text_content = "Firstname Sürname is a great guy." html_content = "<p>Firstname Sürname is a <strong>great</strong> guy.</p>" msg = EmailMultiAlternatives( "Subject", text_content, "[email protected]", ["[email protected]"] ) msg.encoding = "iso-8859-1" msg.attach_alternative(html_content, "text/html") payload0 = msg.message().get_payload(0) self.assertMessageHasHeaders( payload0, { ("MIME-Version", "1.0"), ("Content-Type", 'text/plain; charset="iso-8859-1"'), ("Content-Transfer-Encoding", "quoted-printable"), }, ) self.assertTrue( payload0.as_bytes().endswith(b"\n\nFirstname S=FCrname is a great guy.") ) payload1 = msg.message().get_payload(1) self.assertMessageHasHeaders( payload1, { ("MIME-Version", "1.0"), ("Content-Type", 'text/html; charset="iso-8859-1"'), ("Content-Transfer-Encoding", "quoted-printable"), }, ) self.assertTrue( payload1.as_bytes().endswith( b"\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>" ) ) def test_attachments(self): """Regression test for #9367""" headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} subject, from_email, to = "hello", "[email protected]", "[email protected]" text_content = "This is an important message." html_content = "<p>This is an <strong>important</strong> message.</p>" msg = EmailMultiAlternatives( subject, text_content, from_email, [to], headers=headers ) msg.attach_alternative(html_content, "text/html") msg.attach("an attachment.pdf", b"%PDF-1.4.%...", mimetype="application/pdf") msg_bytes = msg.message().as_bytes() message = message_from_bytes(msg_bytes) self.assertTrue(message.is_multipart()) self.assertEqual(message.get_content_type(), "multipart/mixed") self.assertEqual(message.get_default_type(), "text/plain") payload = message.get_payload() self.assertEqual(payload[0].get_content_type(), "multipart/alternative") self.assertEqual(payload[1].get_content_type(), "application/pdf") def test_attachments_two_tuple(self): msg = EmailMessage(attachments=[("filename1", "content1")]) filename, content, mimetype = self.get_decoded_attachments(msg)[0] self.assertEqual(filename, "filename1") self.assertEqual(content, b"content1") self.assertEqual(mimetype, "application/octet-stream") def test_attachments_MIMEText(self): txt = MIMEText("content1") msg = EmailMessage(attachments=[txt]) payload = msg.message().get_payload() self.assertEqual(payload[0], txt) def test_non_ascii_attachment_filename(self): """Regression test for #14964""" headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} subject, from_email, to = "hello", "[email protected]", "[email protected]" content = "This is the message." msg = EmailMessage(subject, content, from_email, [to], headers=headers) # Unicode in file name msg.attach("une pièce jointe.pdf", b"%PDF-1.4.%...", mimetype="application/pdf") msg_bytes = msg.message().as_bytes() message = message_from_bytes(msg_bytes) payload = message.get_payload() self.assertEqual(payload[1].get_filename(), "une pièce jointe.pdf") def test_attach_file(self): """ Test attaching a file against different mimetypes and make sure that a file will be attached and sent properly even if an invalid mimetype is specified. """ files = ( # filename, actual mimetype ("file.txt", "text/plain"), ("file.png", "image/png"), ("file_txt", None), ("file_png", None), ("file_txt.png", "image/png"), ("file_png.txt", "text/plain"), ("file.eml", "message/rfc822"), ) test_mimetypes = ["text/plain", "image/png", None] for basename, real_mimetype in files: for mimetype in test_mimetypes: email = EmailMessage( "subject", "body", "[email protected]", ["[email protected]"] ) self.assertEqual(mimetypes.guess_type(basename)[0], real_mimetype) self.assertEqual(email.attachments, []) file_path = os.path.join( os.path.dirname(__file__), "attachments", basename ) email.attach_file(file_path, mimetype=mimetype) self.assertEqual(len(email.attachments), 1) self.assertIn(basename, email.attachments[0]) msgs_sent_num = email.send() self.assertEqual(msgs_sent_num, 1) def test_attach_text_as_bytes(self): msg = EmailMessage("subject", "body", "[email protected]", ["[email protected]"]) msg.attach("file.txt", b"file content") sent_num = msg.send() self.assertEqual(sent_num, 1) filename, content, mimetype = self.get_decoded_attachments(msg)[0] self.assertEqual(filename, "file.txt") self.assertEqual(content, b"file content") self.assertEqual(mimetype, "text/plain") def test_attach_utf8_text_as_bytes(self): """ Non-ASCII characters encoded as valid UTF-8 are correctly transported and decoded. """ msg = EmailMessage("subject", "body", "[email protected]", ["[email protected]"]) msg.attach("file.txt", b"\xc3\xa4") # UTF-8 encoded a umlaut. filename, content, mimetype = self.get_decoded_attachments(msg)[0] self.assertEqual(filename, "file.txt") self.assertEqual(content, b"\xc3\xa4") self.assertEqual(mimetype, "text/plain") def test_attach_non_utf8_text_as_bytes(self): """ Binary data that can't be decoded as UTF-8 overrides the MIME type instead of decoding the data. """ msg = EmailMessage("subject", "body", "[email protected]", ["[email protected]"]) msg.attach("file.txt", b"\xff") # Invalid UTF-8. filename, content, mimetype = self.get_decoded_attachments(msg)[0] self.assertEqual(filename, "file.txt") # Content should be passed through unmodified. self.assertEqual(content, b"\xff") self.assertEqual(mimetype, "application/octet-stream") def test_attach_mimetext_content_mimetype(self): email_msg = EmailMessage() txt = MIMEText("content") msg = ( "content and mimetype must not be given when a MIMEBase instance " "is provided." ) with self.assertRaisesMessage(ValueError, msg): email_msg.attach(txt, content="content") with self.assertRaisesMessage(ValueError, msg): email_msg.attach(txt, mimetype="text/plain") def test_attach_content_none(self): email_msg = EmailMessage() msg = "content must be provided." with self.assertRaisesMessage(ValueError, msg): email_msg.attach("file.txt", mimetype="application/pdf") def test_dummy_backend(self): """ Make sure that dummy backends returns correct number of sent messages """ connection = dummy.EmailBackend() email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"], headers={"From": "[email protected]"}, ) self.assertEqual(connection.send_messages([email, email, email]), 3) def test_arbitrary_keyword(self): """ Make sure that get_connection() accepts arbitrary keyword that might be used with custom backends. """ c = mail.get_connection(fail_silently=True, foo="bar") self.assertTrue(c.fail_silently) def test_custom_backend(self): """Test custom backend defined in this suite.""" conn = mail.get_connection("mail.custombackend.EmailBackend") self.assertTrue(hasattr(conn, "test_outbox")) email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"], headers={"From": "[email protected]"}, ) conn.send_messages([email]) self.assertEqual(len(conn.test_outbox), 1) def test_backend_arg(self): """Test backend argument of mail.get_connection()""" self.assertIsInstance( mail.get_connection("django.core.mail.backends.smtp.EmailBackend"), smtp.EmailBackend, ) self.assertIsInstance( mail.get_connection("django.core.mail.backends.locmem.EmailBackend"), locmem.EmailBackend, ) self.assertIsInstance( mail.get_connection("django.core.mail.backends.dummy.EmailBackend"), dummy.EmailBackend, ) self.assertIsInstance( mail.get_connection("django.core.mail.backends.console.EmailBackend"), console.EmailBackend, ) with tempfile.TemporaryDirectory() as tmp_dir: self.assertIsInstance( mail.get_connection( "django.core.mail.backends.filebased.EmailBackend", file_path=tmp_dir, ), filebased.EmailBackend, ) if sys.platform == "win32" and not PY311: msg = ( "_getfullpathname: path should be string, bytes or os.PathLike, not " "object" ) else: msg = "expected str, bytes or os.PathLike object, not object" with self.assertRaisesMessage(TypeError, msg): mail.get_connection( "django.core.mail.backends.filebased.EmailBackend", file_path=object() ) self.assertIsInstance(mail.get_connection(), locmem.EmailBackend) @override_settings( EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend", ADMINS=[("nobody", "[email protected]")], MANAGERS=[("nobody", "[email protected]")], ) def test_connection_arg(self): """Test connection argument to send_mail(), et. al.""" mail.outbox = [] # Send using non-default connection connection = mail.get_connection("mail.custombackend.EmailBackend") send_mail( "Subject", "Content", "[email protected]", ["[email protected]"], connection=connection, ) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, "Subject") connection = mail.get_connection("mail.custombackend.EmailBackend") send_mass_mail( [ ("Subject1", "Content1", "[email protected]", ["[email protected]"]), ("Subject2", "Content2", "[email protected]", ["[email protected]"]), ], connection=connection, ) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 2) self.assertEqual(connection.test_outbox[0].subject, "Subject1") self.assertEqual(connection.test_outbox[1].subject, "Subject2") connection = mail.get_connection("mail.custombackend.EmailBackend") mail_admins("Admin message", "Content", connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, "[Django] Admin message") connection = mail.get_connection("mail.custombackend.EmailBackend") mail_managers("Manager message", "Content", connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, "[Django] Manager message") def test_dont_mangle_from_in_body(self): # Regression for #13433 - Make sure that EmailMessage doesn't mangle # 'From ' in message body. email = EmailMessage( "Subject", "From the future", "[email protected]", ["[email protected]"], headers={"From": "[email protected]"}, ) self.assertNotIn(b">From the future", email.message().as_bytes()) def test_dont_base64_encode(self): # Ticket #3472 # Shouldn't use Base64 encoding at all msg = EmailMessage( "Subject", "UTF-8 encoded body", "[email protected]", ["[email protected]"], headers={"From": "[email protected]"}, ) self.assertIn(b"Content-Transfer-Encoding: 7bit", msg.message().as_bytes()) # Ticket #11212 # Shouldn't use quoted printable, should detect it can represent # content with 7 bit data. msg = EmailMessage( "Subject", "Body with only ASCII characters.", "[email protected]", ["[email protected]"], headers={"From": "[email protected]"}, ) s = msg.message().as_bytes() self.assertIn(b"Content-Transfer-Encoding: 7bit", s) # Shouldn't use quoted printable, should detect it can represent # content with 8 bit data. msg = EmailMessage( "Subject", "Body with latin characters: àáä.", "[email protected]", ["[email protected]"], headers={"From": "[email protected]"}, ) s = msg.message().as_bytes() self.assertIn(b"Content-Transfer-Encoding: 8bit", s) s = msg.message().as_string() self.assertIn("Content-Transfer-Encoding: 8bit", s) msg = EmailMessage( "Subject", "Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.", "[email protected]", ["[email protected]"], headers={"From": "[email protected]"}, ) s = msg.message().as_bytes() self.assertIn(b"Content-Transfer-Encoding: 8bit", s) s = msg.message().as_string() self.assertIn("Content-Transfer-Encoding: 8bit", s) def test_dont_base64_encode_message_rfc822(self): # Ticket #18967 # Shouldn't use base64 encoding for a child EmailMessage attachment. # Create a child message first child_msg = EmailMessage( "Child Subject", "Some body of child message", "[email protected]", ["[email protected]"], headers={"From": "[email protected]"}, ) child_s = child_msg.message().as_string() # Now create a parent parent_msg = EmailMessage( "Parent Subject", "Some parent body", "[email protected]", ["[email protected]"], headers={"From": "[email protected]"}, ) # Attach to parent as a string parent_msg.attach(content=child_s, mimetype="message/rfc822") parent_s = parent_msg.message().as_string() # The child message header is not base64 encoded self.assertIn("Child Subject", parent_s) # Feature test: try attaching email.Message object directly to the mail. parent_msg = EmailMessage( "Parent Subject", "Some parent body", "[email protected]", ["[email protected]"], headers={"From": "[email protected]"}, ) parent_msg.attach(content=child_msg.message(), mimetype="message/rfc822") parent_s = parent_msg.message().as_string() # The child message header is not base64 encoded self.assertIn("Child Subject", parent_s) # Feature test: try attaching Django's EmailMessage object directly to the mail. parent_msg = EmailMessage( "Parent Subject", "Some parent body", "[email protected]", ["[email protected]"], headers={"From": "[email protected]"}, ) parent_msg.attach(content=child_msg, mimetype="message/rfc822") parent_s = parent_msg.message().as_string() # The child message header is not base64 encoded self.assertIn("Child Subject", parent_s) def test_custom_utf8_encoding(self): """A UTF-8 charset with a custom body encoding is respected.""" body = "Body with latin characters: àáä." msg = EmailMessage("Subject", body, "[email protected]", ["[email protected]"]) encoding = charset.Charset("utf-8") encoding.body_encoding = charset.QP msg.encoding = encoding message = msg.message() self.assertMessageHasHeaders( message, { ("MIME-Version", "1.0"), ("Content-Type", 'text/plain; charset="utf-8"'), ("Content-Transfer-Encoding", "quoted-printable"), }, ) self.assertEqual(message.get_payload(), encoding.body_encode(body)) def test_sanitize_address(self): """Email addresses are properly sanitized.""" for email_address, encoding, expected_result in ( # ASCII addresses. ("[email protected]", "ascii", "[email protected]"), ("[email protected]", "utf-8", "[email protected]"), (("A name", "[email protected]"), "ascii", "A name <[email protected]>"), ( ("A name", "[email protected]"), "utf-8", "A name <[email protected]>", ), ("localpartonly", "ascii", "localpartonly"), # ASCII addresses with display names. ("A name <[email protected]>", "ascii", "A name <[email protected]>"), ("A name <[email protected]>", "utf-8", "A name <[email protected]>"), ('"A name" <[email protected]>', "ascii", "A name <[email protected]>"), ('"A name" <[email protected]>', "utf-8", "A name <[email protected]>"), # Unicode addresses (supported per RFC-6532). ("tó@example.com", "utf-8", "[email protected]"), ("to@éxample.com", "utf-8", "[email protected]"), ( ("Tó Example", "tó@example.com"), "utf-8", "=?utf-8?q?T=C3=B3_Example?= <[email protected]>", ), # Unicode addresses with display names. ( "Tó Example <tó@example.com>", "utf-8", "=?utf-8?q?T=C3=B3_Example?= <[email protected]>", ), ( "To Example <to@éxample.com>", "ascii", "To Example <[email protected]>", ), ( "To Example <to@éxample.com>", "utf-8", "To Example <[email protected]>", ), # Addresses with two @ signs. ('"[email protected]"@example.com', "utf-8", r'"[email protected]"@example.com'), ( '"[email protected]" <[email protected]>', "utf-8", '"[email protected]" <[email protected]>', ), ( ("To Example", "[email protected]@example.com"), "utf-8", 'To Example <"[email protected]"@example.com>', ), # Addresses with long unicode display names. ( "Tó Example very long" * 4 + " <[email protected]>", "utf-8", "=?utf-8?q?T=C3=B3_Example_very_longT=C3=B3_Example_very_longT" "=C3=B3_Example_?=\n" " =?utf-8?q?very_longT=C3=B3_Example_very_long?= " "<[email protected]>", ), ( ("Tó Example very long" * 4, "[email protected]"), "utf-8", "=?utf-8?q?T=C3=B3_Example_very_longT=C3=B3_Example_very_longT" "=C3=B3_Example_?=\n" " =?utf-8?q?very_longT=C3=B3_Example_very_long?= " "<[email protected]>", ), # Address with long display name and unicode domain. ( ("To Example very long" * 4, "to@exampl€.com"), "utf-8", "To Example very longTo Example very longTo Example very longT" "o Example very\n" " long <[email protected]>", ), ): with self.subTest(email_address=email_address, encoding=encoding): self.assertEqual( sanitize_address(email_address, encoding), expected_result ) def test_sanitize_address_invalid(self): for email_address in ( # Invalid address with two @ signs. "[email protected]@example.com", # Invalid address without the quotes. "[email protected] <[email protected]>", # Other invalid addresses. "@", "to@", "@example.com", ("", ""), ): with self.subTest(email_address=email_address): with self.assertRaisesMessage(ValueError, "Invalid address"): sanitize_address(email_address, encoding="utf-8") def test_sanitize_address_header_injection(self): msg = "Invalid address; address parts cannot contain newlines." tests = [ "Name\nInjection <[email protected]>", ("Name\nInjection", "[email protected]"), "Name <to\[email protected]>", ("Name", "to\[email protected]"), ] for email_address in tests: with self.subTest(email_address=email_address): with self.assertRaisesMessage(ValueError, msg): sanitize_address(email_address, encoding="utf-8") def test_email_multi_alternatives_content_mimetype_none(self): email_msg = EmailMultiAlternatives() msg = "Both content and mimetype must be provided." with self.assertRaisesMessage(ValueError, msg): email_msg.attach_alternative(None, "text/html") with self.assertRaisesMessage(ValueError, msg): email_msg.attach_alternative("<p>content</p>", None) @requires_tz_support class MailTimeZoneTests(SimpleTestCase): @override_settings( EMAIL_USE_LOCALTIME=False, USE_TZ=True, TIME_ZONE="Africa/Algiers" ) def test_date_header_utc(self): """ EMAIL_USE_LOCALTIME=False creates a datetime in UTC. """ email = EmailMessage( "Subject", "Body", "[email protected]", ["[email protected]"] ) self.assertTrue(email.message()["Date"].endswith("-0000")) @override_settings( EMAIL_USE_LOCALTIME=True, USE_TZ=True, TIME_ZONE="Africa/Algiers" ) def test_date_header_localtime(self): """ EMAIL_USE_LOCALTIME=True creates a datetime in the local time zone. """ email = EmailMessage( "Subject", "Body", "[email protected]", ["[email protected]"] ) self.assertTrue( email.message()["Date"].endswith("+0100") ) # Africa/Algiers is UTC+1 class PythonGlobalState(SimpleTestCase): """ Tests for #12422 -- Django smarts (#2472/#11212) with charset of utf-8 text parts shouldn't pollute global email Python package charset registry when django.mail.message is imported. """ def test_utf8(self): txt = MIMEText("UTF-8 encoded body", "plain", "utf-8") self.assertIn("Content-Transfer-Encoding: base64", txt.as_string()) def test_7bit(self): txt = MIMEText("Body with only ASCII characters.", "plain", "utf-8") self.assertIn("Content-Transfer-Encoding: base64", txt.as_string()) def test_8bit_latin(self): txt = MIMEText("Body with latin characters: àáä.", "plain", "utf-8") self.assertIn("Content-Transfer-Encoding: base64", txt.as_string()) def test_8bit_non_latin(self): txt = MIMEText( "Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.", "plain", "utf-8", ) self.assertIn("Content-Transfer-Encoding: base64", txt.as_string()) class BaseEmailBackendTests(HeadersCheckMixin): email_backend = None def setUp(self): self.settings_override = override_settings(EMAIL_BACKEND=self.email_backend) self.settings_override.enable() def tearDown(self): self.settings_override.disable() def assertStartsWith(self, first, second): if not first.startswith(second): self.longMessage = True self.assertEqual( first[: len(second)], second, "First string doesn't start with the second.", ) def get_mailbox_content(self): raise NotImplementedError( "subclasses of BaseEmailBackendTests must provide a get_mailbox_content() " "method" ) def flush_mailbox(self): raise NotImplementedError( "subclasses of BaseEmailBackendTests may require a flush_mailbox() method" ) def get_the_message(self): mailbox = self.get_mailbox_content() self.assertEqual( len(mailbox), 1, "Expected exactly one message, got %d.\n%r" % (len(mailbox), [m.as_string() for m in mailbox]), ) return mailbox[0] def test_send(self): email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"] ) num_sent = mail.get_connection().send_messages([email]) self.assertEqual(num_sent, 1) message = self.get_the_message() self.assertEqual(message["subject"], "Subject") self.assertEqual(message.get_payload(), "Content") self.assertEqual(message["from"], "[email protected]") self.assertEqual(message.get_all("to"), ["[email protected]"]) def test_send_unicode(self): email = EmailMessage( "Chère maman", "Je t'aime très fort", "[email protected]", ["[email protected]"] ) num_sent = mail.get_connection().send_messages([email]) self.assertEqual(num_sent, 1) message = self.get_the_message() self.assertEqual(message["subject"], "=?utf-8?q?Ch=C3=A8re_maman?=") self.assertEqual( message.get_payload(decode=True).decode(), "Je t'aime très fort" ) def test_send_long_lines(self): """ Email line length is limited to 998 chars by the RFC 5322 Section 2.1.1. Message body containing longer lines are converted to Quoted-Printable to avoid having to insert newlines, which could be hairy to do properly. """ # Unencoded body length is < 998 (840) but > 998 when utf-8 encoded. email = EmailMessage( "Subject", "В южных морях " * 60, "[email protected]", ["[email protected]"] ) email.send() message = self.get_the_message() self.assertMessageHasHeaders( message, { ("MIME-Version", "1.0"), ("Content-Type", 'text/plain; charset="utf-8"'), ("Content-Transfer-Encoding", "quoted-printable"), }, ) def test_send_many(self): email1 = EmailMessage( "Subject", "Content1", "[email protected]", ["[email protected]"] ) email2 = EmailMessage( "Subject", "Content2", "[email protected]", ["[email protected]"] ) # send_messages() may take a list or an iterator. emails_lists = ([email1, email2], iter((email1, email2))) for emails_list in emails_lists: num_sent = mail.get_connection().send_messages(emails_list) self.assertEqual(num_sent, 2) messages = self.get_mailbox_content() self.assertEqual(len(messages), 2) self.assertEqual(messages[0].get_payload(), "Content1") self.assertEqual(messages[1].get_payload(), "Content2") self.flush_mailbox() def test_send_verbose_name(self): email = EmailMessage( "Subject", "Content", '"Firstname Sürname" <[email protected]>', ["[email protected]"], ) email.send() message = self.get_the_message() self.assertEqual(message["subject"], "Subject") self.assertEqual(message.get_payload(), "Content") self.assertEqual( message["from"], "=?utf-8?q?Firstname_S=C3=BCrname?= <[email protected]>" ) def test_plaintext_send_mail(self): """ Test send_mail without the html_message regression test for adding html_message parameter to send_mail() """ send_mail("Subject", "Content", "[email protected]", ["[email protected]"]) message = self.get_the_message() self.assertEqual(message.get("subject"), "Subject") self.assertEqual(message.get_all("to"), ["[email protected]"]) self.assertFalse(message.is_multipart()) self.assertEqual(message.get_payload(), "Content") self.assertEqual(message.get_content_type(), "text/plain") def test_html_send_mail(self): """Test html_message argument to send_mail""" send_mail( "Subject", "Content", "[email protected]", ["[email protected]"], html_message="HTML Content", ) message = self.get_the_message() self.assertEqual(message.get("subject"), "Subject") self.assertEqual(message.get_all("to"), ["[email protected]"]) self.assertTrue(message.is_multipart()) self.assertEqual(len(message.get_payload()), 2) self.assertEqual(message.get_payload(0).get_payload(), "Content") self.assertEqual(message.get_payload(0).get_content_type(), "text/plain") self.assertEqual(message.get_payload(1).get_payload(), "HTML Content") self.assertEqual(message.get_payload(1).get_content_type(), "text/html") @override_settings(MANAGERS=[("nobody", "[email protected]")]) def test_html_mail_managers(self): """Test html_message argument to mail_managers""" mail_managers("Subject", "Content", html_message="HTML Content") message = self.get_the_message() self.assertEqual(message.get("subject"), "[Django] Subject") self.assertEqual(message.get_all("to"), ["[email protected]"]) self.assertTrue(message.is_multipart()) self.assertEqual(len(message.get_payload()), 2) self.assertEqual(message.get_payload(0).get_payload(), "Content") self.assertEqual(message.get_payload(0).get_content_type(), "text/plain") self.assertEqual(message.get_payload(1).get_payload(), "HTML Content") self.assertEqual(message.get_payload(1).get_content_type(), "text/html") @override_settings(ADMINS=[("nobody", "[email protected]")]) def test_html_mail_admins(self): """Test html_message argument to mail_admins""" mail_admins("Subject", "Content", html_message="HTML Content") message = self.get_the_message() self.assertEqual(message.get("subject"), "[Django] Subject") self.assertEqual(message.get_all("to"), ["[email protected]"]) self.assertTrue(message.is_multipart()) self.assertEqual(len(message.get_payload()), 2) self.assertEqual(message.get_payload(0).get_payload(), "Content") self.assertEqual(message.get_payload(0).get_content_type(), "text/plain") self.assertEqual(message.get_payload(1).get_payload(), "HTML Content") self.assertEqual(message.get_payload(1).get_content_type(), "text/html") @override_settings( ADMINS=[("nobody", "[email protected]")], MANAGERS=[("nobody", "[email protected]")], ) def test_manager_and_admin_mail_prefix(self): """ String prefix + lazy translated subject = bad output Regression for #13494 """ mail_managers(gettext_lazy("Subject"), "Content") message = self.get_the_message() self.assertEqual(message.get("subject"), "[Django] Subject") self.flush_mailbox() mail_admins(gettext_lazy("Subject"), "Content") message = self.get_the_message() self.assertEqual(message.get("subject"), "[Django] Subject") @override_settings(ADMINS=[], MANAGERS=[]) def test_empty_admins(self): """ mail_admins/mail_managers doesn't connect to the mail server if there are no recipients (#9383) """ mail_admins("hi", "there") self.assertEqual(self.get_mailbox_content(), []) mail_managers("hi", "there") self.assertEqual(self.get_mailbox_content(), []) def test_wrong_admins_managers(self): tests = ( "[email protected]", ("[email protected]",), ["[email protected]", "[email protected]"], ("[email protected]", "[email protected]"), ) for setting, mail_func in ( ("ADMINS", mail_admins), ("MANAGERS", mail_managers), ): msg = "The %s setting must be a list of 2-tuples." % setting for value in tests: with self.subTest(setting=setting, value=value), self.settings( **{setting: value} ): with self.assertRaisesMessage(ValueError, msg): mail_func("subject", "content") def test_message_cc_header(self): """ Regression test for #7722 """ email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"], cc=["[email protected]"], ) mail.get_connection().send_messages([email]) message = self.get_the_message() self.assertMessageHasHeaders( message, { ("MIME-Version", "1.0"), ("Content-Type", 'text/plain; charset="utf-8"'), ("Content-Transfer-Encoding", "7bit"), ("Subject", "Subject"), ("From", "[email protected]"), ("To", "[email protected]"), ("Cc", "[email protected]"), }, ) self.assertIn("\nDate: ", message.as_string()) def test_idn_send(self): """ Regression test for #14301 """ self.assertTrue(send_mail("Subject", "Content", "from@öäü.com", ["to@öäü.com"])) message = self.get_the_message() self.assertEqual(message.get("subject"), "Subject") self.assertEqual(message.get("from"), "[email protected]") self.assertEqual(message.get("to"), "[email protected]") self.flush_mailbox() m = EmailMessage( "Subject", "Content", "from@öäü.com", ["to@öäü.com"], cc=["cc@öäü.com"] ) m.send() message = self.get_the_message() self.assertEqual(message.get("subject"), "Subject") self.assertEqual(message.get("from"), "[email protected]") self.assertEqual(message.get("to"), "[email protected]") self.assertEqual(message.get("cc"), "[email protected]") def test_recipient_without_domain(self): """ Regression test for #15042 """ self.assertTrue(send_mail("Subject", "Content", "tester", ["django"])) message = self.get_the_message() self.assertEqual(message.get("subject"), "Subject") self.assertEqual(message.get("from"), "tester") self.assertEqual(message.get("to"), "django") def test_lazy_addresses(self): """ Email sending should support lazy email addresses (#24416). """ _ = gettext_lazy self.assertTrue(send_mail("Subject", "Content", _("tester"), [_("django")])) message = self.get_the_message() self.assertEqual(message.get("from"), "tester") self.assertEqual(message.get("to"), "django") self.flush_mailbox() m = EmailMessage( "Subject", "Content", _("tester"), [_("to1"), _("to2")], cc=[_("cc1"), _("cc2")], bcc=[_("bcc")], reply_to=[_("reply")], ) self.assertEqual(m.recipients(), ["to1", "to2", "cc1", "cc2", "bcc"]) m.send() message = self.get_the_message() self.assertEqual(message.get("from"), "tester") self.assertEqual(message.get("to"), "to1, to2") self.assertEqual(message.get("cc"), "cc1, cc2") self.assertEqual(message.get("Reply-To"), "reply") def test_close_connection(self): """ Connection can be closed (even when not explicitly opened) """ conn = mail.get_connection(username="", password="") conn.close() def test_use_as_contextmanager(self): """ The connection can be used as a contextmanager. """ opened = [False] closed = [False] conn = mail.get_connection(username="", password="") def open(): opened[0] = True conn.open = open def close(): closed[0] = True conn.close = close with conn as same_conn: self.assertTrue(opened[0]) self.assertIs(same_conn, conn) self.assertFalse(closed[0]) self.assertTrue(closed[0]) class LocmemBackendTests(BaseEmailBackendTests, SimpleTestCase): email_backend = "django.core.mail.backends.locmem.EmailBackend" def get_mailbox_content(self): return [m.message() for m in mail.outbox] def flush_mailbox(self): mail.outbox = [] def tearDown(self): super().tearDown() mail.outbox = [] def test_locmem_shared_messages(self): """ Make sure that the locmen backend populates the outbox. """ connection = locmem.EmailBackend() connection2 = locmem.EmailBackend() email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"], headers={"From": "[email protected]"}, ) connection.send_messages([email]) connection2.send_messages([email]) self.assertEqual(len(mail.outbox), 2) def test_validate_multiline_headers(self): # Ticket #18861 - Validate emails when using the locmem backend with self.assertRaises(BadHeaderError): send_mail( "Subject\nMultiline", "Content", "[email protected]", ["[email protected]"] ) class FileBackendTests(BaseEmailBackendTests, SimpleTestCase): email_backend = "django.core.mail.backends.filebased.EmailBackend" def setUp(self): super().setUp() self.tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, self.tmp_dir) self._settings_override = override_settings(EMAIL_FILE_PATH=self.tmp_dir) self._settings_override.enable() def tearDown(self): self._settings_override.disable() super().tearDown() def mkdtemp(self): return tempfile.mkdtemp() def flush_mailbox(self): for filename in os.listdir(self.tmp_dir): os.unlink(os.path.join(self.tmp_dir, filename)) def get_mailbox_content(self): messages = [] for filename in os.listdir(self.tmp_dir): with open(os.path.join(self.tmp_dir, filename), "rb") as fp: session = fp.read().split(b"\n" + (b"-" * 79) + b"\n") messages.extend(message_from_bytes(m) for m in session if m) return messages def test_file_sessions(self): """Make sure opening a connection creates a new file""" msg = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"], headers={"From": "[email protected]"}, ) connection = mail.get_connection() connection.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 1) with open(os.path.join(self.tmp_dir, os.listdir(self.tmp_dir)[0]), "rb") as fp: message = message_from_binary_file(fp) self.assertEqual(message.get_content_type(), "text/plain") self.assertEqual(message.get("subject"), "Subject") self.assertEqual(message.get("from"), "[email protected]") self.assertEqual(message.get("to"), "[email protected]") connection2 = mail.get_connection() connection2.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 2) connection.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 2) msg.connection = mail.get_connection() self.assertTrue(connection.open()) msg.send() self.assertEqual(len(os.listdir(self.tmp_dir)), 3) msg.send() self.assertEqual(len(os.listdir(self.tmp_dir)), 3) connection.close() class FileBackendPathLibTests(FileBackendTests): def mkdtemp(self): tmp_dir = super().mkdtemp() return Path(tmp_dir) class ConsoleBackendTests(BaseEmailBackendTests, SimpleTestCase): email_backend = "django.core.mail.backends.console.EmailBackend" def setUp(self): super().setUp() self.__stdout = sys.stdout self.stream = sys.stdout = StringIO() def tearDown(self): del self.stream sys.stdout = self.__stdout del self.__stdout super().tearDown() def flush_mailbox(self): self.stream = sys.stdout = StringIO() def get_mailbox_content(self): messages = self.stream.getvalue().split("\n" + ("-" * 79) + "\n") return [message_from_bytes(m.encode()) for m in messages if m] def test_console_stream_kwarg(self): """ The console backend can be pointed at an arbitrary stream. """ s = StringIO() connection = mail.get_connection( "django.core.mail.backends.console.EmailBackend", stream=s ) send_mail( "Subject", "Content", "[email protected]", ["[email protected]"], connection=connection, ) message = s.getvalue().split("\n" + ("-" * 79) + "\n")[0].encode() self.assertMessageHasHeaders( message, { ("MIME-Version", "1.0"), ("Content-Type", 'text/plain; charset="utf-8"'), ("Content-Transfer-Encoding", "7bit"), ("Subject", "Subject"), ("From", "[email protected]"), ("To", "[email protected]"), }, ) self.assertIn(b"\nDate: ", message) class SMTPHandler: def __init__(self, *args, **kwargs): self.mailbox = [] async def handle_DATA(self, server, session, envelope): data = envelope.content mail_from = envelope.mail_from message = message_from_bytes(data.rstrip()) message_addr = parseaddr(message.get("from"))[1] if mail_from != message_addr: # According to the spec, mail_from does not necessarily match the # From header - this is the case where the local part isn't # encoded, so try to correct that. lp, domain = mail_from.split("@", 1) lp = Header(lp, "utf-8").encode() mail_from = "@".join([lp, domain]) if mail_from != message_addr: return f"553 '{mail_from}' != '{message_addr}'" self.mailbox.append(message) return "250 OK" def flush_mailbox(self): self.mailbox[:] = [] @skipUnless(HAS_AIOSMTPD, "No aiosmtpd library detected.") class SMTPBackendTestsBase(SimpleTestCase): @classmethod def setUpClass(cls): super().setUpClass() # Find a free port. with socket.socket() as s: s.bind(("127.0.0.1", 0)) port = s.getsockname()[1] cls.smtp_handler = SMTPHandler() cls.smtp_controller = Controller( cls.smtp_handler, hostname="127.0.0.1", port=port, ) cls._settings_override = override_settings( EMAIL_HOST=cls.smtp_controller.hostname, EMAIL_PORT=cls.smtp_controller.port, ) cls._settings_override.enable() cls.addClassCleanup(cls._settings_override.disable) cls.smtp_controller.start() cls.addClassCleanup(cls.stop_smtp) @classmethod def stop_smtp(cls): cls.smtp_controller.stop() @skipUnless(HAS_AIOSMTPD, "No aiosmtpd library detected.") class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase): email_backend = "django.core.mail.backends.smtp.EmailBackend" def setUp(self): super().setUp() self.smtp_handler.flush_mailbox() def tearDown(self): self.smtp_handler.flush_mailbox() super().tearDown() def flush_mailbox(self): self.smtp_handler.flush_mailbox() def get_mailbox_content(self): return self.smtp_handler.mailbox @override_settings( EMAIL_HOST_USER="not empty username", EMAIL_HOST_PASSWORD="not empty password", ) def test_email_authentication_use_settings(self): backend = smtp.EmailBackend() self.assertEqual(backend.username, "not empty username") self.assertEqual(backend.password, "not empty password") @override_settings( EMAIL_HOST_USER="not empty username", EMAIL_HOST_PASSWORD="not empty password", ) def test_email_authentication_override_settings(self): backend = smtp.EmailBackend(username="username", password="password") self.assertEqual(backend.username, "username") self.assertEqual(backend.password, "password") @override_settings( EMAIL_HOST_USER="not empty username", EMAIL_HOST_PASSWORD="not empty password", ) def test_email_disabled_authentication(self): backend = smtp.EmailBackend(username="", password="") self.assertEqual(backend.username, "") self.assertEqual(backend.password, "") def test_auth_attempted(self): """ Opening the backend with non empty username/password tries to authenticate against the SMTP server. """ backend = smtp.EmailBackend( username="not empty username", password="not empty password" ) with self.assertRaisesMessage( SMTPException, "SMTP AUTH extension not supported by server." ): with backend: pass def test_server_open(self): """ open() returns whether it opened a connection. """ backend = smtp.EmailBackend(username="", password="") self.assertIsNone(backend.connection) opened = backend.open() backend.close() self.assertIs(opened, True) def test_reopen_connection(self): backend = smtp.EmailBackend() # Simulate an already open connection. backend.connection = mock.Mock(spec=object()) self.assertIs(backend.open(), False) @override_settings(EMAIL_USE_TLS=True) def test_email_tls_use_settings(self): backend = smtp.EmailBackend() self.assertTrue(backend.use_tls) @override_settings(EMAIL_USE_TLS=True) def test_email_tls_override_settings(self): backend = smtp.EmailBackend(use_tls=False) self.assertFalse(backend.use_tls) def test_email_tls_default_disabled(self): backend = smtp.EmailBackend() self.assertFalse(backend.use_tls) def test_ssl_tls_mutually_exclusive(self): msg = ( "EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set " "one of those settings to True." ) with self.assertRaisesMessage(ValueError, msg): smtp.EmailBackend(use_ssl=True, use_tls=True) @override_settings(EMAIL_USE_SSL=True) def test_email_ssl_use_settings(self): backend = smtp.EmailBackend() self.assertTrue(backend.use_ssl) @override_settings(EMAIL_USE_SSL=True) def test_email_ssl_override_settings(self): backend = smtp.EmailBackend(use_ssl=False) self.assertFalse(backend.use_ssl) def test_email_ssl_default_disabled(self): backend = smtp.EmailBackend() self.assertFalse(backend.use_ssl) @override_settings(EMAIL_SSL_CERTFILE="foo") def test_email_ssl_certfile_use_settings(self): backend = smtp.EmailBackend() self.assertEqual(backend.ssl_certfile, "foo") @override_settings(EMAIL_SSL_CERTFILE="foo") def test_email_ssl_certfile_override_settings(self): backend = smtp.EmailBackend(ssl_certfile="bar") self.assertEqual(backend.ssl_certfile, "bar") def test_email_ssl_certfile_default_disabled(self): backend = smtp.EmailBackend() self.assertIsNone(backend.ssl_certfile) @override_settings(EMAIL_SSL_KEYFILE="foo") def test_email_ssl_keyfile_use_settings(self): backend = smtp.EmailBackend() self.assertEqual(backend.ssl_keyfile, "foo") @override_settings(EMAIL_SSL_KEYFILE="foo") def test_email_ssl_keyfile_override_settings(self): backend = smtp.EmailBackend(ssl_keyfile="bar") self.assertEqual(backend.ssl_keyfile, "bar") def test_email_ssl_keyfile_default_disabled(self): backend = smtp.EmailBackend() self.assertIsNone(backend.ssl_keyfile) @override_settings(EMAIL_USE_TLS=True) def test_email_tls_attempts_starttls(self): backend = smtp.EmailBackend() self.assertTrue(backend.use_tls) with self.assertRaisesMessage( SMTPException, "STARTTLS extension not supported by server." ): with backend: pass @override_settings(EMAIL_USE_SSL=True) def test_email_ssl_attempts_ssl_connection(self): backend = smtp.EmailBackend() self.assertTrue(backend.use_ssl) with self.assertRaises(SSLError): with backend: pass def test_connection_timeout_default(self): """The connection's timeout value is None by default.""" connection = mail.get_connection("django.core.mail.backends.smtp.EmailBackend") self.assertIsNone(connection.timeout) def test_connection_timeout_custom(self): """The timeout parameter can be customized.""" class MyEmailBackend(smtp.EmailBackend): def __init__(self, *args, **kwargs): kwargs.setdefault("timeout", 42) super().__init__(*args, **kwargs) myemailbackend = MyEmailBackend() myemailbackend.open() self.assertEqual(myemailbackend.timeout, 42) self.assertEqual(myemailbackend.connection.timeout, 42) myemailbackend.close() @override_settings(EMAIL_TIMEOUT=10) def test_email_timeout_override_settings(self): backend = smtp.EmailBackend() self.assertEqual(backend.timeout, 10) def test_email_msg_uses_crlf(self): """#23063 -- RFC-compliant messages are sent over SMTP.""" send = SMTP.send try: smtp_messages = [] def mock_send(self, s): smtp_messages.append(s) return send(self, s) SMTP.send = mock_send email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"] ) mail.get_connection().send_messages([email]) # Find the actual message msg = None for i, m in enumerate(smtp_messages): if m[:4] == "data": msg = smtp_messages[i + 1] break self.assertTrue(msg) msg = msg.decode() # The message only contains CRLF and not combinations of CRLF, LF, and CR. msg = msg.replace("\r\n", "") self.assertNotIn("\r", msg) self.assertNotIn("\n", msg) finally: SMTP.send = send def test_send_messages_after_open_failed(self): """ send_messages() shouldn't try to send messages if open() raises an exception after initializing the connection. """ backend = smtp.EmailBackend() # Simulate connection initialization success and a subsequent # connection exception. backend.connection = mock.Mock(spec=object()) backend.open = lambda: None email = EmailMessage( "Subject", "Content", "[email protected]", ["[email protected]"] ) self.assertEqual(backend.send_messages([email]), 0) def test_send_messages_empty_list(self): backend = smtp.EmailBackend() backend.connection = mock.Mock(spec=object()) self.assertEqual(backend.send_messages([]), 0) def test_send_messages_zero_sent(self): """A message isn't sent if it doesn't have any recipients.""" backend = smtp.EmailBackend() backend.connection = mock.Mock(spec=object()) email = EmailMessage("Subject", "Content", "[email protected]", to=[]) sent = backend.send_messages([email]) self.assertEqual(sent, 0) @skipUnless(HAS_AIOSMTPD, "No aiosmtpd library detected.") class SMTPBackendStoppedServerTests(SMTPBackendTestsBase): @classmethod def setUpClass(cls): super().setUpClass() cls.backend = smtp.EmailBackend(username="", password="") cls.smtp_controller.stop() @classmethod def stop_smtp(cls): # SMTP controller is stopped in setUpClass(). pass def test_server_stopped(self): """ Closing the backend while the SMTP server is stopped doesn't raise an exception. """ self.backend.close() def test_fail_silently_on_connection_error(self): """ A socket connection error is silenced with fail_silently=True. """ with self.assertRaises(ConnectionError): self.backend.open() self.backend.fail_silently = True self.backend.open()
2d25b0ea8deb70f598046df97186afea32d76b97942be2da1f2733327137401d
import os import re import shutil import tempfile import time import warnings from io import StringIO from pathlib import Path from unittest import mock, skipIf, skipUnless from admin_scripts.tests import AdminScriptTestCase from django.core import management from django.core.management import execute_from_command_line from django.core.management.base import CommandError from django.core.management.commands.makemessages import Command as MakeMessagesCommand from django.core.management.commands.makemessages import write_pot_file from django.core.management.utils import find_command from django.test import SimpleTestCase, override_settings from django.test.utils import captured_stderr, captured_stdout from django.utils._os import symlinks_supported from django.utils.translation import TranslatorCommentWarning from .utils import POFileAssertionMixin, RunInTmpDirMixin, copytree LOCALE = "de" has_xgettext = find_command("xgettext") gettext_version = MakeMessagesCommand().gettext_version if has_xgettext else None requires_gettext_019 = skipIf( has_xgettext and gettext_version < (0, 19), "gettext 0.19 required" ) @skipUnless(has_xgettext, "xgettext is mandatory for extraction tests") class ExtractorTests(POFileAssertionMixin, RunInTmpDirMixin, SimpleTestCase): work_subdir = "commands" PO_FILE = "locale/%s/LC_MESSAGES/django.po" % LOCALE def _run_makemessages(self, **options): out = StringIO() management.call_command( "makemessages", locale=[LOCALE], verbosity=2, stdout=out, **options ) output = out.getvalue() self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() return output, po_contents def assertMsgIdPlural(self, msgid, haystack, use_quotes=True): return self._assertPoKeyword( "msgid_plural", msgid, haystack, use_quotes=use_quotes ) def assertMsgStr(self, msgstr, haystack, use_quotes=True): return self._assertPoKeyword("msgstr", msgstr, haystack, use_quotes=use_quotes) def assertNotMsgId(self, msgid, s, use_quotes=True): if use_quotes: msgid = '"%s"' % msgid msgid = re.escape(msgid) return self.assertTrue(not re.search("^msgid %s" % msgid, s, re.MULTILINE)) def _assertPoLocComment( self, assert_presence, po_filename, line_number, *comment_parts ): with open(po_filename) as fp: po_contents = fp.read() if os.name == "nt": # #: .\path\to\file.html:123 cwd_prefix = "%s%s" % (os.curdir, os.sep) else: # #: path/to/file.html:123 cwd_prefix = "" path = os.path.join(cwd_prefix, *comment_parts) parts = [path] if isinstance(line_number, str): line_number = self._get_token_line_number(path, line_number) if line_number is not None: parts.append(":%d" % line_number) needle = "".join(parts) pattern = re.compile(r"^\#\:.*" + re.escape(needle), re.MULTILINE) if assert_presence: return self.assertRegex( po_contents, pattern, '"%s" not found in final .po file.' % needle ) else: return self.assertNotRegex( po_contents, pattern, '"%s" shouldn\'t be in final .po file.' % needle ) def _get_token_line_number(self, path, token): with open(path) as f: for line, content in enumerate(f, 1): if token in content: return line self.fail( "The token '%s' could not be found in %s, please check the test config" % (token, path) ) def assertLocationCommentPresent(self, po_filename, line_number, *comment_parts): r""" self.assertLocationCommentPresent('django.po', 42, 'dirA', 'dirB', 'foo.py') verifies that the django.po file has a gettext-style location comment of the form `#: dirA/dirB/foo.py:42` (or `#: .\dirA\dirB\foo.py:42` on Windows) None can be passed for the line_number argument to skip checking of the :42 suffix part. A string token can also be passed as line_number, in which case it will be searched in the template, and its line number will be used. A msgid is a suitable candidate. """ return self._assertPoLocComment(True, po_filename, line_number, *comment_parts) def assertLocationCommentNotPresent(self, po_filename, line_number, *comment_parts): """Check the opposite of assertLocationComment()""" return self._assertPoLocComment(False, po_filename, line_number, *comment_parts) def assertRecentlyModified(self, path): """ Assert that file was recently modified (modification time was less than 10 seconds ago). """ delta = time.time() - os.stat(path).st_mtime self.assertLess(delta, 10, "%s was recently modified" % path) def assertNotRecentlyModified(self, path): """ Assert that file was not recently modified (modification time was more than 10 seconds ago). """ delta = time.time() - os.stat(path).st_mtime self.assertGreater(delta, 10, "%s wasn't recently modified" % path) class BasicExtractorTests(ExtractorTests): @override_settings(USE_I18N=False) def test_use_i18n_false(self): """ makemessages also runs successfully when USE_I18N is False. """ management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE, encoding="utf-8") as fp: po_contents = fp.read() # Check two random strings self.assertIn("#. Translators: One-line translator comment #1", po_contents) self.assertIn('msgctxt "Special trans context #1"', po_contents) def test_no_option(self): # One of either the --locale, --exclude, or --all options is required. msg = "Type 'manage.py help makemessages' for usage information." with mock.patch( "django.core.management.commands.makemessages.sys.argv", ["manage.py", "makemessages"], ): with self.assertRaisesRegex(CommandError, msg): management.call_command("makemessages") def test_valid_locale(self): out = StringIO() management.call_command("makemessages", locale=["de"], stdout=out, verbosity=1) self.assertNotIn("invalid locale de", out.getvalue()) self.assertIn("processing locale de", out.getvalue()) self.assertIs(Path(self.PO_FILE).exists(), True) def test_valid_locale_with_country(self): out = StringIO() management.call_command( "makemessages", locale=["en_GB"], stdout=out, verbosity=1 ) self.assertNotIn("invalid locale en_GB", out.getvalue()) self.assertIn("processing locale en_GB", out.getvalue()) self.assertIs(Path("locale/en_GB/LC_MESSAGES/django.po").exists(), True) def test_valid_locale_tachelhit_latin_morocco(self): out = StringIO() management.call_command( "makemessages", locale=["shi_Latn_MA"], stdout=out, verbosity=1 ) self.assertNotIn("invalid locale shi_Latn_MA", out.getvalue()) self.assertIn("processing locale shi_Latn_MA", out.getvalue()) self.assertIs(Path("locale/shi_Latn_MA/LC_MESSAGES/django.po").exists(), True) def test_valid_locale_private_subtag(self): out = StringIO() management.call_command( "makemessages", locale=["nl_NL-x-informal"], stdout=out, verbosity=1 ) self.assertNotIn("invalid locale nl_NL-x-informal", out.getvalue()) self.assertIn("processing locale nl_NL-x-informal", out.getvalue()) self.assertIs( Path("locale/nl_NL-x-informal/LC_MESSAGES/django.po").exists(), True ) def test_invalid_locale_uppercase(self): out = StringIO() management.call_command("makemessages", locale=["PL"], stdout=out, verbosity=1) self.assertIn("invalid locale PL, did you mean pl?", out.getvalue()) self.assertNotIn("processing locale pl", out.getvalue()) self.assertIs(Path("locale/pl/LC_MESSAGES/django.po").exists(), False) def test_invalid_locale_hyphen(self): out = StringIO() management.call_command( "makemessages", locale=["pl-PL"], stdout=out, verbosity=1 ) self.assertIn("invalid locale pl-PL, did you mean pl_PL?", out.getvalue()) self.assertNotIn("processing locale pl-PL", out.getvalue()) self.assertIs(Path("locale/pl-PL/LC_MESSAGES/django.po").exists(), False) def test_invalid_locale_lower_country(self): out = StringIO() management.call_command( "makemessages", locale=["pl_pl"], stdout=out, verbosity=1 ) self.assertIn("invalid locale pl_pl, did you mean pl_PL?", out.getvalue()) self.assertNotIn("processing locale pl_pl", out.getvalue()) self.assertIs(Path("locale/pl_pl/LC_MESSAGES/django.po").exists(), False) def test_invalid_locale_private_subtag(self): out = StringIO() management.call_command( "makemessages", locale=["nl-nl-x-informal"], stdout=out, verbosity=1 ) self.assertIn( "invalid locale nl-nl-x-informal, did you mean nl_NL-x-informal?", out.getvalue(), ) self.assertNotIn("processing locale nl-nl-x-informal", out.getvalue()) self.assertIs( Path("locale/nl-nl-x-informal/LC_MESSAGES/django.po").exists(), False ) def test_invalid_locale_plus(self): out = StringIO() management.call_command( "makemessages", locale=["en+GB"], stdout=out, verbosity=1 ) self.assertIn("invalid locale en+GB, did you mean en_GB?", out.getvalue()) self.assertNotIn("processing locale en+GB", out.getvalue()) self.assertIs(Path("locale/en+GB/LC_MESSAGES/django.po").exists(), False) def test_invalid_locale_end_with_underscore(self): out = StringIO() management.call_command("makemessages", locale=["en_"], stdout=out, verbosity=1) self.assertIn("invalid locale en_", out.getvalue()) self.assertNotIn("processing locale en_", out.getvalue()) self.assertIs(Path("locale/en_/LC_MESSAGES/django.po").exists(), False) def test_invalid_locale_start_with_underscore(self): out = StringIO() management.call_command("makemessages", locale=["_en"], stdout=out, verbosity=1) self.assertIn("invalid locale _en", out.getvalue()) self.assertNotIn("processing locale _en", out.getvalue()) self.assertIs(Path("locale/_en/LC_MESSAGES/django.po").exists(), False) def test_comments_extractor(self): management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE, encoding="utf-8") as fp: po_contents = fp.read() self.assertNotIn("This comment should not be extracted", po_contents) # Comments in templates self.assertIn( "#. Translators: This comment should be extracted", po_contents ) self.assertIn( "#. Translators: Django comment block for translators\n#. " "string's meaning unveiled", po_contents, ) self.assertIn("#. Translators: One-line translator comment #1", po_contents) self.assertIn( "#. Translators: Two-line translator comment #1\n#. continued here.", po_contents, ) self.assertIn("#. Translators: One-line translator comment #2", po_contents) self.assertIn( "#. Translators: Two-line translator comment #2\n#. continued here.", po_contents, ) self.assertIn("#. Translators: One-line translator comment #3", po_contents) self.assertIn( "#. Translators: Two-line translator comment #3\n#. continued here.", po_contents, ) self.assertIn("#. Translators: One-line translator comment #4", po_contents) self.assertIn( "#. Translators: Two-line translator comment #4\n#. continued here.", po_contents, ) self.assertIn( "#. Translators: One-line translator comment #5 -- with " "non ASCII characters: áéíóúö", po_contents, ) self.assertIn( "#. Translators: Two-line translator comment #5 -- with " "non ASCII characters: áéíóúö\n#. continued here.", po_contents, ) def test_special_char_extracted(self): management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE, encoding="utf-8") as fp: po_contents = fp.read() self.assertMsgId("Non-breaking space\u00a0:", po_contents) def test_blocktranslate_trimmed(self): management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() # should not be trimmed self.assertNotMsgId("Text with a few line breaks.", po_contents) # should be trimmed self.assertMsgId( "Again some text with a few line breaks, this time should be trimmed.", po_contents, ) # #21406 -- Should adjust for eaten line numbers self.assertMsgId("Get my line number", po_contents) self.assertLocationCommentPresent( self.PO_FILE, "Get my line number", "templates", "test.html" ) def test_extraction_error(self): msg = ( "Translation blocks must not include other block tags: blocktranslate " "(file %s, line 3)" % os.path.join("templates", "template_with_error.tpl") ) with self.assertRaisesMessage(SyntaxError, msg): management.call_command( "makemessages", locale=[LOCALE], extensions=["tpl"], verbosity=0 ) # The temporary files were cleaned up. self.assertFalse(os.path.exists("./templates/template_with_error.tpl.py")) self.assertFalse(os.path.exists("./templates/template_0_with_no_error.tpl.py")) def test_unicode_decode_error(self): shutil.copyfile("./not_utf8.sample", "./not_utf8.txt") out = StringIO() management.call_command("makemessages", locale=[LOCALE], stdout=out) self.assertIn( "UnicodeDecodeError: skipped file not_utf8.txt in .", out.getvalue() ) def test_unicode_file_name(self): open(os.path.join(self.test_dir, "vidéo.txt"), "a").close() management.call_command("makemessages", locale=[LOCALE], verbosity=0) def test_extraction_warning(self): """test xgettext warning about multiple bare interpolation placeholders""" shutil.copyfile("./code.sample", "./code_sample.py") out = StringIO() management.call_command("makemessages", locale=[LOCALE], stdout=out) self.assertIn("code_sample.py:4", out.getvalue()) def test_template_message_context_extractor(self): """ Message contexts are correctly extracted for the {% translate %} and {% blocktranslate %} template tags (#14806). """ management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() # {% translate %} self.assertIn('msgctxt "Special trans context #1"', po_contents) self.assertMsgId("Translatable literal #7a", po_contents) self.assertIn('msgctxt "Special trans context #2"', po_contents) self.assertMsgId("Translatable literal #7b", po_contents) self.assertIn('msgctxt "Special trans context #3"', po_contents) self.assertMsgId("Translatable literal #7c", po_contents) # {% translate %} with a filter for ( minor_part ) in "abcdefgh": # Iterate from #7.1a to #7.1h template markers self.assertIn( 'msgctxt "context #7.1{}"'.format(minor_part), po_contents ) self.assertMsgId( "Translatable literal #7.1{}".format(minor_part), po_contents ) # {% blocktranslate %} self.assertIn('msgctxt "Special blocktranslate context #1"', po_contents) self.assertMsgId("Translatable literal #8a", po_contents) self.assertIn('msgctxt "Special blocktranslate context #2"', po_contents) self.assertMsgId("Translatable literal #8b-singular", po_contents) self.assertIn("Translatable literal #8b-plural", po_contents) self.assertIn('msgctxt "Special blocktranslate context #3"', po_contents) self.assertMsgId("Translatable literal #8c-singular", po_contents) self.assertIn("Translatable literal #8c-plural", po_contents) self.assertIn('msgctxt "Special blocktranslate context #4"', po_contents) self.assertMsgId("Translatable literal #8d %(a)s", po_contents) # {% trans %} and {% blocktrans %} self.assertMsgId("trans text", po_contents) self.assertMsgId("blocktrans text", po_contents) def test_context_in_single_quotes(self): management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() # {% translate %} self.assertIn('msgctxt "Context wrapped in double quotes"', po_contents) self.assertIn('msgctxt "Context wrapped in single quotes"', po_contents) # {% blocktranslate %} self.assertIn( 'msgctxt "Special blocktranslate context wrapped in double quotes"', po_contents, ) self.assertIn( 'msgctxt "Special blocktranslate context wrapped in single quotes"', po_contents, ) def test_template_comments(self): """Template comment tags on the same line of other constructs (#19552)""" # Test detection/end user reporting of old, incorrect templates # translator comments syntax with warnings.catch_warnings(record=True) as ws: warnings.simplefilter("always") management.call_command( "makemessages", locale=[LOCALE], extensions=["thtml"], verbosity=0 ) self.assertEqual(len(ws), 3) for w in ws: self.assertTrue(issubclass(w.category, TranslatorCommentWarning)) self.assertRegex( str(ws[0].message), r"The translator-targeted comment 'Translators: ignored i18n " r"comment #1' \(file templates[/\\]comments.thtml, line 4\) " r"was ignored, because it wasn't the last item on the line\.", ) self.assertRegex( str(ws[1].message), r"The translator-targeted comment 'Translators: ignored i18n " r"comment #3' \(file templates[/\\]comments.thtml, line 6\) " r"was ignored, because it wasn't the last item on the line\.", ) self.assertRegex( str(ws[2].message), r"The translator-targeted comment 'Translators: ignored i18n " r"comment #4' \(file templates[/\\]comments.thtml, line 8\) " r"was ignored, because it wasn't the last item on the line\.", ) # Now test .po file contents self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() self.assertMsgId("Translatable literal #9a", po_contents) self.assertNotIn("ignored comment #1", po_contents) self.assertNotIn("Translators: ignored i18n comment #1", po_contents) self.assertMsgId("Translatable literal #9b", po_contents) self.assertNotIn("ignored i18n comment #2", po_contents) self.assertNotIn("ignored comment #2", po_contents) self.assertMsgId("Translatable literal #9c", po_contents) self.assertNotIn("ignored comment #3", po_contents) self.assertNotIn("ignored i18n comment #3", po_contents) self.assertMsgId("Translatable literal #9d", po_contents) self.assertNotIn("ignored comment #4", po_contents) self.assertMsgId("Translatable literal #9e", po_contents) self.assertNotIn("ignored comment #5", po_contents) self.assertNotIn("ignored i18n comment #4", po_contents) self.assertMsgId("Translatable literal #9f", po_contents) self.assertIn("#. Translators: valid i18n comment #5", po_contents) self.assertMsgId("Translatable literal #9g", po_contents) self.assertIn("#. Translators: valid i18n comment #6", po_contents) self.assertMsgId("Translatable literal #9h", po_contents) self.assertIn("#. Translators: valid i18n comment #7", po_contents) self.assertMsgId("Translatable literal #9i", po_contents) self.assertRegex(po_contents, r"#\..+Translators: valid i18n comment #8") self.assertRegex(po_contents, r"#\..+Translators: valid i18n comment #9") self.assertMsgId("Translatable literal #9j", po_contents) def test_makemessages_find_files(self): """ find_files only discover files having the proper extensions. """ cmd = MakeMessagesCommand() cmd.ignore_patterns = ["CVS", ".*", "*~", "*.pyc"] cmd.symlinks = False cmd.domain = "django" cmd.extensions = [".html", ".txt", ".py"] cmd.verbosity = 0 cmd.locale_paths = [] cmd.default_locale_path = os.path.join(self.test_dir, "locale") found_files = cmd.find_files(self.test_dir) self.assertGreater(len(found_files), 1) found_exts = {os.path.splitext(tfile.file)[1] for tfile in found_files} self.assertEqual(found_exts.difference({".py", ".html", ".txt"}), set()) cmd.extensions = [".js"] cmd.domain = "djangojs" found_files = cmd.find_files(self.test_dir) self.assertGreater(len(found_files), 1) found_exts = {os.path.splitext(tfile.file)[1] for tfile in found_files} self.assertEqual(found_exts.difference({".js"}), set()) @mock.patch("django.core.management.commands.makemessages.popen_wrapper") def test_makemessages_gettext_version(self, mocked_popen_wrapper): # "Normal" output: mocked_popen_wrapper.return_value = ( "xgettext (GNU gettext-tools) 0.18.1\n" "Copyright (C) 1995-1998, 2000-2010 Free Software Foundation, Inc.\n" "License GPLv3+: GNU GPL version 3 or later " "<http://gnu.org/licenses/gpl.html>\n" "This is free software: you are free to change and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law.\n" "Written by Ulrich Drepper.\n", "", 0, ) cmd = MakeMessagesCommand() self.assertEqual(cmd.gettext_version, (0, 18, 1)) # Version number with only 2 parts (#23788) mocked_popen_wrapper.return_value = ( "xgettext (GNU gettext-tools) 0.17\n", "", 0, ) cmd = MakeMessagesCommand() self.assertEqual(cmd.gettext_version, (0, 17)) # Bad version output mocked_popen_wrapper.return_value = ("any other return value\n", "", 0) cmd = MakeMessagesCommand() with self.assertRaisesMessage( CommandError, "Unable to get gettext version. Is it installed?" ): cmd.gettext_version def test_po_file_encoding_when_updating(self): """ Update of PO file doesn't corrupt it with non-UTF-8 encoding on Windows (#23271). """ BR_PO_BASE = "locale/pt_BR/LC_MESSAGES/django" shutil.copyfile(BR_PO_BASE + ".pristine", BR_PO_BASE + ".po") management.call_command("makemessages", locale=["pt_BR"], verbosity=0) self.assertTrue(os.path.exists(BR_PO_BASE + ".po")) with open(BR_PO_BASE + ".po", encoding="utf-8") as fp: po_contents = fp.read() self.assertMsgStr("Größe", po_contents) def test_pot_charset_header_is_utf8(self): """Content-Type: ... charset=CHARSET is replaced with charset=UTF-8""" msgs = ( "# SOME DESCRIPTIVE TITLE.\n" "# (some lines truncated as they are not relevant)\n" '"Content-Type: text/plain; charset=CHARSET\\n"\n' '"Content-Transfer-Encoding: 8bit\\n"\n' "\n" "#: somefile.py:8\n" 'msgid "mañana; charset=CHARSET"\n' 'msgstr ""\n' ) with tempfile.NamedTemporaryFile() as pot_file: pot_filename = pot_file.name write_pot_file(pot_filename, msgs) with open(pot_filename, encoding="utf-8") as fp: pot_contents = fp.read() self.assertIn("Content-Type: text/plain; charset=UTF-8", pot_contents) self.assertIn("mañana; charset=CHARSET", pot_contents) class JavaScriptExtractorTests(ExtractorTests): PO_FILE = "locale/%s/LC_MESSAGES/djangojs.po" % LOCALE def test_javascript_literals(self): _, po_contents = self._run_makemessages(domain="djangojs") self.assertMsgId("This literal should be included.", po_contents) self.assertMsgId("gettext_noop should, too.", po_contents) self.assertMsgId("This one as well.", po_contents) self.assertMsgId(r"He said, \"hello\".", po_contents) self.assertMsgId("okkkk", po_contents) self.assertMsgId("TEXT", po_contents) self.assertMsgId("It's at http://example.com", po_contents) self.assertMsgId("String", po_contents) self.assertMsgId( "/* but this one will be too */ 'cause there is no way of telling...", po_contents, ) self.assertMsgId("foo", po_contents) self.assertMsgId("bar", po_contents) self.assertMsgId("baz", po_contents) self.assertMsgId("quz", po_contents) self.assertMsgId("foobar", po_contents) def test_media_static_dirs_ignored(self): """ Regression test for #23583. """ with override_settings( STATIC_ROOT=os.path.join(self.test_dir, "static/"), MEDIA_ROOT=os.path.join(self.test_dir, "media_root/"), ): _, po_contents = self._run_makemessages(domain="djangojs") self.assertMsgId( "Static content inside app should be included.", po_contents ) self.assertNotMsgId( "Content from STATIC_ROOT should not be included", po_contents ) @override_settings(STATIC_ROOT=None, MEDIA_ROOT="") def test_default_root_settings(self): """ Regression test for #23717. """ _, po_contents = self._run_makemessages(domain="djangojs") self.assertMsgId("Static content inside app should be included.", po_contents) class IgnoredExtractorTests(ExtractorTests): def test_ignore_directory(self): out, po_contents = self._run_makemessages( ignore_patterns=[ os.path.join("ignore_dir", "*"), ] ) self.assertIn("ignoring directory ignore_dir", out) self.assertMsgId("This literal should be included.", po_contents) self.assertNotMsgId("This should be ignored.", po_contents) def test_ignore_subdirectory(self): out, po_contents = self._run_makemessages( ignore_patterns=[ "templates/*/ignore.html", "templates/subdir/*", ] ) self.assertIn("ignoring directory subdir", out) self.assertNotMsgId("This subdir should be ignored too.", po_contents) def test_ignore_file_patterns(self): out, po_contents = self._run_makemessages( ignore_patterns=[ "xxx_*", ] ) self.assertIn("ignoring file xxx_ignored.html", out) self.assertNotMsgId("This should be ignored too.", po_contents) def test_media_static_dirs_ignored(self): with override_settings( STATIC_ROOT=os.path.join(self.test_dir, "static/"), MEDIA_ROOT=os.path.join(self.test_dir, "media_root/"), ): out, _ = self._run_makemessages() self.assertIn("ignoring directory static", out) self.assertIn("ignoring directory media_root", out) class SymlinkExtractorTests(ExtractorTests): def setUp(self): super().setUp() self.symlinked_dir = os.path.join(self.test_dir, "templates_symlinked") def test_symlink(self): if symlinks_supported(): os.symlink(os.path.join(self.test_dir, "templates"), self.symlinked_dir) else: self.skipTest( "os.symlink() not available on this OS + Python version combination." ) management.call_command( "makemessages", locale=[LOCALE], verbosity=0, symlinks=True ) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() self.assertMsgId("This literal should be included.", po_contents) self.assertLocationCommentPresent( self.PO_FILE, None, "templates_symlinked", "test.html" ) class CopyPluralFormsExtractorTests(ExtractorTests): PO_FILE_ES = "locale/es/LC_MESSAGES/django.po" def test_copy_plural_forms(self): management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() self.assertIn("Plural-Forms: nplurals=2; plural=(n != 1)", po_contents) def test_override_plural_forms(self): """Ticket #20311.""" management.call_command( "makemessages", locale=["es"], extensions=["djtpl"], verbosity=0 ) self.assertTrue(os.path.exists(self.PO_FILE_ES)) with open(self.PO_FILE_ES, encoding="utf-8") as fp: po_contents = fp.read() found = re.findall( r'^(?P<value>"Plural-Forms.+?\\n")\s*$', po_contents, re.MULTILINE | re.DOTALL, ) self.assertEqual(1, len(found)) def test_translate_and_plural_blocktranslate_collision(self): """ Ensures a correct workaround for the gettext bug when handling a literal found inside a {% translate %} tag and also in another file inside a {% blocktranslate %} with a plural (#17375). """ management.call_command( "makemessages", locale=[LOCALE], extensions=["html", "djtpl"], verbosity=0 ) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() self.assertNotIn( "#-#-#-#-# django.pot (PACKAGE VERSION) #-#-#-#-#\\n", po_contents ) self.assertMsgId( "First `translate`, then `blocktranslate` with a plural", po_contents ) self.assertMsgIdPlural( "Plural for a `translate` and `blocktranslate` collision case", po_contents, ) class NoWrapExtractorTests(ExtractorTests): def test_no_wrap_enabled(self): management.call_command( "makemessages", locale=[LOCALE], verbosity=0, no_wrap=True ) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() self.assertMsgId( "This literal should also be included wrapped or not wrapped " "depending on the use of the --no-wrap option.", po_contents, ) def test_no_wrap_disabled(self): management.call_command( "makemessages", locale=[LOCALE], verbosity=0, no_wrap=False ) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() self.assertMsgId( '""\n"This literal should also be included wrapped or not ' 'wrapped depending on the "\n"use of the --no-wrap option."', po_contents, use_quotes=False, ) class LocationCommentsTests(ExtractorTests): def test_no_location_enabled(self): """Behavior is correct if --no-location switch is specified. See #16903.""" management.call_command( "makemessages", locale=[LOCALE], verbosity=0, no_location=True ) self.assertTrue(os.path.exists(self.PO_FILE)) self.assertLocationCommentNotPresent(self.PO_FILE, None, "test.html") def test_no_location_disabled(self): """Behavior is correct if --no-location switch isn't specified.""" management.call_command( "makemessages", locale=[LOCALE], verbosity=0, no_location=False ) self.assertTrue(os.path.exists(self.PO_FILE)) # #16903 -- Standard comment with source file relative path should be present self.assertLocationCommentPresent( self.PO_FILE, "Translatable literal #6b", "templates", "test.html" ) def test_location_comments_for_templatized_files(self): """ Ensure no leaky paths in comments, e.g. #: path\to\file.html.py:123 Refs #21209/#26341. """ management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.read() self.assertMsgId("#: templates/test.html.py", po_contents) self.assertLocationCommentNotPresent(self.PO_FILE, None, ".html.py") self.assertLocationCommentPresent(self.PO_FILE, 5, "templates", "test.html") @requires_gettext_019 def test_add_location_full(self): """makemessages --add-location=full""" management.call_command( "makemessages", locale=[LOCALE], verbosity=0, add_location="full" ) self.assertTrue(os.path.exists(self.PO_FILE)) # Comment with source file relative path and line number is present. self.assertLocationCommentPresent( self.PO_FILE, "Translatable literal #6b", "templates", "test.html" ) @requires_gettext_019 def test_add_location_file(self): """makemessages --add-location=file""" management.call_command( "makemessages", locale=[LOCALE], verbosity=0, add_location="file" ) self.assertTrue(os.path.exists(self.PO_FILE)) # Comment with source file relative path is present. self.assertLocationCommentPresent(self.PO_FILE, None, "templates", "test.html") # But it should not contain the line number. self.assertLocationCommentNotPresent( self.PO_FILE, "Translatable literal #6b", "templates", "test.html" ) @requires_gettext_019 def test_add_location_never(self): """makemessages --add-location=never""" management.call_command( "makemessages", locale=[LOCALE], verbosity=0, add_location="never" ) self.assertTrue(os.path.exists(self.PO_FILE)) self.assertLocationCommentNotPresent(self.PO_FILE, None, "test.html") @mock.patch( "django.core.management.commands.makemessages.Command.gettext_version", new=(0, 18, 99), ) def test_add_location_gettext_version_check(self): """ CommandError is raised when using makemessages --add-location with gettext < 0.19. """ msg = ( "The --add-location option requires gettext 0.19 or later. You have " "0.18.99." ) with self.assertRaisesMessage(CommandError, msg): management.call_command( "makemessages", locale=[LOCALE], verbosity=0, add_location="full" ) class NoObsoleteExtractorTests(ExtractorTests): work_subdir = "obsolete_translations" def test_no_obsolete(self): management.call_command( "makemessages", locale=[LOCALE], verbosity=0, no_obsolete=True ) self.assertIs(os.path.exists(self.PO_FILE), True) with open(self.PO_FILE) as fp: po_contents = fp.read() self.assertNotIn('#~ msgid "Obsolete string."', po_contents) self.assertNotIn('#~ msgstr "Translated obsolete string."', po_contents) self.assertMsgId("This is a translatable string.", po_contents) self.assertMsgStr("This is a translated string.", po_contents) class KeepPotFileExtractorTests(ExtractorTests): POT_FILE = "locale/django.pot" def test_keep_pot_disabled_by_default(self): management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertFalse(os.path.exists(self.POT_FILE)) def test_keep_pot_explicitly_disabled(self): management.call_command( "makemessages", locale=[LOCALE], verbosity=0, keep_pot=False ) self.assertFalse(os.path.exists(self.POT_FILE)) def test_keep_pot_enabled(self): management.call_command( "makemessages", locale=[LOCALE], verbosity=0, keep_pot=True ) self.assertTrue(os.path.exists(self.POT_FILE)) class MultipleLocaleExtractionTests(ExtractorTests): PO_FILE_PT = "locale/pt/LC_MESSAGES/django.po" PO_FILE_DE = "locale/de/LC_MESSAGES/django.po" PO_FILE_KO = "locale/ko/LC_MESSAGES/django.po" LOCALES = ["pt", "de", "ch"] def test_multiple_locales(self): management.call_command("makemessages", locale=["pt", "de"], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE_PT)) self.assertTrue(os.path.exists(self.PO_FILE_DE)) def test_all_locales(self): """ When the `locale` flag is absent, all dirs from the parent locale dir are considered as language directories, except if the directory doesn't start with two letters (which excludes __pycache__, .gitignore, etc.). """ os.mkdir(os.path.join("locale", "_do_not_pick")) # Excluding locales that do not compile management.call_command("makemessages", exclude=["ja", "es_AR"], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE_KO)) self.assertFalse(os.path.exists("locale/_do_not_pick/LC_MESSAGES/django.po")) class ExcludedLocaleExtractionTests(ExtractorTests): work_subdir = "exclude" LOCALES = ["en", "fr", "it"] PO_FILE = "locale/%s/LC_MESSAGES/django.po" def _set_times_for_all_po_files(self): """ Set access and modification times to the Unix epoch time for all the .po files. """ for locale in self.LOCALES: os.utime(self.PO_FILE % locale, (0, 0)) def setUp(self): super().setUp() copytree("canned_locale", "locale") self._set_times_for_all_po_files() def test_command_help(self): with captured_stdout(), captured_stderr(): # `call_command` bypasses the parser; by calling # `execute_from_command_line` with the help subcommand we # ensure that there are no issues with the parser itself. execute_from_command_line(["django-admin", "help", "makemessages"]) def test_one_locale_excluded(self): management.call_command("makemessages", exclude=["it"], verbosity=0) self.assertRecentlyModified(self.PO_FILE % "en") self.assertRecentlyModified(self.PO_FILE % "fr") self.assertNotRecentlyModified(self.PO_FILE % "it") def test_multiple_locales_excluded(self): management.call_command("makemessages", exclude=["it", "fr"], verbosity=0) self.assertRecentlyModified(self.PO_FILE % "en") self.assertNotRecentlyModified(self.PO_FILE % "fr") self.assertNotRecentlyModified(self.PO_FILE % "it") def test_one_locale_excluded_with_locale(self): management.call_command( "makemessages", locale=["en", "fr"], exclude=["fr"], verbosity=0 ) self.assertRecentlyModified(self.PO_FILE % "en") self.assertNotRecentlyModified(self.PO_FILE % "fr") self.assertNotRecentlyModified(self.PO_FILE % "it") def test_multiple_locales_excluded_with_locale(self): management.call_command( "makemessages", locale=["en", "fr", "it"], exclude=["fr", "it"], verbosity=0 ) self.assertRecentlyModified(self.PO_FILE % "en") self.assertNotRecentlyModified(self.PO_FILE % "fr") self.assertNotRecentlyModified(self.PO_FILE % "it") class CustomLayoutExtractionTests(ExtractorTests): work_subdir = "project_dir" def test_no_locale_raises(self): msg = ( "Unable to find a locale path to store translations for file " "__init__.py. Make sure the 'locale' directory exists in an app " "or LOCALE_PATHS setting is set." ) with self.assertRaisesMessage(management.CommandError, msg): management.call_command("makemessages", locale=[LOCALE], verbosity=0) # Working files are cleaned up on an error. self.assertFalse(os.path.exists("./app_no_locale/test.html.py")) def test_project_locale_paths(self): self._test_project_locale_paths(os.path.join(self.test_dir, "project_locale")) def test_project_locale_paths_pathlib(self): self._test_project_locale_paths(Path(self.test_dir) / "project_locale") def _test_project_locale_paths(self, locale_path): """ * translations for an app containing a locale folder are stored in that folder * translations outside of that app are in LOCALE_PATHS[0] """ with override_settings(LOCALE_PATHS=[locale_path]): management.call_command("makemessages", locale=[LOCALE], verbosity=0) project_de_locale = os.path.join( self.test_dir, "project_locale", "de", "LC_MESSAGES", "django.po" ) app_de_locale = os.path.join( self.test_dir, "app_with_locale", "locale", "de", "LC_MESSAGES", "django.po", ) self.assertTrue(os.path.exists(project_de_locale)) self.assertTrue(os.path.exists(app_de_locale)) with open(project_de_locale) as fp: po_contents = fp.read() self.assertMsgId("This app has no locale directory", po_contents) self.assertMsgId("This is a project-level string", po_contents) with open(app_de_locale) as fp: po_contents = fp.read() self.assertMsgId("This app has a locale directory", po_contents) @skipUnless(has_xgettext, "xgettext is mandatory for extraction tests") class NoSettingsExtractionTests(AdminScriptTestCase): def test_makemessages_no_settings(self): out, err = self.run_django_admin(["makemessages", "-l", "en", "-v", "0"]) self.assertNoOutput(err) self.assertNoOutput(out) class UnchangedPoExtractionTests(ExtractorTests): work_subdir = "unchanged" def setUp(self): super().setUp() po_file = Path(self.PO_FILE) po_file_tmp = Path(self.PO_FILE + ".tmp") if os.name == "nt": # msgmerge outputs Windows style paths on Windows. po_contents = po_file_tmp.read_text().replace( "#: __init__.py", "#: .\\__init__.py", ) po_file.write_text(po_contents) else: po_file_tmp.rename(po_file) self.original_po_contents = po_file.read_text() def test_po_remains_unchanged(self): """PO files are unchanged unless there are new changes.""" _, po_contents = self._run_makemessages() self.assertEqual(po_contents, self.original_po_contents) def test_po_changed_with_new_strings(self): """PO files are updated when new changes are detected.""" Path("models.py.tmp").rename("models.py") _, po_contents = self._run_makemessages() self.assertNotEqual(po_contents, self.original_po_contents) self.assertMsgId( "This is a hitherto undiscovered translatable string.", po_contents, )
e4e364989b1d5d46226fcc7a5d637782d570f75c6fd00c2061d21da9fa98fbe8
from django.contrib import admin from django.contrib.admin.decorators import register from django.contrib.admin.exceptions import AlreadyRegistered, NotRegistered from django.contrib.admin.sites import site from django.core.exceptions import ImproperlyConfigured from django.test import SimpleTestCase from .models import Location, Person, Place, Traveler class NameAdmin(admin.ModelAdmin): list_display = ["name"] save_on_top = True class CustomSite(admin.AdminSite): pass class TestRegistration(SimpleTestCase): def setUp(self): self.site = admin.AdminSite() def test_bare_registration(self): self.site.register(Person) self.assertIsInstance(self.site.get_model_admin(Person), admin.ModelAdmin) self.site.unregister(Person) self.assertEqual(self.site._registry, {}) def test_registration_with_model_admin(self): self.site.register(Person, NameAdmin) self.assertIsInstance(self.site.get_model_admin(Person), NameAdmin) self.site.unregister(Person) self.assertEqual(self.site._registry, {}) def test_prevent_double_registration(self): self.site.register(Person) msg = "The model Person is already registered in app 'admin_registration'." with self.assertRaisesMessage(AlreadyRegistered, msg): self.site.register(Person) def test_prevent_double_registration_for_custom_admin(self): class PersonAdmin(admin.ModelAdmin): pass self.site.register(Person, PersonAdmin) msg = ( "The model Person is already registered with " "'admin_registration.PersonAdmin'." ) with self.assertRaisesMessage(AlreadyRegistered, msg): self.site.register(Person, PersonAdmin) def test_unregister_unregistered_model(self): msg = "The model Person is not registered" with self.assertRaisesMessage(NotRegistered, msg): self.site.unregister(Person) def test_registration_with_star_star_options(self): self.site.register(Person, search_fields=["name"]) self.assertEqual(self.site.get_model_admin(Person).search_fields, ["name"]) def test_get_model_admin_unregister_model(self): msg = "The model Person is not registered." with self.assertRaisesMessage(NotRegistered, msg): self.site.get_model_admin(Person) def test_star_star_overrides(self): self.site.register( Person, NameAdmin, search_fields=["name"], list_display=["__str__"] ) person_admin = self.site.get_model_admin(Person) self.assertEqual(person_admin.search_fields, ["name"]) self.assertEqual(person_admin.list_display, ["__str__"]) self.assertIs(person_admin.save_on_top, True) def test_iterable_registration(self): self.site.register([Person, Place], search_fields=["name"]) self.assertIsInstance(self.site.get_model_admin(Person), admin.ModelAdmin) self.assertEqual(self.site.get_model_admin(Person).search_fields, ["name"]) self.assertIsInstance(self.site.get_model_admin(Place), admin.ModelAdmin) self.assertEqual(self.site.get_model_admin(Place).search_fields, ["name"]) self.site.unregister([Person, Place]) self.assertEqual(self.site._registry, {}) def test_abstract_model(self): """ Exception is raised when trying to register an abstract model. Refs #12004. """ msg = "The model Location is abstract, so it cannot be registered with admin." with self.assertRaisesMessage(ImproperlyConfigured, msg): self.site.register(Location) def test_is_registered_model(self): "Checks for registered models should return true." self.site.register(Person) self.assertTrue(self.site.is_registered(Person)) def test_is_registered_not_registered_model(self): "Checks for unregistered models should return false." self.assertFalse(self.site.is_registered(Person)) class TestRegistrationDecorator(SimpleTestCase): """ Tests the register decorator in admin.decorators For clarity: @register(Person) class AuthorAdmin(ModelAdmin): pass is functionally equal to (the way it is written in these tests): AuthorAdmin = register(Person)(AuthorAdmin) """ def setUp(self): self.default_site = site self.custom_site = CustomSite() def test_basic_registration(self): register(Person)(NameAdmin) self.assertIsInstance( self.default_site.get_model_admin(Person), admin.ModelAdmin ) self.default_site.unregister(Person) def test_custom_site_registration(self): register(Person, site=self.custom_site)(NameAdmin) self.assertIsInstance( self.custom_site.get_model_admin(Person), admin.ModelAdmin ) def test_multiple_registration(self): register(Traveler, Place)(NameAdmin) self.assertIsInstance( self.default_site.get_model_admin(Traveler), admin.ModelAdmin ) self.default_site.unregister(Traveler) self.assertIsInstance( self.default_site.get_model_admin(Place), admin.ModelAdmin ) self.default_site.unregister(Place) def test_wrapped_class_not_a_model_admin(self): with self.assertRaisesMessage( ValueError, "Wrapped class must subclass ModelAdmin." ): register(Person)(CustomSite) def test_custom_site_not_an_admin_site(self): with self.assertRaisesMessage(ValueError, "site must subclass AdminSite"): register(Person, site=Traveler)(NameAdmin) def test_empty_models_list_registration_fails(self): with self.assertRaisesMessage( ValueError, "At least one model must be passed to register." ): register()(NameAdmin)
d93371c7ba7ed235e33819079d04e5ed05810b6fdc53483e5e33c94a44f59b42
import datetime from unittest import mock from django.contrib import admin from django.contrib.admin.models import LogEntry from django.contrib.admin.options import IncorrectLookupParameters from django.contrib.admin.templatetags.admin_list import pagination from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.admin.views.main import ( ALL_VAR, IS_FACETS_VAR, IS_POPUP_VAR, ORDER_VAR, PAGE_VAR, SEARCH_VAR, TO_FIELD_VAR, ) from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.messages.storage.cookie import CookieStorage from django.db import DatabaseError, connection, models from django.db.models import F, Field, IntegerField from django.db.models.functions import Upper from django.db.models.lookups import Contains, Exact from django.template import Context, Template, TemplateSyntaxError from django.test import TestCase, override_settings, skipUnlessDBFeature from django.test.client import RequestFactory from django.test.utils import CaptureQueriesContext, isolate_apps, register_lookup from django.urls import reverse from django.utils import formats from .admin import ( BandAdmin, ChildAdmin, ChordsBandAdmin, ConcertAdmin, CustomPaginationAdmin, CustomPaginator, DynamicListDisplayChildAdmin, DynamicListDisplayLinksChildAdmin, DynamicListFilterChildAdmin, DynamicSearchFieldsChildAdmin, EmptyValueChildAdmin, EventAdmin, FilteredChildAdmin, GroupAdmin, InvitationAdmin, NoListDisplayLinksParentAdmin, ParentAdmin, ParentAdminTwoSearchFields, QuartetAdmin, SwallowAdmin, ) from .admin import site as custom_site from .models import ( Band, CharPK, Child, ChordsBand, ChordsMusician, Concert, CustomIdUser, Event, Genre, Group, Invitation, Membership, Musician, OrderedObject, Parent, Quartet, Swallow, SwallowOneToOne, UnorderedObject, ) def build_tbody_html(obj, href, extra_fields): return ( "<tbody><tr>" '<td class="action-checkbox">' '<input type="checkbox" name="_selected_action" value="{}" ' 'class="action-select" aria-label="Select this object for an action - {}"></td>' '<th class="field-name"><a href="{}">name</a></th>' "{}</tr></tbody>" ).format(obj.pk, str(obj), href, extra_fields) @override_settings(ROOT_URLCONF="admin_changelist.urls") class ChangeListTests(TestCase): factory = RequestFactory() @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", email="[email protected]", password="xxx" ) def _create_superuser(self, username): return User.objects.create_superuser( username=username, email="[email protected]", password="xxx" ) def _mocked_authenticated_request(self, url, user): request = self.factory.get(url) request.user = user return request def test_repr(self): m = ChildAdmin(Child, custom_site) request = self.factory.get("/child/") request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(repr(cl), "<ChangeList: model=Child model_admin=ChildAdmin>") def test_specified_ordering_by_f_expression(self): class OrderedByFBandAdmin(admin.ModelAdmin): list_display = ["name", "genres", "nr_of_members"] ordering = ( F("nr_of_members").desc(nulls_last=True), Upper(F("name")).asc(), F("genres").asc(), ) m = OrderedByFBandAdmin(Band, custom_site) request = self.factory.get("/band/") request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.get_ordering_field_columns(), {3: "desc", 2: "asc"}) def test_specified_ordering_by_f_expression_without_asc_desc(self): class OrderedByFBandAdmin(admin.ModelAdmin): list_display = ["name", "genres", "nr_of_members"] ordering = (F("nr_of_members"), Upper("name"), F("genres")) m = OrderedByFBandAdmin(Band, custom_site) request = self.factory.get("/band/") request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.get_ordering_field_columns(), {3: "asc", 2: "asc"}) def test_select_related_preserved(self): """ Regression test for #10348: ChangeList.get_queryset() shouldn't overwrite a custom select_related provided by ModelAdmin.get_queryset(). """ m = ChildAdmin(Child, custom_site) request = self.factory.get("/child/") request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.query.select_related, {"parent": {}}) def test_select_related_preserved_when_multi_valued_in_search_fields(self): parent = Parent.objects.create(name="Mary") Child.objects.create(parent=parent, name="Danielle") Child.objects.create(parent=parent, name="Daniel") m = ParentAdmin(Parent, custom_site) request = self.factory.get("/parent/", data={SEARCH_VAR: "daniel"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 1) # select_related is preserved. self.assertEqual(cl.queryset.query.select_related, {"child": {}}) def test_select_related_as_tuple(self): ia = InvitationAdmin(Invitation, custom_site) request = self.factory.get("/invitation/") request.user = self.superuser cl = ia.get_changelist_instance(request) self.assertEqual(cl.queryset.query.select_related, {"player": {}}) def test_select_related_as_empty_tuple(self): ia = InvitationAdmin(Invitation, custom_site) ia.list_select_related = () request = self.factory.get("/invitation/") request.user = self.superuser cl = ia.get_changelist_instance(request) self.assertIs(cl.queryset.query.select_related, False) def test_get_select_related_custom_method(self): class GetListSelectRelatedAdmin(admin.ModelAdmin): list_display = ("band", "player") def get_list_select_related(self, request): return ("band", "player") ia = GetListSelectRelatedAdmin(Invitation, custom_site) request = self.factory.get("/invitation/") request.user = self.superuser cl = ia.get_changelist_instance(request) self.assertEqual(cl.queryset.query.select_related, {"player": {}, "band": {}}) def test_many_search_terms(self): parent = Parent.objects.create(name="Mary") Child.objects.create(parent=parent, name="Danielle") Child.objects.create(parent=parent, name="Daniel") m = ParentAdmin(Parent, custom_site) request = self.factory.get("/parent/", data={SEARCH_VAR: "daniel " * 80}) request.user = self.superuser cl = m.get_changelist_instance(request) with CaptureQueriesContext(connection) as context: object_count = cl.queryset.count() self.assertEqual(object_count, 1) self.assertEqual(context.captured_queries[0]["sql"].count("JOIN"), 1) def test_related_field_multiple_search_terms(self): """ Searches over multi-valued relationships return rows from related models only when all searched fields match that row. """ parent = Parent.objects.create(name="Mary") Child.objects.create(parent=parent, name="Danielle", age=18) Child.objects.create(parent=parent, name="Daniel", age=19) m = ParentAdminTwoSearchFields(Parent, custom_site) request = self.factory.get("/parent/", data={SEARCH_VAR: "danielle 19"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 0) request = self.factory.get("/parent/", data={SEARCH_VAR: "daniel 19"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 1) def test_result_list_empty_changelist_value(self): """ Regression test for #14982: EMPTY_CHANGELIST_VALUE should be honored for relationship fields """ new_child = Child.objects.create(name="name", parent=None) request = self.factory.get("/child/") request.user = self.superuser m = ChildAdmin(Child, custom_site) cl = m.get_changelist_instance(request) cl.formset = None template = Template( "{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}" ) context = Context({"cl": cl, "opts": Child._meta}) table_output = template.render(context) link = reverse("admin:admin_changelist_child_change", args=(new_child.id,)) row_html = build_tbody_html( new_child, link, '<td class="field-parent nowrap">-</td>' ) self.assertNotEqual( table_output.find(row_html), -1, "Failed to find expected row element: %s" % table_output, ) def test_result_list_set_empty_value_display_on_admin_site(self): """ Empty value display can be set on AdminSite. """ new_child = Child.objects.create(name="name", parent=None) request = self.factory.get("/child/") request.user = self.superuser # Set a new empty display value on AdminSite. admin.site.empty_value_display = "???" m = ChildAdmin(Child, admin.site) cl = m.get_changelist_instance(request) cl.formset = None template = Template( "{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}" ) context = Context({"cl": cl, "opts": Child._meta}) table_output = template.render(context) link = reverse("admin:admin_changelist_child_change", args=(new_child.id,)) row_html = build_tbody_html( new_child, link, '<td class="field-parent nowrap">???</td>' ) self.assertNotEqual( table_output.find(row_html), -1, "Failed to find expected row element: %s" % table_output, ) def test_result_list_set_empty_value_display_in_model_admin(self): """ Empty value display can be set in ModelAdmin or individual fields. """ new_child = Child.objects.create(name="name", parent=None) request = self.factory.get("/child/") request.user = self.superuser m = EmptyValueChildAdmin(Child, admin.site) cl = m.get_changelist_instance(request) cl.formset = None template = Template( "{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}" ) context = Context({"cl": cl, "opts": Child._meta}) table_output = template.render(context) link = reverse("admin:admin_changelist_child_change", args=(new_child.id,)) row_html = build_tbody_html( new_child, link, '<td class="field-age_display">&amp;dagger;</td>' '<td class="field-age">-empty-</td>', ) self.assertNotEqual( table_output.find(row_html), -1, "Failed to find expected row element: %s" % table_output, ) def test_result_list_html(self): """ Inclusion tag result_list generates a table when with default ModelAdmin settings. """ new_parent = Parent.objects.create(name="parent") new_child = Child.objects.create(name="name", parent=new_parent) request = self.factory.get("/child/") request.user = self.superuser m = ChildAdmin(Child, custom_site) cl = m.get_changelist_instance(request) cl.formset = None template = Template( "{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}" ) context = Context({"cl": cl, "opts": Child._meta}) table_output = template.render(context) link = reverse("admin:admin_changelist_child_change", args=(new_child.id,)) row_html = build_tbody_html( new_child, link, '<td class="field-parent nowrap">%s</td>' % new_parent ) self.assertNotEqual( table_output.find(row_html), -1, "Failed to find expected row element: %s" % table_output, ) self.assertInHTML( '<input type="checkbox" id="action-toggle" ' 'aria-label="Select all objects on this page for an action">', table_output, ) def test_result_list_editable_html(self): """ Regression tests for #11791: Inclusion tag result_list generates a table and this checks that the items are nested within the table element tags. Also a regression test for #13599, verifies that hidden fields when list_editable is enabled are rendered in a div outside the table. """ new_parent = Parent.objects.create(name="parent") new_child = Child.objects.create(name="name", parent=new_parent) request = self.factory.get("/child/") request.user = self.superuser m = ChildAdmin(Child, custom_site) # Test with list_editable fields m.list_display = ["id", "name", "parent"] m.list_display_links = ["id"] m.list_editable = ["name"] cl = m.get_changelist_instance(request) FormSet = m.get_changelist_formset(request) cl.formset = FormSet(queryset=cl.result_list) template = Template( "{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}" ) context = Context({"cl": cl, "opts": Child._meta}) table_output = template.render(context) # make sure that hidden fields are in the correct place hiddenfields_div = ( '<div class="hiddenfields">' '<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id">' "</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 = ( '<input name="form-0-name" value="name" class="vTextField" ' 'maxlength="30" type="text" id="id_form-0-name">' ) self.assertInHTML( '<td class="field-name">%s</td>' % editable_name_field, table_output, msg_prefix='Failed to find "name" list_editable field', ) def test_result_list_editable(self): """ Regression test for #14312: list_editable with pagination """ new_parent = Parent.objects.create(name="parent") for i in range(1, 201): Child.objects.create(name="name %s" % i, parent=new_parent) request = self.factory.get("/child/", data={"p": -1}) # Anything outside range request.user = self.superuser m = ChildAdmin(Child, custom_site) # Test with list_editable fields m.list_display = ["id", "name", "parent"] m.list_display_links = ["id"] m.list_editable = ["name"] with self.assertRaises(IncorrectLookupParameters): m.get_changelist_instance(request) @skipUnlessDBFeature("supports_transactions") def test_list_editable_atomicity(self): a = Swallow.objects.create(origin="Swallow A", load=4, speed=1) b = Swallow.objects.create(origin="Swallow B", load=2, speed=2) self.client.force_login(self.superuser) changelist_url = reverse("admin:admin_changelist_swallow_changelist") data = { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "2", "form-MIN_NUM_FORMS": "0", "form-MAX_NUM_FORMS": "1000", "form-0-uuid": str(a.pk), "form-1-uuid": str(b.pk), "form-0-load": "9.0", "form-0-speed": "3.0", "form-1-load": "5.0", "form-1-speed": "1.0", "_save": "Save", } with mock.patch( "django.contrib.admin.ModelAdmin.log_change", side_effect=DatabaseError ): with self.assertRaises(DatabaseError): self.client.post(changelist_url, data) # Original values are preserved. a.refresh_from_db() self.assertEqual(a.load, 4) self.assertEqual(a.speed, 1) b.refresh_from_db() self.assertEqual(b.load, 2) self.assertEqual(b.speed, 2) with mock.patch( "django.contrib.admin.ModelAdmin.log_change", side_effect=[None, DatabaseError], ): with self.assertRaises(DatabaseError): self.client.post(changelist_url, data) # Original values are preserved. a.refresh_from_db() self.assertEqual(a.load, 4) self.assertEqual(a.speed, 1) b.refresh_from_db() self.assertEqual(b.load, 2) self.assertEqual(b.speed, 2) def test_custom_paginator(self): new_parent = Parent.objects.create(name="parent") for i in range(1, 201): Child.objects.create(name="name %s" % i, parent=new_parent) request = self.factory.get("/child/") request.user = self.superuser m = CustomPaginationAdmin(Child, custom_site) cl = m.get_changelist_instance(request) cl.get_results(request) self.assertIsInstance(cl.paginator, CustomPaginator) def test_distinct_for_m2m_in_list_filter(self): """ Regression test for #13902: When using a ManyToMany in list_filter, results shouldn't appear more than once. Basic ManyToMany. """ blues = Genre.objects.create(name="Blues") band = Band.objects.create(name="B.B. King Review", nr_of_members=11) band.genres.add(blues) band.genres.add(blues) m = BandAdmin(Band, custom_site) request = self.factory.get("/band/", data={"genres": blues.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) cl.get_results(request) # There's only one Group instance self.assertEqual(cl.result_count, 1) # Queryset must be deletable. cl.queryset.delete() self.assertEqual(cl.queryset.count(), 0) def test_distinct_for_through_m2m_in_list_filter(self): """ Regression test for #13902: When using a ManyToMany in list_filter, results shouldn't appear more than once. With an intermediate model. """ lead = Musician.objects.create(name="Vox") band = Group.objects.create(name="The Hype") Membership.objects.create(group=band, music=lead, role="lead voice") Membership.objects.create(group=band, music=lead, role="bass player") m = GroupAdmin(Group, custom_site) request = self.factory.get("/group/", data={"members": lead.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) cl.get_results(request) # There's only one Group instance self.assertEqual(cl.result_count, 1) # Queryset must be deletable. cl.queryset.delete() self.assertEqual(cl.queryset.count(), 0) def test_distinct_for_through_m2m_at_second_level_in_list_filter(self): """ When using a ManyToMany in list_filter at the second level behind a ForeignKey, distinct() must be called and results shouldn't appear more than once. """ lead = Musician.objects.create(name="Vox") band = Group.objects.create(name="The Hype") Concert.objects.create(name="Woodstock", group=band) Membership.objects.create(group=band, music=lead, role="lead voice") Membership.objects.create(group=band, music=lead, role="bass player") m = ConcertAdmin(Concert, custom_site) request = self.factory.get("/concert/", data={"group__members": lead.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) cl.get_results(request) # There's only one Concert instance self.assertEqual(cl.result_count, 1) # Queryset must be deletable. cl.queryset.delete() self.assertEqual(cl.queryset.count(), 0) def test_distinct_for_inherited_m2m_in_list_filter(self): """ Regression test for #13902: When using a ManyToMany in list_filter, results shouldn't appear more than once. Model managed in the admin inherits from the one that defines the relationship. """ lead = Musician.objects.create(name="John") four = Quartet.objects.create(name="The Beatles") Membership.objects.create(group=four, music=lead, role="lead voice") Membership.objects.create(group=four, music=lead, role="guitar player") m = QuartetAdmin(Quartet, custom_site) request = self.factory.get("/quartet/", data={"members": lead.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) cl.get_results(request) # There's only one Quartet instance self.assertEqual(cl.result_count, 1) # Queryset must be deletable. cl.queryset.delete() self.assertEqual(cl.queryset.count(), 0) def test_distinct_for_m2m_to_inherited_in_list_filter(self): """ Regression test for #13902: When using a ManyToMany in list_filter, results shouldn't appear more than once. Target of the relationship inherits from another. """ lead = ChordsMusician.objects.create(name="Player A") three = ChordsBand.objects.create(name="The Chords Trio") Invitation.objects.create(band=three, player=lead, instrument="guitar") Invitation.objects.create(band=three, player=lead, instrument="bass") m = ChordsBandAdmin(ChordsBand, custom_site) request = self.factory.get("/chordsband/", data={"members": lead.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) cl.get_results(request) # There's only one ChordsBand instance self.assertEqual(cl.result_count, 1) def test_distinct_for_non_unique_related_object_in_list_filter(self): """ Regressions tests for #15819: If a field listed in list_filters is a non-unique related object, distinct() must be called. """ parent = Parent.objects.create(name="Mary") # Two children with the same name Child.objects.create(parent=parent, name="Daniel") Child.objects.create(parent=parent, name="Daniel") m = ParentAdmin(Parent, custom_site) request = self.factory.get("/parent/", data={"child__name": "Daniel"}) request.user = self.superuser cl = m.get_changelist_instance(request) # Make sure distinct() was called self.assertEqual(cl.queryset.count(), 1) # Queryset must be deletable. cl.queryset.delete() self.assertEqual(cl.queryset.count(), 0) def test_changelist_search_form_validation(self): m = ConcertAdmin(Concert, custom_site) tests = [ ({SEARCH_VAR: "\x00"}, "Null characters are not allowed."), ({SEARCH_VAR: "some\x00thing"}, "Null characters are not allowed."), ] for case, error in tests: with self.subTest(case=case): request = self.factory.get("/concert/", case) request.user = self.superuser request._messages = CookieStorage(request) m.get_changelist_instance(request) messages = [m.message for m in request._messages] self.assertEqual(1, len(messages)) self.assertEqual(error, messages[0]) def test_distinct_for_non_unique_related_object_in_search_fields(self): """ Regressions tests for #15819: If a field listed in search_fields is a non-unique related object, distinct() must be called. """ parent = Parent.objects.create(name="Mary") Child.objects.create(parent=parent, name="Danielle") Child.objects.create(parent=parent, name="Daniel") m = ParentAdmin(Parent, custom_site) request = self.factory.get("/parent/", data={SEARCH_VAR: "daniel"}) request.user = self.superuser cl = m.get_changelist_instance(request) # Make sure distinct() was called self.assertEqual(cl.queryset.count(), 1) # Queryset must be deletable. cl.queryset.delete() self.assertEqual(cl.queryset.count(), 0) def test_distinct_for_many_to_many_at_second_level_in_search_fields(self): """ When using a ManyToMany in search_fields at the second level behind a ForeignKey, distinct() must be called and results shouldn't appear more than once. """ lead = Musician.objects.create(name="Vox") band = Group.objects.create(name="The Hype") Concert.objects.create(name="Woodstock", group=band) Membership.objects.create(group=band, music=lead, role="lead voice") Membership.objects.create(group=band, music=lead, role="bass player") m = ConcertAdmin(Concert, custom_site) request = self.factory.get("/concert/", data={SEARCH_VAR: "vox"}) request.user = self.superuser cl = m.get_changelist_instance(request) # There's only one Concert instance self.assertEqual(cl.queryset.count(), 1) # Queryset must be deletable. cl.queryset.delete() self.assertEqual(cl.queryset.count(), 0) def test_multiple_search_fields(self): """ All rows containing each of the searched words are returned, where each word must be in one of search_fields. """ band_duo = Group.objects.create(name="Duo") band_hype = Group.objects.create(name="The Hype") mary = Musician.objects.create(name="Mary Halvorson") jonathan = Musician.objects.create(name="Jonathan Finlayson") band_duo.members.set([mary, jonathan]) Concert.objects.create(name="Tiny desk concert", group=band_duo) Concert.objects.create(name="Woodstock concert", group=band_hype) # FK lookup. concert_model_admin = ConcertAdmin(Concert, custom_site) concert_model_admin.search_fields = ["group__name", "name"] # Reverse FK lookup. group_model_admin = GroupAdmin(Group, custom_site) group_model_admin.search_fields = ["name", "concert__name", "members__name"] for search_string, result_count in ( ("Duo Concert", 1), ("Tiny Desk Concert", 1), ("Concert", 2), ("Other Concert", 0), ("Duo Woodstock", 0), ): with self.subTest(search_string=search_string): # FK lookup. request = self.factory.get( "/concert/", data={SEARCH_VAR: search_string} ) request.user = self.superuser concert_changelist = concert_model_admin.get_changelist_instance( request ) self.assertEqual(concert_changelist.queryset.count(), result_count) # Reverse FK lookup. request = self.factory.get("/group/", data={SEARCH_VAR: search_string}) request.user = self.superuser group_changelist = group_model_admin.get_changelist_instance(request) self.assertEqual(group_changelist.queryset.count(), result_count) # Many-to-many lookup. for search_string, result_count in ( ("Finlayson Duo Tiny", 1), ("Finlayson", 1), ("Finlayson Hype", 0), ("Jonathan Finlayson Duo", 1), ("Mary Jonathan Duo", 0), ("Oscar Finlayson Duo", 0), ): with self.subTest(search_string=search_string): request = self.factory.get("/group/", data={SEARCH_VAR: search_string}) request.user = self.superuser group_changelist = group_model_admin.get_changelist_instance(request) self.assertEqual(group_changelist.queryset.count(), result_count) def test_pk_in_search_fields(self): band = Group.objects.create(name="The Hype") Concert.objects.create(name="Woodstock", group=band) m = ConcertAdmin(Concert, custom_site) m.search_fields = ["group__pk"] request = self.factory.get("/concert/", data={SEARCH_VAR: band.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 1) request = self.factory.get("/concert/", data={SEARCH_VAR: band.pk + 5}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 0) def test_builtin_lookup_in_search_fields(self): band = Group.objects.create(name="The Hype") concert = Concert.objects.create(name="Woodstock", group=band) m = ConcertAdmin(Concert, custom_site) m.search_fields = ["name__iexact"] request = self.factory.get("/", data={SEARCH_VAR: "woodstock"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [concert]) request = self.factory.get("/", data={SEARCH_VAR: "wood"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, []) def test_custom_lookup_in_search_fields(self): band = Group.objects.create(name="The Hype") concert = Concert.objects.create(name="Woodstock", group=band) m = ConcertAdmin(Concert, custom_site) m.search_fields = ["group__name__cc"] with register_lookup(Field, Contains, lookup_name="cc"): request = self.factory.get("/", data={SEARCH_VAR: "Hype"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [concert]) request = self.factory.get("/", data={SEARCH_VAR: "Woodstock"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, []) def test_spanning_relations_with_custom_lookup_in_search_fields(self): hype = Group.objects.create(name="The Hype") concert = Concert.objects.create(name="Woodstock", group=hype) vox = Musician.objects.create(name="Vox", age=20) Membership.objects.create(music=vox, group=hype) # Register a custom lookup on IntegerField to ensure that field # traversing logic in ModelAdmin.get_search_results() works. with register_lookup(IntegerField, Exact, lookup_name="exactly"): m = ConcertAdmin(Concert, custom_site) m.search_fields = ["group__members__age__exactly"] request = self.factory.get("/", data={SEARCH_VAR: "20"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [concert]) request = self.factory.get("/", data={SEARCH_VAR: "21"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, []) def test_custom_lookup_with_pk_shortcut(self): self.assertEqual(CharPK._meta.pk.name, "char_pk") # Not equal to 'pk'. m = admin.ModelAdmin(CustomIdUser, custom_site) abc = CharPK.objects.create(char_pk="abc") abcd = CharPK.objects.create(char_pk="abcd") m = admin.ModelAdmin(CharPK, custom_site) m.search_fields = ["pk__exact"] request = self.factory.get("/", data={SEARCH_VAR: "abc"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [abc]) request = self.factory.get("/", data={SEARCH_VAR: "abcd"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [abcd]) def test_no_distinct_for_m2m_in_list_filter_without_params(self): """ If a ManyToManyField is in list_filter but isn't in any lookup params, the changelist's query shouldn't have distinct. """ m = BandAdmin(Band, custom_site) for lookup_params in ({}, {"name": "test"}): request = self.factory.get("/band/", lookup_params) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertIs(cl.queryset.query.distinct, False) # A ManyToManyField in params does have distinct applied. request = self.factory.get("/band/", {"genres": "0"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertIs(cl.queryset.query.distinct, True) def test_pagination(self): """ Regression tests for #12893: Pagination in admins changelist doesn't use queryset set by modeladmin. """ parent = Parent.objects.create(name="anything") for i in range(1, 31): Child.objects.create(name="name %s" % i, parent=parent) Child.objects.create(name="filtered %s" % i, parent=parent) request = self.factory.get("/child/") request.user = self.superuser # Test default queryset m = ChildAdmin(Child, custom_site) cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 60) self.assertEqual(cl.paginator.count, 60) self.assertEqual(list(cl.paginator.page_range), [1, 2, 3, 4, 5, 6]) # Test custom queryset m = FilteredChildAdmin(Child, custom_site) cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 30) self.assertEqual(cl.paginator.count, 30) self.assertEqual(list(cl.paginator.page_range), [1, 2, 3]) def test_computed_list_display_localization(self): """ Regression test for #13196: output of functions should be localized in the changelist. """ self.client.force_login(self.superuser) event = Event.objects.create(date=datetime.date.today()) response = self.client.get(reverse("admin:admin_changelist_event_changelist")) self.assertContains(response, formats.localize(event.date)) self.assertNotContains(response, str(event.date)) def test_dynamic_list_display(self): """ Regression tests for #14206: dynamic list_display support. """ parent = Parent.objects.create(name="parent") for i in range(10): Child.objects.create(name="child %s" % i, parent=parent) user_noparents = self._create_superuser("noparents") user_parents = self._create_superuser("parents") # Test with user 'noparents' m = custom_site.get_model_admin(Child) request = self._mocked_authenticated_request("/child/", user_noparents) response = m.changelist_view(request) self.assertNotContains(response, "Parent object") list_display = m.get_list_display(request) list_display_links = m.get_list_display_links(request, list_display) self.assertEqual(list_display, ["name", "age"]) self.assertEqual(list_display_links, ["name"]) # Test with user 'parents' m = DynamicListDisplayChildAdmin(Child, custom_site) request = self._mocked_authenticated_request("/child/", user_parents) response = m.changelist_view(request) self.assertContains(response, "Parent object") custom_site.unregister(Child) list_display = m.get_list_display(request) list_display_links = m.get_list_display_links(request, list_display) self.assertEqual(list_display, ("parent", "name", "age")) self.assertEqual(list_display_links, ["parent"]) # Test default implementation custom_site.register(Child, ChildAdmin) m = custom_site.get_model_admin(Child) request = self._mocked_authenticated_request("/child/", user_noparents) response = m.changelist_view(request) self.assertContains(response, "Parent object") def test_show_all(self): parent = Parent.objects.create(name="anything") for i in range(1, 31): Child.objects.create(name="name %s" % i, parent=parent) Child.objects.create(name="filtered %s" % i, parent=parent) # Add "show all" parameter to request request = self.factory.get("/child/", data={ALL_VAR: ""}) request.user = self.superuser # Test valid "show all" request (number of total objects is under max) m = ChildAdmin(Child, custom_site) m.list_max_show_all = 200 # 200 is the max we'll pass to ChangeList cl = m.get_changelist_instance(request) cl.get_results(request) self.assertEqual(len(cl.result_list), 60) # Test invalid "show all" request (number of total objects over max) # falls back to paginated pages m = ChildAdmin(Child, custom_site) m.list_max_show_all = 30 # 30 is the max we'll pass to ChangeList for this test cl = m.get_changelist_instance(request) cl.get_results(request) self.assertEqual(len(cl.result_list), 10) def test_dynamic_list_display_links(self): """ Regression tests for #16257: dynamic list_display_links support. """ parent = Parent.objects.create(name="parent") for i in range(1, 10): Child.objects.create(id=i, name="child %s" % i, parent=parent, age=i) m = DynamicListDisplayLinksChildAdmin(Child, custom_site) superuser = self._create_superuser("superuser") request = self._mocked_authenticated_request("/child/", superuser) response = m.changelist_view(request) for i in range(1, 10): link = reverse("admin:admin_changelist_child_change", args=(i,)) self.assertContains(response, '<a href="%s">%s</a>' % (link, i)) list_display = m.get_list_display(request) list_display_links = m.get_list_display_links(request, list_display) self.assertEqual(list_display, ("parent", "name", "age")) self.assertEqual(list_display_links, ["age"]) def test_no_list_display_links(self): """#15185 -- Allow no links from the 'change list' view grid.""" p = Parent.objects.create(name="parent") m = NoListDisplayLinksParentAdmin(Parent, custom_site) superuser = self._create_superuser("superuser") request = self._mocked_authenticated_request("/parent/", superuser) response = m.changelist_view(request) link = reverse("admin:admin_changelist_parent_change", args=(p.pk,)) self.assertNotContains(response, '<a href="%s">' % link) def test_clear_all_filters_link(self): self.client.force_login(self.superuser) url = reverse("admin:auth_user_changelist") response = self.client.get(url) self.assertNotContains(response, "&#10006; Clear all filters") link = '<a href="%s">&#10006; Clear all filters</a>' for data, href in ( ({"is_staff__exact": "0"}, "?"), ( {"is_staff__exact": "0", "username__startswith": "test"}, "?username__startswith=test", ), ( {"is_staff__exact": "0", SEARCH_VAR: "test"}, "?%s=test" % SEARCH_VAR, ), ( {"is_staff__exact": "0", IS_POPUP_VAR: "id"}, "?%s=id" % IS_POPUP_VAR, ), ): with self.subTest(data=data): response = self.client.get(url, data=data) self.assertContains(response, link % href) def test_clear_all_filters_link_callable_filter(self): self.client.force_login(self.superuser) url = reverse("admin:admin_changelist_band_changelist") response = self.client.get(url) self.assertNotContains(response, "&#10006; Clear all filters") link = '<a href="%s">&#10006; Clear all filters</a>' for data, href in ( ({"nr_of_members_partition": "5"}, "?"), ( {"nr_of_members_partition": "more", "name__startswith": "test"}, "?name__startswith=test", ), ( {"nr_of_members_partition": "5", IS_POPUP_VAR: "id"}, "?%s=id" % IS_POPUP_VAR, ), ): with self.subTest(data=data): response = self.client.get(url, data=data) self.assertContains(response, link % href) def test_no_clear_all_filters_link(self): self.client.force_login(self.superuser) url = reverse("admin:auth_user_changelist") link = ">&#10006; Clear all filters</a>" for data in ( {SEARCH_VAR: "test"}, {ORDER_VAR: "-1"}, {TO_FIELD_VAR: "id"}, {PAGE_VAR: "1"}, {IS_POPUP_VAR: "1"}, {IS_FACETS_VAR: ""}, {"username__startswith": "test"}, ): with self.subTest(data=data): response = self.client.get(url, data=data) self.assertNotContains(response, link) def test_tuple_list_display(self): swallow = Swallow.objects.create(origin="Africa", load="12.34", speed="22.2") swallow2 = Swallow.objects.create(origin="Africa", load="12.34", speed="22.2") swallow_o2o = SwallowOneToOne.objects.create(swallow=swallow2) model_admin = SwallowAdmin(Swallow, custom_site) superuser = self._create_superuser("superuser") request = self._mocked_authenticated_request("/swallow/", superuser) response = model_admin.changelist_view(request) # just want to ensure it doesn't blow up during rendering self.assertContains(response, str(swallow.origin)) self.assertContains(response, str(swallow.load)) self.assertContains(response, str(swallow.speed)) # Reverse one-to-one relations should work. self.assertContains(response, '<td class="field-swallowonetoone">-</td>') self.assertContains( response, '<td class="field-swallowonetoone">%s</td>' % swallow_o2o ) def test_multiuser_edit(self): """ Simultaneous edits of list_editable fields on the changelist by different users must not result in one user's edits creating a new object instead of modifying the correct existing object (#11313). """ # To replicate this issue, simulate the following steps: # 1. User1 opens an admin changelist with list_editable fields. # 2. User2 edits object "Foo" such that it moves to another page in # the pagination order and saves. # 3. User1 edits object "Foo" and saves. # 4. The edit made by User1 does not get applied to object "Foo" but # instead is used to create a new object (bug). # For this test, order the changelist by the 'speed' attribute and # display 3 objects per page (SwallowAdmin.list_per_page = 3). # Setup the test to reflect the DB state after step 2 where User2 has # edited the first swallow object's speed from '4' to '1'. a = Swallow.objects.create(origin="Swallow A", load=4, speed=1) b = Swallow.objects.create(origin="Swallow B", load=2, speed=2) c = Swallow.objects.create(origin="Swallow C", load=5, speed=5) d = Swallow.objects.create(origin="Swallow D", load=9, speed=9) superuser = self._create_superuser("superuser") self.client.force_login(superuser) changelist_url = reverse("admin:admin_changelist_swallow_changelist") # Send the POST from User1 for step 3. It's still using the changelist # ordering from before User2's edits in step 2. data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MIN_NUM_FORMS": "0", "form-MAX_NUM_FORMS": "1000", "form-0-uuid": str(d.pk), "form-1-uuid": str(c.pk), "form-2-uuid": str(a.pk), "form-0-load": "9.0", "form-0-speed": "9.0", "form-1-load": "5.0", "form-1-speed": "5.0", "form-2-load": "5.0", "form-2-speed": "4.0", "_save": "Save", } response = self.client.post( changelist_url, data, follow=True, extra={"o": "-2"} ) # The object User1 edited in step 3 is displayed on the changelist and # has the correct edits applied. self.assertContains(response, "1 swallow was changed successfully.") self.assertContains(response, a.origin) a.refresh_from_db() self.assertEqual(a.load, float(data["form-2-load"])) self.assertEqual(a.speed, float(data["form-2-speed"])) b.refresh_from_db() self.assertEqual(b.load, 2) self.assertEqual(b.speed, 2) c.refresh_from_db() self.assertEqual(c.load, float(data["form-1-load"])) self.assertEqual(c.speed, float(data["form-1-speed"])) d.refresh_from_db() self.assertEqual(d.load, float(data["form-0-load"])) self.assertEqual(d.speed, float(data["form-0-speed"])) # No new swallows were created. self.assertEqual(len(Swallow.objects.all()), 4) def test_get_edited_object_ids(self): a = Swallow.objects.create(origin="Swallow A", load=4, speed=1) b = Swallow.objects.create(origin="Swallow B", load=2, speed=2) c = Swallow.objects.create(origin="Swallow C", load=5, speed=5) superuser = self._create_superuser("superuser") self.client.force_login(superuser) changelist_url = reverse("admin:admin_changelist_swallow_changelist") m = SwallowAdmin(Swallow, custom_site) data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MIN_NUM_FORMS": "0", "form-MAX_NUM_FORMS": "1000", "form-0-uuid": str(a.pk), "form-1-uuid": str(b.pk), "form-2-uuid": str(c.pk), "form-0-load": "9.0", "form-0-speed": "9.0", "form-1-load": "5.0", "form-1-speed": "5.0", "form-2-load": "5.0", "form-2-speed": "4.0", "_save": "Save", } request = self.factory.post(changelist_url, data=data) pks = m._get_edited_object_pks(request, prefix="form") self.assertEqual(sorted(pks), sorted([str(a.pk), str(b.pk), str(c.pk)])) def test_get_list_editable_queryset(self): a = Swallow.objects.create(origin="Swallow A", load=4, speed=1) Swallow.objects.create(origin="Swallow B", load=2, speed=2) data = { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "2", "form-MIN_NUM_FORMS": "0", "form-MAX_NUM_FORMS": "1000", "form-0-uuid": str(a.pk), "form-0-load": "10", "_save": "Save", } superuser = self._create_superuser("superuser") self.client.force_login(superuser) changelist_url = reverse("admin:admin_changelist_swallow_changelist") m = SwallowAdmin(Swallow, custom_site) request = self.factory.post(changelist_url, data=data) queryset = m._get_list_editable_queryset(request, prefix="form") self.assertEqual(queryset.count(), 1) data["form-0-uuid"] = "INVALD_PRIMARY_KEY" # The unfiltered queryset is returned if there's invalid data. request = self.factory.post(changelist_url, data=data) queryset = m._get_list_editable_queryset(request, prefix="form") self.assertEqual(queryset.count(), 2) def test_get_list_editable_queryset_with_regex_chars_in_prefix(self): a = Swallow.objects.create(origin="Swallow A", load=4, speed=1) Swallow.objects.create(origin="Swallow B", load=2, speed=2) data = { "form$-TOTAL_FORMS": "2", "form$-INITIAL_FORMS": "2", "form$-MIN_NUM_FORMS": "0", "form$-MAX_NUM_FORMS": "1000", "form$-0-uuid": str(a.pk), "form$-0-load": "10", "_save": "Save", } superuser = self._create_superuser("superuser") self.client.force_login(superuser) changelist_url = reverse("admin:admin_changelist_swallow_changelist") m = SwallowAdmin(Swallow, custom_site) request = self.factory.post(changelist_url, data=data) queryset = m._get_list_editable_queryset(request, prefix="form$") self.assertEqual(queryset.count(), 1) def test_changelist_view_list_editable_changed_objects_uses_filter(self): """list_editable edits use a filtered queryset to limit memory usage.""" a = Swallow.objects.create(origin="Swallow A", load=4, speed=1) Swallow.objects.create(origin="Swallow B", load=2, speed=2) data = { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "2", "form-MIN_NUM_FORMS": "0", "form-MAX_NUM_FORMS": "1000", "form-0-uuid": str(a.pk), "form-0-load": "10", "_save": "Save", } superuser = self._create_superuser("superuser") self.client.force_login(superuser) changelist_url = reverse("admin:admin_changelist_swallow_changelist") with CaptureQueriesContext(connection) as context: response = self.client.post(changelist_url, data=data) self.assertEqual(response.status_code, 200) self.assertIn("WHERE", context.captured_queries[4]["sql"]) self.assertIn("IN", context.captured_queries[4]["sql"]) # Check only the first few characters since the UUID may have dashes. self.assertIn(str(a.pk)[:8], context.captured_queries[4]["sql"]) def test_deterministic_order_for_unordered_model(self): """ The primary key is used in the ordering of the changelist's results to guarantee a deterministic order, even when the model doesn't have any default ordering defined (#17198). """ superuser = self._create_superuser("superuser") for counter in range(1, 51): UnorderedObject.objects.create(id=counter, bool=True) class UnorderedObjectAdmin(admin.ModelAdmin): list_per_page = 10 def check_results_order(ascending=False): custom_site.register(UnorderedObject, UnorderedObjectAdmin) model_admin = UnorderedObjectAdmin(UnorderedObject, custom_site) counter = 0 if ascending else 51 for page in range(1, 6): request = self._mocked_authenticated_request( "/unorderedobject/?p=%s" % page, superuser ) response = model_admin.changelist_view(request) for result in response.context_data["cl"].result_list: counter += 1 if ascending else -1 self.assertEqual(result.id, counter) custom_site.unregister(UnorderedObject) # When no order is defined at all, everything is ordered by '-pk'. check_results_order() # When an order field is defined but multiple records have the same # value for that field, make sure everything gets ordered by -pk as well. UnorderedObjectAdmin.ordering = ["bool"] check_results_order() # When order fields are defined, including the pk itself, use them. UnorderedObjectAdmin.ordering = ["bool", "-pk"] check_results_order() UnorderedObjectAdmin.ordering = ["bool", "pk"] check_results_order(ascending=True) UnorderedObjectAdmin.ordering = ["-id", "bool"] check_results_order() UnorderedObjectAdmin.ordering = ["id", "bool"] check_results_order(ascending=True) def test_deterministic_order_for_model_ordered_by_its_manager(self): """ The primary key is used in the ordering of the changelist's results to guarantee a deterministic order, even when the model has a manager that defines a default ordering (#17198). """ superuser = self._create_superuser("superuser") for counter in range(1, 51): OrderedObject.objects.create(id=counter, bool=True, number=counter) class OrderedObjectAdmin(admin.ModelAdmin): list_per_page = 10 def check_results_order(ascending=False): custom_site.register(OrderedObject, OrderedObjectAdmin) model_admin = OrderedObjectAdmin(OrderedObject, custom_site) counter = 0 if ascending else 51 for page in range(1, 6): request = self._mocked_authenticated_request( "/orderedobject/?p=%s" % page, superuser ) response = model_admin.changelist_view(request) for result in response.context_data["cl"].result_list: counter += 1 if ascending else -1 self.assertEqual(result.id, counter) custom_site.unregister(OrderedObject) # When no order is defined at all, use the model's default ordering # (i.e. 'number'). check_results_order(ascending=True) # When an order field is defined but multiple records have the same # value for that field, make sure everything gets ordered by -pk as well. OrderedObjectAdmin.ordering = ["bool"] check_results_order() # When order fields are defined, including the pk itself, use them. OrderedObjectAdmin.ordering = ["bool", "-pk"] check_results_order() OrderedObjectAdmin.ordering = ["bool", "pk"] check_results_order(ascending=True) OrderedObjectAdmin.ordering = ["-id", "bool"] check_results_order() OrderedObjectAdmin.ordering = ["id", "bool"] check_results_order(ascending=True) @isolate_apps("admin_changelist") def test_total_ordering_optimization(self): class Related(models.Model): unique_field = models.BooleanField(unique=True) class Meta: ordering = ("unique_field",) class Model(models.Model): unique_field = models.BooleanField(unique=True) unique_nullable_field = models.BooleanField(unique=True, null=True) related = models.ForeignKey(Related, models.CASCADE) other_related = models.ForeignKey(Related, models.CASCADE) related_unique = models.OneToOneField(Related, models.CASCADE) field = models.BooleanField() other_field = models.BooleanField() null_field = models.BooleanField(null=True) class Meta: unique_together = { ("field", "other_field"), ("field", "null_field"), ("related", "other_related_id"), } class ModelAdmin(admin.ModelAdmin): def get_queryset(self, request): return Model.objects.none() request = self._mocked_authenticated_request("/", self.superuser) site = admin.AdminSite(name="admin") model_admin = ModelAdmin(Model, site) change_list = model_admin.get_changelist_instance(request) tests = ( ([], ["-pk"]), # Unique non-nullable field. (["unique_field"], ["unique_field"]), (["-unique_field"], ["-unique_field"]), # Unique nullable field. (["unique_nullable_field"], ["unique_nullable_field", "-pk"]), # Field. (["field"], ["field", "-pk"]), # Related field introspection is not implemented. (["related__unique_field"], ["related__unique_field", "-pk"]), # Related attname unique. (["related_unique_id"], ["related_unique_id"]), # Related ordering introspection is not implemented. (["related_unique"], ["related_unique", "-pk"]), # Composite unique. (["field", "-other_field"], ["field", "-other_field"]), # Composite unique nullable. (["-field", "null_field"], ["-field", "null_field", "-pk"]), # Composite unique and nullable. ( ["-field", "null_field", "other_field"], ["-field", "null_field", "other_field"], ), # Composite unique attnames. (["related_id", "-other_related_id"], ["related_id", "-other_related_id"]), # Composite unique names. (["related", "-other_related_id"], ["related", "-other_related_id", "-pk"]), ) # F() objects composite unique. total_ordering = [F("field"), F("other_field").desc(nulls_last=True)] # F() objects composite unique nullable. non_total_ordering = [F("field"), F("null_field").desc(nulls_last=True)] tests += ( (total_ordering, total_ordering), (non_total_ordering, non_total_ordering + ["-pk"]), ) for ordering, expected in tests: with self.subTest(ordering=ordering): self.assertEqual( change_list._get_deterministic_ordering(ordering), expected ) @isolate_apps("admin_changelist") def test_total_ordering_optimization_meta_constraints(self): class Related(models.Model): unique_field = models.BooleanField(unique=True) class Meta: ordering = ("unique_field",) class Model(models.Model): field_1 = models.BooleanField() field_2 = models.BooleanField() field_3 = models.BooleanField() field_4 = models.BooleanField() field_5 = models.BooleanField() field_6 = models.BooleanField() nullable_1 = models.BooleanField(null=True) nullable_2 = models.BooleanField(null=True) related_1 = models.ForeignKey(Related, models.CASCADE) related_2 = models.ForeignKey(Related, models.CASCADE) related_3 = models.ForeignKey(Related, models.CASCADE) related_4 = models.ForeignKey(Related, models.CASCADE) class Meta: constraints = [ *[ models.UniqueConstraint(fields=fields, name="".join(fields)) for fields in ( ["field_1"], ["nullable_1"], ["related_1"], ["related_2_id"], ["field_2", "field_3"], ["field_2", "nullable_2"], ["field_2", "related_3"], ["field_3", "related_4_id"], ) ], models.CheckConstraint(check=models.Q(id__gt=0), name="foo"), models.UniqueConstraint( fields=["field_5"], condition=models.Q(id__gt=10), name="total_ordering_1", ), models.UniqueConstraint( fields=["field_6"], condition=models.Q(), name="total_ordering", ), ] class ModelAdmin(admin.ModelAdmin): def get_queryset(self, request): return Model.objects.none() request = self._mocked_authenticated_request("/", self.superuser) site = admin.AdminSite(name="admin") model_admin = ModelAdmin(Model, site) change_list = model_admin.get_changelist_instance(request) tests = ( # Unique non-nullable field. (["field_1"], ["field_1"]), # Unique nullable field. (["nullable_1"], ["nullable_1", "-pk"]), # Related attname unique. (["related_1_id"], ["related_1_id"]), (["related_2_id"], ["related_2_id"]), # Related ordering introspection is not implemented. (["related_1"], ["related_1", "-pk"]), # Composite unique. (["-field_2", "field_3"], ["-field_2", "field_3"]), # Composite unique nullable. (["field_2", "-nullable_2"], ["field_2", "-nullable_2", "-pk"]), # Composite unique and nullable. ( ["field_2", "-nullable_2", "field_3"], ["field_2", "-nullable_2", "field_3"], ), # Composite field and related field name. (["field_2", "-related_3"], ["field_2", "-related_3", "-pk"]), (["field_3", "related_4"], ["field_3", "related_4", "-pk"]), # Composite field and related field attname. (["field_2", "related_3_id"], ["field_2", "related_3_id"]), (["field_3", "-related_4_id"], ["field_3", "-related_4_id"]), # Partial unique constraint is ignored. (["field_5"], ["field_5", "-pk"]), # Unique constraint with an empty condition. (["field_6"], ["field_6"]), ) for ordering, expected in tests: with self.subTest(ordering=ordering): self.assertEqual( change_list._get_deterministic_ordering(ordering), expected ) def test_dynamic_list_filter(self): """ Regression tests for ticket #17646: dynamic list_filter support. """ parent = Parent.objects.create(name="parent") for i in range(10): Child.objects.create(name="child %s" % i, parent=parent) user_noparents = self._create_superuser("noparents") user_parents = self._create_superuser("parents") # Test with user 'noparents' m = DynamicListFilterChildAdmin(Child, custom_site) request = self._mocked_authenticated_request("/child/", user_noparents) response = m.changelist_view(request) self.assertEqual(response.context_data["cl"].list_filter, ["name", "age"]) # Test with user 'parents' m = DynamicListFilterChildAdmin(Child, custom_site) request = self._mocked_authenticated_request("/child/", user_parents) response = m.changelist_view(request) self.assertEqual( response.context_data["cl"].list_filter, ("parent", "name", "age") ) def test_dynamic_search_fields(self): child = self._create_superuser("child") m = DynamicSearchFieldsChildAdmin(Child, custom_site) request = self._mocked_authenticated_request("/child/", child) response = m.changelist_view(request) self.assertEqual(response.context_data["cl"].search_fields, ("name", "age")) def test_pagination_page_range(self): """ Regression tests for ticket #15653: ensure the number of pages generated for changelist views are correct. """ # instantiating and setting up ChangeList object m = GroupAdmin(Group, custom_site) request = self.factory.get("/group/") request.user = self.superuser cl = m.get_changelist_instance(request) cl.list_per_page = 10 ELLIPSIS = cl.paginator.ELLIPSIS for number, pages, expected in [ (1, 1, []), (1, 2, [1, 2]), (6, 11, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]), (6, 12, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), (6, 13, [1, 2, 3, 4, 5, 6, 7, 8, 9, ELLIPSIS, 12, 13]), (7, 12, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), (7, 13, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]), (7, 14, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ELLIPSIS, 13, 14]), (8, 13, [1, 2, ELLIPSIS, 5, 6, 7, 8, 9, 10, 11, 12, 13]), (8, 14, [1, 2, ELLIPSIS, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]), (8, 15, [1, 2, ELLIPSIS, 5, 6, 7, 8, 9, 10, 11, ELLIPSIS, 14, 15]), ]: with self.subTest(number=number, pages=pages): # assuming exactly `pages * cl.list_per_page` objects Group.objects.all().delete() for i in range(pages * cl.list_per_page): Group.objects.create(name="test band") # setting page number and calculating page range cl.page_num = number cl.get_results(request) self.assertEqual(list(pagination(cl)["page_range"]), expected) def test_object_tools_displayed_no_add_permission(self): """ When ModelAdmin.has_add_permission() returns False, the object-tools block is still shown. """ superuser = self._create_superuser("superuser") m = EventAdmin(Event, custom_site) request = self._mocked_authenticated_request("/event/", superuser) self.assertFalse(m.has_add_permission(request)) response = m.changelist_view(request) self.assertIn('<ul class="object-tools">', response.rendered_content) # The "Add" button inside the object-tools shouldn't appear. self.assertNotIn("Add ", response.rendered_content) def test_search_help_text(self): superuser = self._create_superuser("superuser") m = BandAdmin(Band, custom_site) # search_fields without search_help_text. m.search_fields = ["name"] request = self._mocked_authenticated_request("/band/", superuser) response = m.changelist_view(request) self.assertIsNone(response.context_data["cl"].search_help_text) self.assertNotContains(response, '<div class="help id="searchbar_helptext">') # search_fields with search_help_text. m.search_help_text = "Search help text" request = self._mocked_authenticated_request("/band/", superuser) response = m.changelist_view(request) self.assertEqual( response.context_data["cl"].search_help_text, "Search help text" ) self.assertContains( response, '<div class="help" id="searchbar_helptext">Search help text</div>' ) self.assertContains( response, '<input type="text" size="40" name="q" value="" id="searchbar" ' 'aria-describedby="searchbar_helptext">', ) def test_search_bar_total_link_preserves_options(self): self.client.force_login(self.superuser) url = reverse("admin:auth_user_changelist") for data, href in ( ({"is_staff__exact": "0"}, "?"), ({"is_staff__exact": "0", IS_POPUP_VAR: "1"}, f"?{IS_POPUP_VAR}=1"), ({"is_staff__exact": "0", IS_FACETS_VAR: ""}, f"?{IS_FACETS_VAR}"), ( {"is_staff__exact": "0", IS_POPUP_VAR: "1", IS_FACETS_VAR: ""}, f"?{IS_POPUP_VAR}=1&{IS_FACETS_VAR}", ), ): with self.subTest(data=data): response = self.client.get(url, data=data) self.assertContains( response, f'0 results (<a href="{href}">1 total</a>)' ) class GetAdminLogTests(TestCase): def test_custom_user_pk_not_named_id(self): """ {% get_admin_log %} works if the user model's primary key isn't named 'id'. """ context = Context( { "user": CustomIdUser(), "log_entries": LogEntry.objects.all(), } ) template = Template( "{% load log %}{% get_admin_log 10 as admin_log for_user user %}" ) # This template tag just logs. self.assertEqual(template.render(context), "") def test_no_user(self): """{% get_admin_log %} works without specifying a user.""" user = User(username="jondoe", password="secret", email="[email protected]") user.save() ct = ContentType.objects.get_for_model(User) LogEntry.objects.log_action(user.pk, ct.pk, user.pk, repr(user), 1) context = Context({"log_entries": LogEntry.objects.all()}) t = Template( "{% load log %}" "{% get_admin_log 100 as admin_log %}" "{% for entry in admin_log %}" "{{ entry|safe }}" "{% endfor %}" ) self.assertEqual(t.render(context), "Added “<User: jondoe>”.") def test_missing_args(self): msg = "'get_admin_log' statements require two arguments" with self.assertRaisesMessage(TemplateSyntaxError, msg): Template("{% load log %}{% get_admin_log 10 as %}") def test_non_integer_limit(self): msg = "First argument to 'get_admin_log' must be an integer" with self.assertRaisesMessage(TemplateSyntaxError, msg): Template( '{% load log %}{% get_admin_log "10" as admin_log for_user user %}' ) def test_without_as(self): msg = "Second argument to 'get_admin_log' must be 'as'" with self.assertRaisesMessage(TemplateSyntaxError, msg): Template("{% load log %}{% get_admin_log 10 ad admin_log for_user user %}") def test_without_for_user(self): msg = "Fourth argument to 'get_admin_log' must be 'for_user'" with self.assertRaisesMessage(TemplateSyntaxError, msg): Template("{% load log %}{% get_admin_log 10 as admin_log foruser user %}") @override_settings(ROOT_URLCONF="admin_changelist.urls") class SeleniumTests(AdminSeleniumTestCase): available_apps = ["admin_changelist"] + AdminSeleniumTestCase.available_apps def setUp(self): User.objects.create_superuser(username="super", password="secret", email=None) def test_add_row_selection(self): """ The status line for selected rows gets updated correctly (#22038). """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get(self.live_server_url + reverse("admin:auth_user_changelist")) form_id = "#changelist-form" # Test amount of rows in the Changelist rows = self.selenium.find_elements( By.CSS_SELECTOR, "%s #result_list tbody tr" % form_id ) self.assertEqual(len(rows), 1) row = rows[0] selection_indicator = self.selenium.find_element( By.CSS_SELECTOR, "%s .action-counter" % form_id ) all_selector = self.selenium.find_element(By.ID, "action-toggle") row_selector = self.selenium.find_element( By.CSS_SELECTOR, "%s #result_list tbody tr:first-child .action-select" % form_id, ) # Test current selection self.assertEqual(selection_indicator.text, "0 of 1 selected") self.assertIs(all_selector.get_property("checked"), False) self.assertEqual(row.get_attribute("class"), "") # Select a row and check again row_selector.click() self.assertEqual(selection_indicator.text, "1 of 1 selected") self.assertIs(all_selector.get_property("checked"), True) self.assertEqual(row.get_attribute("class"), "selected") # Deselect a row and check again row_selector.click() self.assertEqual(selection_indicator.text, "0 of 1 selected") self.assertIs(all_selector.get_property("checked"), False) self.assertEqual(row.get_attribute("class"), "") def test_modifier_allows_multiple_section(self): """ Selecting a row and then selecting another row whilst holding shift should select all rows in-between. """ from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys Parent.objects.bulk_create([Parent(name="parent%d" % i) for i in range(5)]) self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_changelist_parent_changelist") ) checkboxes = self.selenium.find_elements( By.CSS_SELECTOR, "tr input.action-select" ) self.assertEqual(len(checkboxes), 5) for c in checkboxes: self.assertIs(c.get_property("checked"), False) # Check first row. Hold-shift and check next-to-last row. checkboxes[0].click() ActionChains(self.selenium).key_down(Keys.SHIFT).click(checkboxes[-2]).key_up( Keys.SHIFT ).perform() for c in checkboxes[:-2]: self.assertIs(c.get_property("checked"), True) self.assertIs(checkboxes[-1].get_property("checked"), False) def test_selection_counter_is_synced_when_page_is_shown(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get(self.live_server_url + reverse("admin:auth_user_changelist")) form_id = "#changelist-form" first_row_checkbox_selector = ( f"{form_id} #result_list tbody tr:first-child .action-select" ) selection_indicator_selector = f"{form_id} .action-counter" selection_indicator = self.selenium.find_element( By.CSS_SELECTOR, selection_indicator_selector ) row_checkbox = self.selenium.find_element( By.CSS_SELECTOR, first_row_checkbox_selector ) # Select a row. row_checkbox.click() self.assertEqual(selection_indicator.text, "1 of 1 selected") # Go to another page and get back. self.selenium.get( self.live_server_url + reverse("admin:admin_changelist_parent_changelist") ) self.selenium.back() # The selection indicator is synced with the selected checkboxes. selection_indicator = self.selenium.find_element( By.CSS_SELECTOR, selection_indicator_selector ) row_checkbox = self.selenium.find_element( By.CSS_SELECTOR, first_row_checkbox_selector ) selected_rows = 1 if row_checkbox.is_selected() else 0 self.assertEqual(selection_indicator.text, f"{selected_rows} of 1 selected") def test_select_all_across_pages(self): from selenium.webdriver.common.by import By Parent.objects.bulk_create([Parent(name="parent%d" % i) for i in range(101)]) self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_changelist_parent_changelist") ) selection_indicator = self.selenium.find_element( By.CSS_SELECTOR, ".action-counter" ) select_all_indicator = self.selenium.find_element( By.CSS_SELECTOR, ".actions .all" ) question = self.selenium.find_element(By.CSS_SELECTOR, ".actions > .question") clear = self.selenium.find_element(By.CSS_SELECTOR, ".actions > .clear") select_all = self.selenium.find_element(By.ID, "action-toggle") select_across = self.selenium.find_elements(By.NAME, "select_across") self.assertIs(question.is_displayed(), False) self.assertIs(clear.is_displayed(), False) self.assertIs(select_all.get_property("checked"), False) for hidden_input in select_across: self.assertEqual(hidden_input.get_property("value"), "0") self.assertIs(selection_indicator.is_displayed(), True) self.assertEqual(selection_indicator.text, "0 of 100 selected") self.assertIs(select_all_indicator.is_displayed(), False) select_all.click() self.assertIs(question.is_displayed(), True) self.assertIs(clear.is_displayed(), False) self.assertIs(select_all.get_property("checked"), True) for hidden_input in select_across: self.assertEqual(hidden_input.get_property("value"), "0") self.assertIs(selection_indicator.is_displayed(), True) self.assertEqual(selection_indicator.text, "100 of 100 selected") self.assertIs(select_all_indicator.is_displayed(), False) question.click() self.assertIs(question.is_displayed(), False) self.assertIs(clear.is_displayed(), True) self.assertIs(select_all.get_property("checked"), True) for hidden_input in select_across: self.assertEqual(hidden_input.get_property("value"), "1") self.assertIs(selection_indicator.is_displayed(), False) self.assertIs(select_all_indicator.is_displayed(), True) clear.click() self.assertIs(question.is_displayed(), False) self.assertIs(clear.is_displayed(), False) self.assertIs(select_all.get_property("checked"), False) for hidden_input in select_across: self.assertEqual(hidden_input.get_property("value"), "0") self.assertIs(selection_indicator.is_displayed(), True) self.assertEqual(selection_indicator.text, "0 of 100 selected") self.assertIs(select_all_indicator.is_displayed(), False) def test_actions_warn_on_pending_edits(self): from selenium.webdriver.common.by import By Parent.objects.create(name="foo") self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_changelist_parent_changelist") ) name_input = self.selenium.find_element(By.ID, "id_form-0-name") name_input.clear() name_input.send_keys("bar") self.selenium.find_element(By.ID, "action-toggle").click() self.selenium.find_element(By.NAME, "index").click() # Go alert = self.selenium.switch_to.alert try: self.assertEqual( alert.text, "You have unsaved changes on individual editable fields. If you " "run an action, your unsaved changes will be lost.", ) finally: alert.dismiss() def test_save_with_changes_warns_on_pending_action(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select Parent.objects.create(name="parent") self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_changelist_parent_changelist") ) name_input = self.selenium.find_element(By.ID, "id_form-0-name") name_input.clear() name_input.send_keys("other name") Select(self.selenium.find_element(By.NAME, "action")).select_by_value( "delete_selected" ) self.selenium.find_element(By.NAME, "_save").click() alert = self.selenium.switch_to.alert try: self.assertEqual( alert.text, "You have selected an action, but you haven’t saved your " "changes to individual fields yet. Please click OK to save. " "You’ll need to re-run the action.", ) finally: alert.dismiss() def test_save_without_changes_warns_on_pending_action(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select Parent.objects.create(name="parent") self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_changelist_parent_changelist") ) Select(self.selenium.find_element(By.NAME, "action")).select_by_value( "delete_selected" ) self.selenium.find_element(By.NAME, "_save").click() alert = self.selenium.switch_to.alert try: self.assertEqual( alert.text, "You have selected an action, and you haven’t made any " "changes on individual fields. You’re probably looking for " "the Go button rather than the Save button.", ) finally: alert.dismiss() def test_collapse_filters(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get(self.live_server_url + reverse("admin:auth_user_changelist")) # The UserAdmin has 3 field filters by default: "staff status", # "superuser status", and "active". details = self.selenium.find_elements(By.CSS_SELECTOR, "details") # All filters are opened at first. for detail in details: self.assertTrue(detail.get_attribute("open")) # Collapse "staff' and "superuser" filters. for detail in details[:2]: summary = detail.find_element(By.CSS_SELECTOR, "summary") summary.click() self.assertFalse(detail.get_attribute("open")) # Filters are in the same state after refresh. self.selenium.refresh() self.assertFalse( self.selenium.find_element( By.CSS_SELECTOR, "[data-filter-title='staff status']" ).get_attribute("open") ) self.assertFalse( self.selenium.find_element( By.CSS_SELECTOR, "[data-filter-title='superuser status']" ).get_attribute("open") ) self.assertTrue( self.selenium.find_element( By.CSS_SELECTOR, "[data-filter-title='active']" ).get_attribute("open") ) # Collapse a filter on another view (Bands). self.selenium.get( self.live_server_url + reverse("admin:admin_changelist_band_changelist") ) self.selenium.find_element(By.CSS_SELECTOR, "summary").click() # Go to Users view and then, back again to Bands view. self.selenium.get(self.live_server_url + reverse("admin:auth_user_changelist")) self.selenium.get( self.live_server_url + reverse("admin:admin_changelist_band_changelist") ) # The filter remains in the same state. self.assertFalse( self.selenium.find_element( By.CSS_SELECTOR, "[data-filter-title='number of members']", ).get_attribute("open") ) def test_collapse_filter_with_unescaped_title(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") changelist_url = reverse("admin:admin_changelist_proxyuser_changelist") self.selenium.get(self.live_server_url + changelist_url) # Title is escaped. filter_title = self.selenium.find_element( By.CSS_SELECTOR, "[data-filter-title='It\\'s OK']" ) filter_title.find_element(By.CSS_SELECTOR, "summary").click() self.assertFalse(filter_title.get_attribute("open")) # Filter is in the same state after refresh. self.selenium.refresh() self.assertFalse( self.selenium.find_element( By.CSS_SELECTOR, "[data-filter-title='It\\'s OK']" ).get_attribute("open") )
a5925ad273413760225c8e2055abeaee0fc6b7cf9179955956d9f1aa46b33c8f
import copy import datetime import json import uuid from django.core.exceptions import NON_FIELD_ERRORS from django.core.files.uploadedfile import SimpleUploadedFile from django.core.validators import MaxValueValidator, RegexValidator from django.forms import ( BooleanField, CharField, CheckboxSelectMultiple, ChoiceField, DateField, DateTimeField, EmailField, FileField, FileInput, FloatField, Form, HiddenInput, ImageField, IntegerField, MultipleChoiceField, MultipleHiddenInput, MultiValueField, MultiWidget, NullBooleanField, PasswordInput, RadioSelect, Select, SplitDateTimeField, SplitHiddenDateTimeWidget, Textarea, TextInput, TimeField, ValidationError, forms, ) from django.forms.renderers import DjangoTemplates, get_default_renderer from django.forms.utils import ErrorList from django.http import QueryDict from django.template import Context, Template from django.test import SimpleTestCase from django.test.utils import override_settings from django.utils.datastructures import MultiValueDict from django.utils.safestring import mark_safe from . import jinja2_tests class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[("P", "Python"), ("J", "Java")], widget=RadioSelect) class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class PersonNew(Form): first_name = CharField(widget=TextInput(attrs={"id": "first_name_id"})) last_name = CharField() birthday = DateField() class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=CheckboxSelectMultiple, ) class MultiValueDictLike(dict): def getlist(self, key): return [self[key]] class FormsTestCase(SimpleTestCase): # A Form is a collection of Fields. It knows how to validate a set of data and it # knows how to render itself in a couple of default ways (e.g., an HTML table). # You can pass it data in __init__(), as a dictionary. def test_form(self): # Pass a dictionary to a Form's __init__(). p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"} ) self.assertTrue(p.is_bound) self.assertEqual(p.errors, {}) self.assertIsInstance(p.errors, dict) self.assertTrue(p.is_valid()) self.assertHTMLEqual(p.errors.as_ul(), "") self.assertEqual(p.errors.as_text(), "") 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"]), '<input type="text" name="first_name" value="John" id="id_first_name" ' "required>", ) self.assertHTMLEqual( str(p["last_name"]), '<input type="text" name="last_name" value="Lennon" id="id_last_name" ' "required>", ) self.assertHTMLEqual( str(p["birthday"]), '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required>", ) msg = ( "Key 'nonexistentfield' not found in 'Person'. Choices are: birthday, " "first_name, last_name." ) with self.assertRaisesMessage(KeyError, msg): p["nonexistentfield"] form_output = [] for boundfield in p: form_output.append(str(boundfield)) self.assertHTMLEqual( "\n".join(form_output), '<input type="text" name="first_name" value="John" id="id_first_name" ' "required>" '<input type="text" name="last_name" value="Lennon" id="id_last_name" ' "required>" '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required>", ) form_output = [] for boundfield in p: form_output.append([boundfield.label, boundfield.data]) self.assertEqual( form_output, [ ["First name", "John"], ["Last name", "Lennon"], ["Birthday", "1940-10-9"], ], ) self.assertHTMLEqual( str(p), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" value="John" required id="id_first_name"></div><div>' '<label for="id_last_name">Last name:</label><input type="text" ' 'name="last_name" value="Lennon" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label><input type="text" ' 'name="birthday" value="1940-10-9" required id="id_birthday"></div>', ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" value="John" required id="id_first_name"></div><div>' '<label for="id_last_name">Last name:</label><input type="text" ' 'name="last_name" value="Lennon" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label><input type="text" ' 'name="birthday" value="1940-10-9" required id="id_birthday"></div>', ) def test_empty_dict(self): # Empty dictionaries are valid, too. p = Person({}) self.assertTrue(p.is_bound) self.assertEqual(p.errors["first_name"], ["This field is required."]) self.assertEqual(p.errors["last_name"], ["This field is required."]) self.assertEqual(p.errors["birthday"], ["This field is required."]) self.assertFalse(p.is_valid()) self.assertEqual(p.cleaned_data, {}) self.assertHTMLEqual( str(p), '<div><label for="id_first_name">First name:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="first_name" required id="id_first_name"></div>' '<div><label for="id_last_name">Last name:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="last_name" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="birthday" required id="id_birthday"></div>', ) self.assertHTMLEqual( p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td> <ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="birthday" id="id_birthday" required></td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> <label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> <label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> <label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></li>""", ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="first_name" required id="id_first_name"></div>' '<div><label for="id_last_name">Last name:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="last_name" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="birthday" required id="id_birthday"></div>', ) def test_empty_querydict_args(self): data = QueryDict() files = QueryDict() p = Person(data, files) self.assertIs(p.data, data) self.assertIs(p.files, files) def test_unbound_form(self): # If you don't pass any values to the Form's __init__(), or if you pass None, # the Form will be considered unbound and won't do any validation. Form.errors # will be an empty dictionary *but* Form.is_valid() will return False. p = Person() self.assertFalse(p.is_bound) self.assertEqual(p.errors, {}) self.assertFalse(p.is_valid()) with self.assertRaises(AttributeError): p.cleaned_data self.assertHTMLEqual( str(p), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" id="id_first_name" required></div><div><label ' 'for="id_last_name">Last name:</label><input type="text" name="last_name" ' 'id="id_last_name" required></div><div><label for="id_birthday">' 'Birthday:</label><input type="text" name="birthday" id="id_birthday" ' "required></div>", ) self.assertHTMLEqual( p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" id="id_birthday" required></td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></li>""", ) self.assertHTMLEqual( p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" id="id_first_name" required></div><div><label ' 'for="id_last_name">Last name:</label><input type="text" name="last_name" ' 'id="id_last_name" required></div><div><label for="id_birthday">' 'Birthday:</label><input type="text" name="birthday" id="id_birthday" ' "required></div>", ) 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(), '<tr><th><label for="id_first_name">First name:</label></th><td>' '<input type="text" name="first_name" value="John" id="id_first_name" ' "required></td></tr>\n" '<tr><th><label for="id_last_name">Last name:</label>' '</th><td><input type="text" name="last_name" ' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111"' 'id="id_last_name" required></td></tr>\n' '<tr><th><label for="id_birthday">Birthday:</label></th><td>' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required></td></tr>", ) self.assertHTMLEqual( p.as_ul(), '<li><label for="id_first_name">First name:</label> ' '<input type="text" name="first_name" value="John" id="id_first_name" ' "required></li>\n" '<li><label for="id_last_name">Last name:</label> ' '<input type="text" name="last_name" ' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ' 'id="id_last_name" required></li>\n' '<li><label for="id_birthday">Birthday:</label> ' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required></li>", ) self.assertHTMLEqual( p.as_p(), '<p><label for="id_first_name">First name:</label> ' '<input type="text" name="first_name" value="John" id="id_first_name" ' "required></p>\n" '<p><label for="id_last_name">Last name:</label> ' '<input type="text" name="last_name" ' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ' 'id="id_last_name" required></p>\n' '<p><label for="id_birthday">Birthday:</label> ' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required></p>", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label>' '<input type="text" name="first_name" value="John" id="id_first_name" ' 'required></div><div><label for="id_last_name">Last name:</label>' '<input type="text" name="last_name"' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ' 'id="id_last_name" required></div><div><label for="id_birthday">' 'Birthday:</label><input type="text" name="birthday" value="1940-10-9" ' 'id="id_birthday" required></div>', ) 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.assertEqual( 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(), '<ul class="errorlist"><li>This field is required.</li></ul>', ) self.assertEqual(p["first_name"].errors.as_text(), "* This field is required.") p = Person() self.assertHTMLEqual( str(p["first_name"]), '<input type="text" name="first_name" id="id_first_name" required>', ) self.assertHTMLEqual( str(p["last_name"]), '<input type="text" name="last_name" id="id_last_name" required>', ) self.assertHTMLEqual( str(p["birthday"]), '<input type="text" name="birthday" id="id_birthday" required>', ) def test_cleaned_data_only_fields(self): # cleaned_data will always *only* contain a key for fields defined in the # 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", } p = Person(data) self.assertTrue(p.is_valid()) 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)) def test_optional_data(self): # cleaned_data will include a key and value for *all* fields defined in # the Form, even if the Form's data didn't include a value for fields # that are not required. In this example, the data dictionary doesn't # include a value for the "nick_name" field, but cleaned_data includes # it. For CharFields, it's set to the empty string. class OptionalPersonForm(Form): first_name = CharField() last_name = CharField() nick_name = CharField(required=False) data = {"first_name": "John", "last_name": "Lennon"} f = OptionalPersonForm(data) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["nick_name"], "") self.assertEqual(f.cleaned_data["first_name"], "John") self.assertEqual(f.cleaned_data["last_name"], "Lennon") # For DateFields, it's set to None. class OptionalPersonForm(Form): first_name = CharField() last_name = CharField() birth_date = DateField(required=False) data = {"first_name": "John", "last_name": "Lennon"} f = OptionalPersonForm(data) self.assertTrue(f.is_valid()) self.assertIsNone(f.cleaned_data["birth_date"]) self.assertEqual(f.cleaned_data["first_name"], "John") self.assertEqual(f.cleaned_data["last_name"], "Lennon") def test_auto_id(self): # "auto_id" tells the Form to add an "id" attribute to each form # element. If it's a string that contains '%s', Django will use that as # a format string into which the field's name will be inserted. It will # also put a <label> around the human-readable labels for a field. p = Person(auto_id="%s_id") self.assertHTMLEqual( p.as_table(), """<tr><th><label for="first_name_id">First name:</label></th><td> <input type="text" name="first_name" id="first_name_id" required></td></tr> <tr><th><label for="last_name_id">Last name:</label></th><td> <input type="text" name="last_name" id="last_name_id" required></td></tr> <tr><th><label for="birthday_id">Birthday:</label></th><td> <input type="text" name="birthday" id="birthday_id" required></td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" required></li> <li><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" required></li> <li><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" required></li>""", ) self.assertHTMLEqual( p.as_p(), """<p><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" required></p> <p><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" required></p> <p><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" required></p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="first_name_id">First name:</label><input type="text" ' 'name="first_name" id="first_name_id" required></div><div><label ' 'for="last_name_id">Last name:</label><input type="text" ' 'name="last_name" id="last_name_id" required></div><div><label ' 'for="birthday_id">Birthday:</label><input type="text" name="birthday" ' 'id="birthday_id" required></div>', ) def test_auto_id_true(self): # If auto_id is any True value whose str() does not contain '%s', the "id" # attribute will be the name of the field. p = Person(auto_id=True) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name">First name:</label> <input type="text" name="first_name" id="first_name" required></li> <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" required></li> <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" required></li>""", ) def test_auto_id_false(self): # If auto_id is any False value, an "id" attribute won't be output unless it # was manually entered. p = Person(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li>""", ) def test_id_on_field(self): # In this example, auto_id is False, but the "id" attribute for the "first_name" # field is given. Also note that field gets a <label>, while the others don't. p = PersonNew(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li>""", ) def test_auto_id_on_form_and_field(self): # If the "id" attribute is specified in the Form and auto_id is True, the "id" # attribute in the Form gets precedence. p = PersonNew(auto_id=True) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" required></li> <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" required></li> <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" required></li>""", ) def test_various_boolean_values(self): class SignupForm(Form): email = EmailField() get_spam = BooleanField() f = SignupForm(auto_id=False) self.assertHTMLEqual( str(f["email"]), '<input type="email" name="email" maxlength="320" required>', ) self.assertHTMLEqual( str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>' ) f = SignupForm({"email": "[email protected]", "get_spam": True}, auto_id=False) self.assertHTMLEqual( str(f["email"]), '<input type="email" name="email" maxlength="320" value="[email protected]" ' "required>", ) self.assertHTMLEqual( str(f["get_spam"]), '<input checked type="checkbox" name="get_spam" required>', ) # 'True' or 'true' should be rendered without a value attribute f = SignupForm({"email": "[email protected]", "get_spam": "True"}, auto_id=False) self.assertHTMLEqual( str(f["get_spam"]), '<input checked type="checkbox" name="get_spam" required>', ) f = SignupForm({"email": "[email protected]", "get_spam": "true"}, auto_id=False) self.assertHTMLEqual( str(f["get_spam"]), '<input checked type="checkbox" name="get_spam" required>', ) # A value of 'False' or 'false' should be rendered unchecked f = SignupForm( {"email": "[email protected]", "get_spam": "False"}, auto_id=False ) self.assertHTMLEqual( str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>' ) f = SignupForm( {"email": "[email protected]", "get_spam": "false"}, auto_id=False ) self.assertHTMLEqual( str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>' ) # A value of '0' should be interpreted as a True value (#16820) f = SignupForm({"email": "[email protected]", "get_spam": "0"}) self.assertTrue(f.is_valid()) self.assertTrue(f.cleaned_data.get("get_spam")) def test_widget_output(self): # Any Field can have a Widget class passed to its constructor: class ContactForm(Form): subject = CharField() message = CharField(widget=Textarea) f = ContactForm(auto_id=False) self.assertHTMLEqual( str(f["subject"]), '<input type="text" name="subject" required>' ) self.assertHTMLEqual( str(f["message"]), '<textarea name="message" rows="10" cols="40" required></textarea>', ) # as_textarea(), as_text() and as_hidden() are shortcuts for changing the output # widget type: self.assertHTMLEqual( f["subject"].as_textarea(), '<textarea name="subject" rows="10" cols="40" required></textarea>', ) self.assertHTMLEqual( f["message"].as_text(), '<input type="text" name="message" required>' ) self.assertHTMLEqual( f["message"].as_hidden(), '<input type="hidden" name="message">' ) # The 'widget' parameter to a Field can also be an instance: class ContactForm(Form): subject = CharField() message = CharField(widget=Textarea(attrs={"rows": 80, "cols": 20})) f = ContactForm(auto_id=False) self.assertHTMLEqual( str(f["message"]), '<textarea name="message" rows="80" cols="20" required></textarea>', ) # Instance-level attrs are *not* carried over to as_textarea(), as_text() and # as_hidden(): self.assertHTMLEqual( f["message"].as_text(), '<input type="text" name="message" required>' ) f = ContactForm({"subject": "Hello", "message": "I love you."}, auto_id=False) self.assertHTMLEqual( f["subject"].as_textarea(), '<textarea rows="10" cols="40" name="subject" required>Hello</textarea>', ) self.assertHTMLEqual( f["message"].as_text(), '<input type="text" name="message" value="I love you." required>', ) self.assertHTMLEqual( f["message"].as_hidden(), '<input type="hidden" name="message" value="I love you.">', ) def test_forms_with_choices(self): # For a form with a <select>, use ChoiceField: class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[("P", "Python"), ("J", "Java")]) f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select name="language"> <option value="P" selected>Python</option> <option value="J">Java</option> </select>""", ) # A subtlety: If one of the choices' value is the empty string and the form is # unbound, then the <option> for the empty-string choice will get selected. class FrameworkForm(Form): name = CharField() language = ChoiceField( choices=[("", "------"), ("P", "Python"), ("J", "Java")] ) f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select name="language" required> <option value="" selected>------</option> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) # You can specify widget attributes in the Widget constructor. class FrameworkForm(Form): name = CharField() language = ChoiceField( choices=[("P", "Python"), ("J", "Java")], widget=Select(attrs={"class": "foo"}), ) f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select class="foo" name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select class="foo" name="language"> <option value="P" selected>Python</option> <option value="J">Java</option> </select>""", ) # When passing a custom widget instance to ChoiceField, note that setting # 'choices' on the widget is meaningless. The widget will use the choices # defined on the Field, not the ones defined on the Widget. class FrameworkForm(Form): name = CharField() language = ChoiceField( choices=[("P", "Python"), ("J", "Java")], widget=Select( choices=[("R", "Ruby"), ("P", "Perl")], attrs={"class": "foo"} ), ) f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select class="foo" name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select class="foo" name="language"> <option value="P" selected>Python</option> <option value="J">Java</option> </select>""", ) # You can set a ChoiceField's choices after the fact. class FrameworkForm(Form): name = CharField() language = ChoiceField() f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select name="language"> </select>""", ) f.fields["language"].choices = [("P", "Python"), ("J", "Java")] self.assertHTMLEqual( str(f["language"]), """<select name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) def test_forms_with_radio(self): # Add widget=RadioSelect to use that widget with a ChoiceField. f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<div> <div><label><input type="radio" name="language" value="P" required> Python</label></div> <div><label><input type="radio" name="language" value="J" required> Java</label></div> </div>""", ) self.assertHTMLEqual( f.as_table(), """<tr><th>Name:</th><td><input type="text" name="name" required></td></tr> <tr><th>Language:</th><td><div> <div><label><input type="radio" name="language" value="P" required> Python</label></div> <div><label><input type="radio" name="language" value="J" required> Java</label></div> </div></td></tr>""", ) self.assertHTMLEqual( f.as_ul(), """<li>Name: <input type="text" name="name" required></li> <li>Language: <div> <div><label><input type="radio" name="language" value="P" required> Python</label></div> <div><label><input type="radio" name="language" value="J" required> Java</label></div> </div></li>""", ) # Need an auto_id to generate legend. self.assertHTMLEqual( f.render(f.template_name_div), '<div> Name: <input type="text" name="name" required></div><div><fieldset>' 'Language:<div><div><label><input type="radio" name="language" value="P" ' 'required> Python</label></div><div><label><input type="radio" ' 'name="language" value="J" required> Java</label></div></div></fieldset>' "</div>", ) # Regarding auto_id and <label>, RadioSelect is a special case. Each # radio button gets a distinct ID, formed by appending an underscore # plus the button's zero-based index. f = FrameworkForm(auto_id="id_%s") self.assertHTMLEqual( str(f["language"]), """ <div id="id_language"> <div><label for="id_language_0"> <input type="radio" id="id_language_0" value="P" name="language" required> Python</label></div> <div><label for="id_language_1"> <input type="radio" id="id_language_1" value="J" name="language" required> Java</label></div> </div>""", ) # 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 **not** point to the ID of the *first* radio button to improve # accessibility for screen reader users. self.assertHTMLEqual( f.as_table(), """ <tr><th><label for="id_name">Name:</label></th><td> <input type="text" name="name" id="id_name" required></td></tr> <tr><th><label>Language:</label></th><td><div id="id_language"> <div><label for="id_language_0"> <input type="radio" id="id_language_0" value="P" name="language" required> Python</label></div> <div><label for="id_language_1"> <input type="radio" id="id_language_1" value="J" name="language" required> Java</label></div> </div></td></tr>""", ) self.assertHTMLEqual( f.as_ul(), """ <li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></li> <li><label>Language:</label> <div id="id_language"> <div><label for="id_language_0"> <input type="radio" id="id_language_0" value="P" name="language" required> Python</label></div> <div><label for="id_language_1"> <input type="radio" id="id_language_1" value="J" name="language" required> Java</label></div> </div></li> """, ) self.assertHTMLEqual( f.as_p(), """ <p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></p> <p><label>Language:</label> <div id="id_language"> <div><label for="id_language_0"> <input type="radio" id="id_language_0" value="P" name="language" required> Python</label></div> <div><label for="id_language_1"> <input type="radio" id="id_language_1" value="J" name="language" required> Java</label></div> </div></p> """, ) self.assertHTMLEqual( f.render(f.template_name_div), '<div><label for="id_name">Name:</label><input type="text" name="name" ' 'required id="id_name"></div><div><fieldset><legend>Language:</legend>' '<div id="id_language"><div><label for="id_language_0"><input ' 'type="radio" name="language" value="P" required id="id_language_0">' 'Python</label></div><div><label for="id_language_1"><input type="radio" ' 'name="language" value="J" required id="id_language_1">Java</label></div>' "</div></fieldset></div>", ) def test_form_with_iterable_boundfield(self): class BeatleForm(Form): 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"]), '<label><input type="radio" name="name" value="john" required> John</label>' '<label><input type="radio" name="name" value="paul" required> Paul</label>' '<label><input type="radio" name="name" value="george" required> George' "</label>" '<label><input type="radio" name="name" value="ringo" required> Ringo' "</label>", ) self.assertHTMLEqual( "\n".join("<div>%s</div>" % bf for bf in f["name"]), """ <div><label> <input type="radio" name="name" value="john" required> John</label></div> <div><label> <input type="radio" name="name" value="paul" required> Paul</label></div> <div><label> <input type="radio" name="name" value="george" required> George </label></div> <div><label> <input type="radio" name="name" value="ringo" required> Ringo</label></div> """, ) def test_form_with_iterable_boundfield_id(self): class BeatleForm(Form): name = ChoiceField( choices=[ ("john", "John"), ("paul", "Paul"), ("george", "George"), ("ringo", "Ringo"), ], widget=RadioSelect, ) fields = list(BeatleForm()["name"]) self.assertEqual(len(fields), 4) self.assertEqual(fields[0].id_for_label, "id_name_0") self.assertEqual(fields[0].choice_label, "John") self.assertHTMLEqual( fields[0].tag(), '<input type="radio" name="name" value="john" id="id_name_0" required>', ) self.assertHTMLEqual( str(fields[0]), '<label for="id_name_0"><input type="radio" name="name" ' 'value="john" id="id_name_0" required> John</label>', ) self.assertEqual(fields[1].id_for_label, "id_name_1") self.assertEqual(fields[1].choice_label, "Paul") self.assertHTMLEqual( fields[1].tag(), '<input type="radio" name="name" value="paul" id="id_name_1" required>', ) self.assertHTMLEqual( str(fields[1]), '<label for="id_name_1"><input type="radio" name="name" ' 'value="paul" id="id_name_1" required> Paul</label>', ) def test_iterable_boundfield_select(self): class BeatleForm(Form): name = ChoiceField( choices=[ ("john", "John"), ("paul", "Paul"), ("george", "George"), ("ringo", "Ringo"), ] ) fields = list(BeatleForm(auto_id=False)["name"]) self.assertEqual(len(fields), 4) self.assertIsNone(fields[0].id_for_label) self.assertEqual(fields[0].choice_label, "John") self.assertHTMLEqual(fields[0].tag(), '<option value="john">John</option>') self.assertHTMLEqual(str(fields[0]), '<option value="john">John</option>') def test_form_with_noniterable_boundfield(self): # You can iterate over any BoundField, not just those with widget=RadioSelect. class BeatleForm(Form): name = CharField() f = BeatleForm(auto_id=False) self.assertHTMLEqual( "\n".join(str(bf) for bf in f["name"]), '<input type="text" name="name" required>', ) def test_boundfield_slice(self): class BeatleForm(Form): name = ChoiceField( choices=[ ("john", "John"), ("paul", "Paul"), ("george", "George"), ("ringo", "Ringo"), ], widget=RadioSelect, ) f = BeatleForm() bf = f["name"] self.assertEqual( [str(item) for item in bf[1:]], [str(bf[1]), str(bf[2]), str(bf[3])], ) def test_boundfield_invalid_index(self): class TestForm(Form): name = ChoiceField(choices=[]) field = TestForm()["name"] msg = "BoundField indices must be integers or slices, not str." with self.assertRaisesMessage(TypeError, msg): field["foo"] def test_boundfield_bool(self): """BoundField without any choices (subwidgets) evaluates to True.""" class TestForm(Form): name = ChoiceField(choices=[]) self.assertIs(bool(TestForm()["name"]), True) def test_forms_with_multiple_choice(self): # MultipleChoiceField is a special case, as its data is required to be a list: class SongForm(Form): name = CharField() composers = MultipleChoiceField() f = SongForm(auto_id=False) self.assertHTMLEqual( str(f["composers"]), """<select multiple name="composers" required> </select>""", ) class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")] ) f = SongForm(auto_id=False) self.assertHTMLEqual( str(f["composers"]), """<select multiple name="composers" required> <option value="J">John Lennon</option> <option value="P">Paul McCartney</option> </select>""", ) f = SongForm({"name": "Yesterday", "composers": ["P"]}, auto_id=False) self.assertHTMLEqual( str(f["name"]), '<input type="text" name="name" value="Yesterday" required>' ) self.assertHTMLEqual( str(f["composers"]), """<select multiple name="composers" required> <option value="J">John Lennon</option> <option value="P" selected>Paul McCartney</option> </select>""", ) f = SongForm() self.assertHTMLEqual( f.as_table(), '<tr><th><label for="id_name">Name:</label></th>' '<td><input type="text" name="name" required id="id_name"></td>' '</tr><tr><th><label for="id_composers">Composers:</label></th>' '<td><select name="composers" required id="id_composers" multiple>' '<option value="J">John Lennon</option>' '<option value="P">Paul McCartney</option>' "</select></td></tr>", ) self.assertHTMLEqual( f.as_ul(), '<li><label for="id_name">Name:</label>' '<input type="text" name="name" required id="id_name"></li>' '<li><label for="id_composers">Composers:</label>' '<select name="composers" required id="id_composers" multiple>' '<option value="J">John Lennon</option>' '<option value="P">Paul McCartney</option>' "</select></li>", ) self.assertHTMLEqual( f.as_p(), '<p><label for="id_name">Name:</label>' '<input type="text" name="name" required id="id_name"></p>' '<p><label for="id_composers">Composers:</label>' '<select name="composers" required id="id_composers" multiple>' '<option value="J">John Lennon</option>' '<option value="P">Paul McCartney</option>' "</select></p>", ) self.assertHTMLEqual( f.render(f.template_name_div), '<div><label for="id_name">Name:</label><input type="text" name="name" ' 'required id="id_name"></div><div><label for="id_composers">Composers:' '</label><select name="composers" required id="id_composers" multiple>' '<option value="J">John Lennon</option><option value="P">Paul McCartney' "</option></select></div>", ) def test_multiple_checkbox_render(self): f = SongForm() self.assertHTMLEqual( f.as_table(), '<tr><th><label for="id_name">Name:</label></th><td>' '<input type="text" name="name" required id="id_name"></td></tr>' '<tr><th><label>Composers:</label></th><td><div id="id_composers">' '<div><label for="id_composers_0">' '<input type="checkbox" name="composers" value="J" ' 'id="id_composers_0">John Lennon</label></div>' '<div><label for="id_composers_1">' '<input type="checkbox" name="composers" value="P" ' 'id="id_composers_1">Paul McCartney</label></div>' "</div></td></tr>", ) self.assertHTMLEqual( f.as_ul(), '<li><label for="id_name">Name:</label>' '<input type="text" name="name" required id="id_name"></li>' '<li><label>Composers:</label><div id="id_composers">' '<div><label for="id_composers_0">' '<input type="checkbox" name="composers" value="J" ' 'id="id_composers_0">John Lennon</label></div>' '<div><label for="id_composers_1">' '<input type="checkbox" name="composers" value="P" ' 'id="id_composers_1">Paul McCartney</label></div>' "</div></li>", ) self.assertHTMLEqual( f.as_p(), '<p><label for="id_name">Name:</label>' '<input type="text" name="name" required id="id_name"></p>' '<p><label>Composers:</label><div id="id_composers">' '<div><label for="id_composers_0">' '<input type="checkbox" name="composers" value="J" ' 'id="id_composers_0">John Lennon</label></div>' '<div><label for="id_composers_1">' '<input type="checkbox" name="composers" value="P" ' 'id="id_composers_1">Paul McCartney</label></div>' "</div></p>", ) self.assertHTMLEqual( f.render(f.template_name_div), '<div><label for="id_name">Name:</label><input type="text" name="name" ' 'required id="id_name"></div><div><fieldset><legend>Composers:</legend>' '<div id="id_composers"><div><label for="id_composers_0"><input ' 'type="checkbox" name="composers" value="J" id="id_composers_0">' 'John Lennon</label></div><div><label for="id_composers_1"><input ' 'type="checkbox" name="composers" value="P" id="id_composers_1">' "Paul McCartney</label></div></div></fieldset></div>", ) def test_form_with_disabled_fields(self): class PersonForm(Form): name = CharField() birthday = DateField(disabled=True) class PersonFormFieldInitial(Form): name = CharField() birthday = DateField(disabled=True, initial=datetime.date(1974, 8, 16)) # Disabled fields are generally not transmitted by user agents. # The value from the form's initial data is used. f1 = PersonForm( {"name": "John Doe"}, initial={"birthday": datetime.date(1974, 8, 16)} ) f2 = PersonFormFieldInitial({"name": "John Doe"}) for form in (f1, f2): self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data, {"birthday": datetime.date(1974, 8, 16), "name": "John Doe"}, ) # Values provided in the form's data are ignored. data = {"name": "John Doe", "birthday": "1984-11-10"} f1 = PersonForm(data, initial={"birthday": datetime.date(1974, 8, 16)}) f2 = PersonFormFieldInitial(data) for form in (f1, f2): self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data, {"birthday": datetime.date(1974, 8, 16), "name": "John Doe"}, ) # Initial data remains present on invalid forms. data = {} f1 = PersonForm(data, initial={"birthday": datetime.date(1974, 8, 16)}) f2 = PersonFormFieldInitial(data) for form in (f1, f2): self.assertFalse(form.is_valid()) self.assertEqual(form["birthday"].value(), datetime.date(1974, 8, 16)) def test_hidden_data(self): class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")] ) # MultipleChoiceField rendered as_hidden() is a special case. Because it can # have multiple values, its as_hidden() renders multiple <input type="hidden"> # tags. f = SongForm({"name": "Yesterday", "composers": ["P"]}, auto_id=False) self.assertHTMLEqual( f["composers"].as_hidden(), '<input type="hidden" name="composers" value="P">', ) f = SongForm({"name": "From Me To You", "composers": ["P", "J"]}, auto_id=False) self.assertHTMLEqual( f["composers"].as_hidden(), """<input type="hidden" name="composers" value="P"> <input type="hidden" name="composers" value="J">""", ) # DateTimeField rendered as_hidden() is special too class MessageForm(Form): when = SplitDateTimeField() f = MessageForm({"when_0": "1992-01-01", "when_1": "01:01"}) self.assertTrue(f.is_valid()) self.assertHTMLEqual( str(f["when"]), '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" ' "required>" '<input type="text" name="when_1" value="01:01" id="id_when_1" required>', ) self.assertHTMLEqual( f["when"].as_hidden(), '<input type="hidden" name="when_0" value="1992-01-01" id="id_when_0">' '<input type="hidden" name="when_1" value="01:01" id="id_when_1">', ) def test_multiple_choice_checkbox(self): # MultipleChoiceField can also be used with the CheckboxSelectMultiple widget. f = SongForm(auto_id=False) self.assertHTMLEqual( str(f["composers"]), """ <div> <div><label><input type="checkbox" name="composers" value="J"> John Lennon</label></div> <div><label><input type="checkbox" name="composers" value="P"> Paul McCartney</label></div> </div> """, ) f = SongForm({"composers": ["J"]}, auto_id=False) self.assertHTMLEqual( str(f["composers"]), """ <div> <div><label><input checked type="checkbox" name="composers" value="J"> John Lennon</label></div> <div><label><input type="checkbox" name="composers" value="P"> Paul McCartney</label></div> </div> """, ) f = SongForm({"composers": ["J", "P"]}, auto_id=False) self.assertHTMLEqual( str(f["composers"]), """ <div> <div><label><input checked type="checkbox" name="composers" value="J"> John Lennon</label></div> <div><label><input checked type="checkbox" name="composers" value="P"> Paul McCartney</label></div> </div> """, ) def test_checkbox_auto_id(self): # Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox # gets a distinct ID, formed by appending an underscore plus the checkbox's # zero-based index. class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=CheckboxSelectMultiple, ) f = SongForm(auto_id="%s_id") self.assertHTMLEqual( str(f["composers"]), """ <div id="composers_id"> <div><label for="composers_id_0"> <input type="checkbox" name="composers" value="J" id="composers_id_0"> John Lennon</label></div> <div><label for="composers_id_1"> <input type="checkbox" name="composers" value="P" id="composers_id_1"> Paul McCartney</label></div> </div> """, ) 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, ) data = {"name": "Yesterday", "composers": ["J", "P"]} f = SongForm(data) self.assertEqual(f.errors, {}) data = QueryDict("name=Yesterday&composers=J&composers=P") f = SongForm(data) self.assertEqual(f.errors, {}) data = MultiValueDict({"name": ["Yesterday"], "composers": ["J", "P"]}) f = SongForm(data) self.assertEqual(f.errors, {}) # SelectMultiple uses ducktyping so that MultiValueDictLike.getlist() # is called. f = SongForm(MultiValueDictLike({"name": "Yesterday", "composers": "J"})) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["composers"], ["J"]) def test_multiple_hidden(self): class SongForm(Form): name = CharField() 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, ) f = SongFormHidden( MultiValueDict({"name": ["Yesterday"], "composers": ["J", "P"]}), auto_id=False, ) self.assertHTMLEqual( f.as_ul(), """<li>Name: <input type="text" name="name" value="Yesterday" required> <input type="hidden" name="composers" value="J"> <input type="hidden" name="composers" value="P"></li>""", ) # When using CheckboxSelectMultiple, the framework expects a list of input and # returns a list of input. f = SongForm({"name": "Yesterday"}, auto_id=False) self.assertEqual(f.errors["composers"], ["This field is required."]) f = SongForm({"name": "Yesterday", "composers": ["J"]}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["composers"], ["J"]) self.assertEqual(f.cleaned_data["name"], "Yesterday") f = SongForm({"name": "Yesterday", "composers": ["J", "P"]}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["composers"], ["J", "P"]) self.assertEqual(f.cleaned_data["name"], "Yesterday") # MultipleHiddenInput uses ducktyping so that # MultiValueDictLike.getlist() is called. f = SongForm(MultiValueDictLike({"name": "Yesterday", "composers": "J"})) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["composers"], ["J"]) def test_escaping(self): # Validation errors are HTML-escaped when output as HTML. class EscapingForm(Form): special_name = CharField(label="<em>Special</em> Field") special_safe_name = CharField(label=mark_safe("<em>Special</em> Field")) def clean_special_name(self): raise ValidationError( "Something's wrong with '%s'" % self.cleaned_data["special_name"] ) def clean_special_safe_name(self): raise ValidationError( mark_safe( "'<b>%s</b>' 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(), """ <tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td> <ul class="errorlist"> <li>Something&#x27;s wrong with &#x27;Nothing to escape&#x27;</li></ul> <input type="text" name="special_name" value="Nothing to escape" required> </td></tr> <tr><th><em>Special</em> Field:</th><td> <ul class="errorlist"> <li>'<b>Nothing to escape</b>' is a safe string</li></ul> <input type="text" name="special_safe_name" value="Nothing to escape" required></td></tr> """, ) f = EscapingForm( { "special_name": "Should escape < & > and <script>alert('xss')</script>", "special_safe_name": "<i>Do not escape</i>", }, auto_id=False, ) self.assertHTMLEqual( f.as_table(), "<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td>" '<ul class="errorlist"><li>' "Something&#x27;s wrong with &#x27;Should escape &lt; &amp; &gt; and " "&lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;&#x27;</li></ul>" '<input type="text" name="special_name" value="Should escape &lt; &amp; ' '&gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;" required>' "</td></tr>" "<tr><th><em>Special</em> Field:</th><td>" '<ul class="errorlist">' "<li>'<b><i>Do not escape</i></b>' is a safe string</li></ul>" '<input type="text" name="special_safe_name" ' 'value="&lt;i&gt;Do not escape&lt;/i&gt;" required></td></tr>', ) def test_validating_multiple_fields(self): # There are a couple of ways to do multiple-field validation. If you # want the validation message to be associated with a particular field, # implement the clean_XXX() method on the Form, where XXX is the field # name. As in Field.clean(), the clean_XXX() method should return the # cleaned value. In the clean_XXX() method, you have access to # self.cleaned_data, which is a dictionary of all the data that has # been cleaned *so far*, in order by the fields, including the current # field (e.g., the field XXX if you're in clean_XXX()). class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) 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"] ): raise ValidationError("Please make sure your passwords match.") return self.cleaned_data["password2"] f = UserRegistration(auto_id=False) self.assertEqual(f.errors, {}) f = UserRegistration({}, auto_id=False) 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["password2"], ["Please make sure your passwords match."] ) f = UserRegistration( {"username": "adrian", "password1": "foo", "password2": "foo"}, auto_id=False, ) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["username"], "adrian") self.assertEqual(f.cleaned_data["password1"], "foo") self.assertEqual(f.cleaned_data["password2"], "foo") # Another way of doing multiple-field validation is by implementing the # Form's clean() method. Usually ValidationError raised by that method # will not be associated with a particular field and will have a # special-case association with the field named '__all__'. It's # possible to associate the errors to particular field with the # Form.add_error() method or by passing a dictionary that maps each # field to one or more errors. # # Note that in Form.clean(), you have access to self.cleaned_data, a # dictionary of all the fields/values that have *not* raised a # ValidationError. Also note Form.clean() is required to return a # dictionary of all clean data. class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) 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"] ): raise ValidationError("Please make sure your passwords match.") # Test raising ValidationError that targets multiple fields. errors = {} if self.cleaned_data.get("password1") == "FORBIDDEN_VALUE": errors["password1"] = "Forbidden value." if self.cleaned_data.get("password2") == "FORBIDDEN_VALUE": errors["password2"] = ["Forbidden value."] if errors: raise ValidationError(errors) # Test Form.add_error() if self.cleaned_data.get("password1") == "FORBIDDEN_VALUE2": self.add_error(None, "Non-field error 1.") self.add_error("password1", "Forbidden value 2.") if self.cleaned_data.get("password2") == "FORBIDDEN_VALUE2": self.add_error("password2", "Forbidden value 2.") raise ValidationError("Non-field error 2.") return self.cleaned_data f = UserRegistration(auto_id=False) self.assertEqual(f.errors, {}) f = UserRegistration({}, auto_id=False) self.assertHTMLEqual( f.as_table(), """<tr><th>Username:</th><td> <ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="username" maxlength="10" required></td></tr> <tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul> <input type="password" name="password1" required></td></tr> <tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul> <input type="password" name="password2" required></td></tr>""", ) 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(), """ <tr><td colspan="2"> <ul class="errorlist nonfield"> <li>Please make sure your passwords match.</li></ul></td></tr> <tr><th>Username:</th><td> <input type="text" name="username" value="adrian" maxlength="10" required> </td></tr> <tr><th>Password1:</th><td> <input type="password" name="password1" required></td></tr> <tr><th>Password2:</th><td> <input type="password" name="password2" required></td></tr> """, ) self.assertHTMLEqual( f.as_ul(), """ <li><ul class="errorlist nonfield"> <li>Please make sure your passwords match.</li></ul></li> <li>Username: <input type="text" name="username" value="adrian" maxlength="10" required> </li> <li>Password1: <input type="password" name="password1" required></li> <li>Password2: <input type="password" name="password2" required></li> """, ) self.assertHTMLEqual( f.render(f.template_name_div), '<ul class="errorlist nonfield"><li>Please make sure your passwords match.' '</li></ul><div>Username: <input type="text" name="username" ' 'value="adrian" maxlength="10" required></div><div>Password1: <input ' 'type="password" name="password1" required></div><div>Password2: <input ' 'type="password" name="password2" required></div>', ) f = UserRegistration( {"username": "adrian", "password1": "foo", "password2": "foo"}, auto_id=False, ) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["username"], "adrian") 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, ) 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, ) 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."]) with self.assertRaisesMessage(ValueError, "has no field named"): f.add_error("missing_field", "Some error.") def test_update_error_dict(self): class CodeForm(Form): code = CharField(max_length=10) def clean(self): try: raise ValidationError({"code": [ValidationError("Code error 1.")]}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError({"code": [ValidationError("Code error 2.")]}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError({"code": forms.ErrorList(["Code error 3."])}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError("Non-field error 1.") except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError([ValidationError("Non-field error 2.")]) except ValidationError as e: self._errors = e.update_error_dict(self._errors) # The newly added list of errors is an instance of ErrorList. for field, error_list in self._errors.items(): if not isinstance(error_list, self.error_class): self._errors[field] = self.error_class(error_list) form = CodeForm({"code": "hello"}) # Trigger validation. self.assertFalse(form.is_valid()) # update_error_dict didn't lose track of the ErrorDict type. self.assertIsInstance(form._errors, forms.ErrorDict) self.assertEqual( dict(form.errors), { "code": ["Code error 1.", "Code error 2.", "Code error 3."], NON_FIELD_ERRORS: ["Non-field error 1.", "Non-field error 2."], }, ) def test_has_error(self): class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput, min_length=5) 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"] ): raise ValidationError( "Please make sure your passwords match.", code="password_mismatch", ) f = UserRegistration(data={}) self.assertTrue(f.has_error("password1")) self.assertTrue(f.has_error("password1", "required")) self.assertFalse(f.has_error("password1", "anything")) f = UserRegistration(data={"password1": "Hi", "password2": "Hi"}) self.assertTrue(f.has_error("password1")) self.assertTrue(f.has_error("password1", "min_length")) self.assertFalse(f.has_error("password1", "anything")) self.assertFalse(f.has_error("password2")) self.assertFalse(f.has_error("password2", "anything")) f = UserRegistration(data={"password1": "Bonjour", "password2": "Hello"}) self.assertFalse(f.has_error("password1")) self.assertFalse(f.has_error("password1", "required")) self.assertTrue(f.has_error(NON_FIELD_ERRORS)) self.assertTrue(f.has_error(NON_FIELD_ERRORS, "password_mismatch")) self.assertFalse(f.has_error(NON_FIELD_ERRORS, "anything")) def test_html_output_with_hidden_input_field_errors(self): class TestForm(Form): hidden_input = CharField(widget=HiddenInput) def clean(self): self.add_error(None, "Form error") f = TestForm(data={}) error_dict = { "hidden_input": ["This field is required."], "__all__": ["Form error"], } self.assertEqual(f.errors, error_dict) f.as_table() self.assertEqual(f.errors, error_dict) self.assertHTMLEqual( f.as_table(), '<tr><td colspan="2"><ul class="errorlist nonfield"><li>Form error</li>' "<li>(Hidden field hidden_input) This field is required.</li></ul>" '<input type="hidden" name="hidden_input" id="id_hidden_input"></td></tr>', ) self.assertHTMLEqual( f.as_ul(), '<li><ul class="errorlist nonfield"><li>Form error</li>' "<li>(Hidden field hidden_input) This field is required.</li></ul>" '<input type="hidden" name="hidden_input" id="id_hidden_input"></li>', ) self.assertHTMLEqual( f.as_p(), '<ul class="errorlist nonfield"><li>Form error</li>' "<li>(Hidden field hidden_input) This field is required.</li></ul>" '<p><input type="hidden" name="hidden_input" id="id_hidden_input"></p>', ) self.assertHTMLEqual( f.render(f.template_name_div), '<ul class="errorlist nonfield"><li>Form error</li>' "<li>(Hidden field hidden_input) This field is required.</li></ul>" '<div><input type="hidden" name="hidden_input" id="id_hidden_input"></div>', ) def test_dynamic_construction(self): # It's possible to construct a Form dynamically by adding to the self.fields # dictionary in __init__(). Don't forget to call Form.__init__() within the # subclass' __init__(). class Person(Form): first_name = CharField() last_name = CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["birthday"] = DateField() p = Person(auto_id=False) self.assertHTMLEqual( p.as_table(), """ <tr><th>First name:</th><td> <input type="text" name="first_name" required></td></tr> <tr><th>Last name:</th><td> <input type="text" name="last_name" required></td></tr> <tr><th>Birthday:</th><td> <input type="text" name="birthday" required></td></tr> """, ) # Instances of a dynamic Form do not persist fields from one Form instance to # the next. class MyForm(Form): def __init__(self, data=None, auto_id=False, field_list=[]): Form.__init__(self, data, auto_id=auto_id) for field in field_list: self.fields[field[0]] = field[1] field_list = [("field1", CharField()), ("field2", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """ <tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr> """, ) field_list = [("field3", CharField()), ("field4", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """ <tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr> """, ) class MyForm(Form): default_field_1 = CharField() default_field_2 = CharField() def __init__(self, data=None, auto_id=False, field_list=[]): Form.__init__(self, data, auto_id=auto_id) for field in field_list: self.fields[field[0]] = field[1] field_list = [("field1", CharField()), ("field2", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """ <tr><th>Default field 1:</th><td> <input type="text" name="default_field_1" required></td></tr> <tr><th>Default field 2:</th><td> <input type="text" name="default_field_2" required></td></tr> <tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr> """, ) field_list = [("field3", CharField()), ("field4", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """ <tr><th>Default field 1:</th><td> <input type="text" name="default_field_1" required></td></tr> <tr><th>Default field 2:</th><td> <input type="text" name="default_field_2" required></td></tr> <tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr> """, ) # Similarly, changes to field attributes do not persist from one Form instance # to the next. class Person(Form): first_name = CharField(required=False) last_name = CharField(required=False) def __init__(self, names_required=False, *args, **kwargs): super().__init__(*args, **kwargs) if names_required: self.fields["first_name"].required = True self.fields["first_name"].widget.attrs["class"] = "required" self.fields["last_name"].required = True self.fields["last_name"].widget.attrs["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, ({}, {}), ) 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": "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, ({}, {}), ) class Person(Form): first_name = CharField(max_length=30) last_name = CharField(max_length=30) def __init__(self, name_max_length=None, *args, **kwargs): super().__init__(*args, **kwargs) if name_max_length: self.fields["first_name"].max_length = name_max_length self.fields["last_name"].max_length = name_max_length f = Person(name_max_length=None) self.assertEqual( f["first_name"].field.max_length, f["last_name"].field.max_length, (30, 30) ) f = Person(name_max_length=20) self.assertEqual( f["first_name"].field.max_length, f["last_name"].field.max_length, (20, 20) ) f = Person(name_max_length=None) self.assertEqual( f["first_name"].field.max_length, f["last_name"].field.max_length, (30, 30) ) # Similarly, choices do not persist from one Form instance to the next. # Refs #15127. class Person(Form): first_name = CharField(required=False) last_name = CharField(required=False) gender = ChoiceField(choices=(("f", "Female"), ("m", "Male"))) def __init__(self, allow_unspec_gender=False, *args, **kwargs): super().__init__(*args, **kwargs) if allow_unspec_gender: self.fields["gender"].choices += (("u", "Unspecified"),) f = Person() self.assertEqual(f["gender"].field.choices, [("f", "Female"), ("m", "Male")]) f = Person(allow_unspec_gender=True) self.assertEqual( f["gender"].field.choices, [("f", "Female"), ("m", "Male"), ("u", "Unspecified")], ) f = Person() self.assertEqual(f["gender"].field.choices, [("f", "Female"), ("m", "Male")]) def test_validators_independence(self): """ The list of form field validators can be modified without polluting other forms. """ class MyForm(Form): myfield = CharField(max_length=25) f1 = MyForm() f2 = MyForm() f1.fields["myfield"].validators[0] = MaxValueValidator(12) self.assertNotEqual( f1.fields["myfield"].validators[0], f2.fields["myfield"].validators[0] ) def test_hidden_widget(self): # HiddenInput widgets are displayed differently in the as_table(), as_ul()) # and as_p() output of a Form -- their verbose names are not displayed, and a # separate row is not displayed. They're displayed in the last row of the # form, directly after that row's form element. class Person(Form): first_name = CharField() last_name = CharField() hidden_text = CharField(widget=HiddenInput) birthday = DateField() p = Person(auto_id=False) self.assertHTMLEqual( p.as_table(), """ <tr><th>First name:</th><td><input type="text" name="first_name" required> </td></tr> <tr><th>Last name:</th><td><input type="text" name="last_name" required> </td></tr> <tr><th>Birthday:</th> <td><input type="text" name="birthday" required> <input type="hidden" name="hidden_text"></td></tr> """, ) self.assertHTMLEqual( p.as_ul(), """ <li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required> <input type="hidden" name="hidden_text"></li> """, ) self.assertHTMLEqual( p.as_p(), """ <p>First name: <input type="text" name="first_name" required></p> <p>Last name: <input type="text" name="last_name" required></p> <p>Birthday: <input type="text" name="birthday" required> <input type="hidden" name="hidden_text"></p> """, ) self.assertHTMLEqual( p.as_div(), '<div>First name: <input type="text" name="first_name" required></div>' '<div>Last name: <input type="text" name="last_name" required></div><div>' 'Birthday: <input type="text" name="birthday" required><input ' 'type="hidden" name="hidden_text"></div>', ) # 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(), """<tr><th><label for="id_first_name">First name:</label></th><td> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></li>""", ) self.assertHTMLEqual( p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" id="id_first_name" required></div><div><label ' 'for="id_last_name">Last name:</label><input type="text" name="last_name" ' 'id="id_last_name" required></div><div><label for="id_birthday">Birthday:' '</label><input type="text" name="birthday" id="id_birthday" required>' '<input type="hidden" name="hidden_text" id="id_hidden_text"></div>', ) # 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(), """ <tr><td colspan="2"> <ul class="errorlist nonfield"><li> (Hidden field hidden_text) This field is required.</li></ul></td></tr> <tr><th>First name:</th><td> <input type="text" name="first_name" value="John" required></td></tr> <tr><th>Last name:</th><td> <input type="text" name="last_name" value="Lennon" required></td></tr> <tr><th>Birthday:</th><td> <input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></td></tr> """, ) self.assertHTMLEqual( p.as_ul(), """ <li><ul class="errorlist nonfield"><li> (Hidden field hidden_text) This field is required.</li></ul></li> <li>First name: <input type="text" name="first_name" value="John" required> </li> <li>Last name: <input type="text" name="last_name" value="Lennon" required> </li> <li>Birthday: <input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></li> """, ) self.assertHTMLEqual( p.as_p(), """ <ul class="errorlist nonfield"><li> (Hidden field hidden_text) This field is required.</li></ul> <p>First name: <input type="text" name="first_name" value="John" required> </p> <p>Last name: <input type="text" name="last_name" value="Lennon" required> </p> <p>Birthday: <input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></p> """, ) self.assertHTMLEqual( p.as_div(), '<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field ' 'is required.</li></ul><div>First name: <input type="text" ' 'name="first_name" value="John" required></div><div>Last name: <input ' 'type="text" name="last_name" value="Lennon" required></div><div>' 'Birthday: <input type="text" name="birthday" value="1940-10-9" required>' '<input type="hidden" name="hidden_text"></div>', ) # A corner case: It's possible for a form to have only HiddenInputs. class TestForm(Form): foo = CharField(widget=HiddenInput) bar = CharField(widget=HiddenInput) p = TestForm(auto_id=False) self.assertHTMLEqual( p.as_table(), '<input type="hidden" name="foo"><input type="hidden" name="bar">', ) self.assertHTMLEqual( p.as_ul(), '<input type="hidden" name="foo"><input type="hidden" name="bar">', ) self.assertHTMLEqual( p.as_p(), '<input type="hidden" name="foo"><input type="hidden" name="bar">' ) def test_field_order(self): # A Form's fields are displayed in the same order in which they were defined. class TestForm(Form): field1 = CharField() field2 = CharField() field3 = CharField() field4 = CharField() field5 = CharField() field6 = CharField() field7 = CharField() field8 = CharField() field9 = CharField() field10 = CharField() field11 = CharField() field12 = CharField() field13 = CharField() field14 = CharField() p = TestForm(auto_id=False) self.assertHTMLEqual( p.as_table(), "".join( f"<tr><th>Field{i}:</th><td>" f'<input type="text" name="field{i}" required></td></tr>' for i in range(1, 15) ), ) def test_explicit_field_order(self): class TestFormParent(Form): field1 = CharField() field2 = CharField() field4 = CharField() field5 = CharField() field6 = CharField() field_order = ["field6", "field5", "field4", "field2", "field1"] class TestForm(TestFormParent): field3 = CharField() field_order = ["field2", "field4", "field3", "field5", "field6"] class TestFormRemove(TestForm): field1 = None class TestFormMissing(TestForm): field_order = ["field2", "field4", "field3", "field5", "field6", "field1"] field1 = None class TestFormInit(TestFormParent): field3 = CharField() field_order = None def __init__(self, **kwargs): super().__init__(**kwargs) self.order_fields(field_order=TestForm.field_order) p = TestFormParent() self.assertEqual(list(p.fields), TestFormParent.field_order) p = TestFormRemove() self.assertEqual(list(p.fields), TestForm.field_order) p = TestFormMissing() self.assertEqual(list(p.fields), TestForm.field_order) p = TestForm() self.assertEqual(list(p.fields), TestFormMissing.field_order) p = TestFormInit() order = [*TestForm.field_order, "field1"] self.assertEqual(list(p.fields), order) TestForm.field_order = ["unknown"] p = TestForm() self.assertEqual( list(p.fields), ["field1", "field2", "field4", "field5", "field6", "field3"] ) def test_form_html_attributes(self): # Some Field classes have an effect on the HTML attributes of their associated # Widget. If you set max_length in a CharField and its associated widget is # either a TextInput or PasswordInput, then the widget's rendered HTML will # include the "maxlength" attribute. class UserRegistration(Form): username = CharField(max_length=10) # uses TextInput by default password = CharField(max_length=10, widget=PasswordInput) realname = CharField( max_length=10, widget=TextInput ) # redundantly define widget, just to test address = CharField() # no max_length defined here p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" maxlength="10" required> </li> <li>Password: <input type="password" name="password" maxlength="10" required></li> <li>Realname: <input type="text" name="realname" maxlength="10" required> </li> <li>Address: <input type="text" name="address" required></li> """, ) # If you specify a custom "attrs" that includes the "maxlength" # attribute, the Field's max_length attribute will override whatever # "maxlength" you specify in "attrs". class UserRegistration(Form): username = CharField( max_length=10, widget=TextInput(attrs={"maxlength": 20}) ) password = CharField(max_length=10, widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), '<li>Username: <input type="text" name="username" maxlength="10" required>' "</li>" '<li>Password: <input type="password" name="password" maxlength="10" ' "required></li>", ) def test_specifying_labels(self): # You can specify the label for a field by using the 'label' argument to a Field # class. If you don't specify 'label', Django will use the field name with # underscores converted to spaces, and the initial letter capitalized. class UserRegistration(Form): username = CharField(max_length=10, label="Your username") password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput, label="Contraseña (de nuevo)") p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Your username: <input type="text" name="username" maxlength="10" required></li> <li>Password1: <input type="password" name="password1" required></li> <li>Contraseña (de nuevo): <input type="password" name="password2" required></li> """, ) # Labels for as_* methods will only end in a colon if they don't end in other # punctuation already. class Questions(Form): q1 = CharField(label="The first question") q2 = CharField(label="What is your name?") q3 = CharField(label="The answer to life is:") q4 = CharField(label="Answer this question!") q5 = CharField(label="The last question. Period.") self.assertHTMLEqual( Questions(auto_id=False).as_p(), """<p>The first question: <input type="text" name="q1" required></p> <p>What is your name? <input type="text" name="q2" required></p> <p>The answer to life is: <input type="text" name="q3" required></p> <p>Answer this question! <input type="text" name="q4" required></p> <p>The last question. Period. <input type="text" name="q5" required></p>""", ) self.assertHTMLEqual( Questions().as_p(), """ <p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" required></p> <p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" required></p> <p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" required></p> <p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" required></p> <p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" required></p> """, ) # If a label is set to the empty string for a field, that field won't # get a label. class UserRegistration(Form): username = CharField(max_length=10, label="") password = CharField(widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li> <input type="text" name="username" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li>""", ) p = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( p.as_ul(), """ <li> <input id="id_username" type="text" name="username" maxlength="10" required> </li> <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" required></li> """, ) # If label is None, Django will auto-create the label from the field name. This # is default behavior. class UserRegistration(Form): username = CharField(max_length=10, label=None) password = CharField(widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), '<li>Username: <input type="text" name="username" maxlength="10" required>' "</li>" '<li>Password: <input type="password" name="password" required></li>', ) p = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( p.as_ul(), """<li><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" required></li> <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" required></li>""", ) def test_label_suffix(self): # You can specify the 'label_suffix' argument to a Form class to modify # the punctuation symbol used at the end of a label. By default, the # colon (:) is used, and is only appended to the label if the label # doesn't already end with a punctuation symbol: ., !, ? or :. If you # specify a different suffix, it will be appended regardless of the # last character of the label. class FavoriteForm(Form): color = CharField(label="Favorite color?") animal = CharField(label="Favorite animal") answer = CharField(label="Secret answer", label_suffix=" =") f = FavoriteForm(auto_id=False) self.assertHTMLEqual( f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal: <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""", ) f = FavoriteForm(auto_id=False, label_suffix="?") self.assertHTMLEqual( f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal? <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""", ) f = FavoriteForm(auto_id=False, label_suffix="") self.assertHTMLEqual( f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""", ) f = FavoriteForm(auto_id=False, label_suffix="\u2192") self.assertHTMLEqual( f.as_ul(), '<li>Favorite color? <input type="text" name="color" required></li>\n' "<li>Favorite animal\u2192 " '<input type="text" name="animal" required></li>\n' '<li>Secret answer = <input type="text" name="answer" required></li>', ) def test_initial_data(self): # You can specify initial data for a field by using the 'initial' argument to a # Field class. This initial data is displayed when a Form is rendered with *no* # data. It is not displayed when a Form is rendered with any data (including an # empty dictionary). Also, the initial value is *not* used if data for a # particular required field isn't provided. class UserRegistration(Form): username = CharField(max_length=10, initial="django") password = CharField(widget=PasswordInput) # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> """, ) # Here, we're submitting data, so the initial value will *not* be displayed. p = UserRegistration({}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""", ) p = UserRegistration({"username": ""}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""", ) p = UserRegistration({"username": "foo"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> """, ) # 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 validation error rather than using the initial # value for 'username'. p = UserRegistration({"password": "secret"}) self.assertEqual(p.errors["username"], ["This field is required."]) self.assertFalse(p.is_valid()) def test_dynamic_initial_data(self): # The previous technique dealt with "hard-coded" initial data, but it's also # possible to specify initial data after you've already created the Form class # (i.e., at runtime). Use the 'initial' parameter to the Form constructor. This # should be a dictionary containing initial values for one or more fields in the # form, keyed by field name. class UserRegistration(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) # 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(), """ <li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> """, ) p = UserRegistration(initial={"username": "stephane"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="stephane" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> """, ) # The 'initial' parameter is meaningless if you pass data. p = UserRegistration({}, initial={"username": "django"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""", ) p = UserRegistration( {"username": ""}, initial={"username": "django"}, auto_id=False ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""", ) p = UserRegistration( {"username": "foo"}, initial={"username": "django"}, auto_id=False ) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> """, ) # 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 validation error rather than using the initial value # for 'username'. p = UserRegistration({"password": "secret"}, initial={"username": "django"}) self.assertEqual(p.errors["username"], ["This field is required."]) self.assertFalse(p.is_valid()) # If a Form defines 'initial' *and* 'initial' is passed as a parameter # to Form(), then the latter will get precedence. class UserRegistration(Form): username = CharField(max_length=10, initial="django") password = CharField(widget=PasswordInput) p = UserRegistration(initial={"username": "babik"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="babik" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> """, ) def test_callable_initial_data(self): # The previous technique dealt with raw values as initial data, but it's also # possible to specify callable data. class UserRegistration(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) options = MultipleChoiceField( choices=[("f", "foo"), ("b", "bar"), ("w", "whiz")] ) # We need to define functions that get called later.) def initial_django(): return "django" def initial_stephane(): return "stephane" def initial_options(): return ["f", "b"] def initial_other_options(): return ["b", "w"] # 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(), """ <li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" selected>bar</option> <option value="w">whiz</option> </select></li> """, ) # 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(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b">bar</option> <option value="w">whiz</option> </select></li>""", ) p = UserRegistration( {"username": ""}, initial={"username": initial_django}, auto_id=False ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b">bar</option> <option value="w">whiz</option> </select></li>""", ) p = UserRegistration( {"username": "foo", "options": ["f", "b"]}, initial={"username": initial_django}, auto_id=False, ) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" selected>bar</option> <option value="w">whiz</option> </select></li> """, ) # 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 validation error rather than using the initial # value for 'username'. p = UserRegistration( {"password": "secret"}, initial={"username": initial_django, "options": initial_options}, ) self.assertEqual(p.errors["username"], ["This field is required."]) self.assertFalse(p.is_valid()) # If a Form defines 'initial' *and* 'initial' is passed as a parameter # to Form(), then the latter will get precedence. 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, ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b" selected>bar</option> <option value="w" selected>whiz</option> </select></li> """, ) p = UserRegistration( initial={"username": initial_stephane, "options": initial_options}, auto_id=False, ) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="stephane" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" selected>bar</option> <option value="w">whiz</option> </select></li> """, ) def test_get_initial_for_field(self): now = datetime.datetime(2006, 10, 25, 14, 30, 45, 123456) class PersonForm(Form): first_name = CharField(initial="John") last_name = CharField(initial="Doe") age = IntegerField() occupation = CharField(initial=lambda: "Unknown") dt_fixed = DateTimeField(initial=now) dt_callable = DateTimeField(initial=lambda: now) form = PersonForm(initial={"first_name": "Jane"}) cases = [ ("age", None), ("last_name", "Doe"), # Form.initial overrides Field.initial. ("first_name", "Jane"), # Callables are evaluated. ("occupation", "Unknown"), # Microseconds are removed from datetimes. ("dt_fixed", datetime.datetime(2006, 10, 25, 14, 30, 45)), ("dt_callable", datetime.datetime(2006, 10, 25, 14, 30, 45)), ] for field_name, expected in cases: with self.subTest(field_name=field_name): field = form.fields[field_name] actual = form.get_initial_for_field(field, field_name) self.assertEqual(actual, expected) def test_changed_data(self): class Person(Form): first_name = CharField(initial="Hans") last_name = CharField(initial="Greatel") birthday = DateField(initial=datetime.date(1974, 8, 16)) p = Person( data={"first_name": "Hans", "last_name": "Scrmbl", "birthday": "1974-08-16"} ) self.assertTrue(p.is_valid()) self.assertNotIn("first_name", p.changed_data) self.assertIn("last_name", p.changed_data) self.assertNotIn("birthday", p.changed_data) # A field raising ValidationError is always in changed_data class PedanticField(forms.Field): def to_python(self, value): raise ValidationError("Whatever") class Person2(Person): pedantic = PedanticField(initial="whatever", show_hidden_initial=True) p = Person2( data={ "first_name": "Hans", "last_name": "Scrmbl", "birthday": "1974-08-16", "initial-pedantic": "whatever", } ) self.assertFalse(p.is_valid()) self.assertIn("pedantic", p.changed_data) def test_boundfield_values(self): # It's possible to get to the value which would be used for rendering # the widget for a field by using the BoundField's value method. class UserRegistration(Form): username = CharField(max_length=10, initial="djangonaut") password = CharField(widget=PasswordInput) unbound = UserRegistration() bound = UserRegistration({"password": "foo"}) self.assertIsNone(bound["username"].value()) self.assertEqual(unbound["username"].value(), "djangonaut") self.assertEqual(bound["password"].value(), "foo") self.assertIsNone(unbound["password"].value()) def test_boundfield_initial_called_once(self): """ Multiple calls to BoundField().value() in an unbound form should return the same result each time (#24391). """ class MyForm(Form): name = CharField(max_length=10, initial=uuid.uuid4) form = MyForm() name = form["name"] self.assertEqual(name.value(), name.value()) # BoundField is also cached self.assertIs(form["name"], name) def test_boundfield_value_disabled_callable_initial(self): class PersonForm(Form): name = CharField(initial=lambda: "John Doe", disabled=True) # Without form data. form = PersonForm() self.assertEqual(form["name"].value(), "John Doe") # With form data. As the field is disabled, the value should not be # affected by the form data. form = PersonForm({}) self.assertEqual(form["name"].value(), "John Doe") def test_custom_boundfield(self): class CustomField(CharField): def get_bound_field(self, form, name): return (form, name) class SampleForm(Form): name = CustomField() f = SampleForm() self.assertEqual(f["name"], (f, "name")) def test_initial_datetime_values(self): now = datetime.datetime.now() # Nix microseconds (since they should be ignored). #22502 now_no_ms = now.replace(microsecond=0) if now == now_no_ms: now = now.replace(microsecond=1) def delayed_now(): return now def delayed_now_time(): return now.time() class HiddenInputWithoutMicrosec(HiddenInput): supports_microseconds = False class TextInputWithoutMicrosec(TextInput): supports_microseconds = False class DateTimeForm(Form): # Test a non-callable. fixed = DateTimeField(initial=now) auto_timestamp = DateTimeField(initial=delayed_now) auto_time_only = TimeField(initial=delayed_now_time) supports_microseconds = DateTimeField(initial=delayed_now, widget=TextInput) hi_default_microsec = DateTimeField(initial=delayed_now, widget=HiddenInput) hi_without_microsec = DateTimeField( initial=delayed_now, widget=HiddenInputWithoutMicrosec ) ti_without_microsec = DateTimeField( initial=delayed_now, widget=TextInputWithoutMicrosec ) unbound = DateTimeForm() cases = [ ("fixed", now_no_ms), ("auto_timestamp", now_no_ms), ("auto_time_only", now_no_ms.time()), ("supports_microseconds", now), ("hi_default_microsec", now), ("hi_without_microsec", now_no_ms), ("ti_without_microsec", now_no_ms), ] for field_name, expected in cases: with self.subTest(field_name=field_name): actual = unbound[field_name].value() self.assertEqual(actual, expected) # Also check get_initial_for_field(). field = unbound.fields[field_name] actual = unbound.get_initial_for_field(field, field_name) self.assertEqual(actual, expected) def get_datetime_form_with_callable_initial(self, disabled, microseconds=0): class FakeTime: def __init__(self): self.elapsed_seconds = 0 def now(self): self.elapsed_seconds += 1 return datetime.datetime( 2006, 10, 25, 14, 30, 45 + self.elapsed_seconds, microseconds, ) class DateTimeForm(forms.Form): dt = DateTimeField(initial=FakeTime().now, disabled=disabled) return DateTimeForm({}) def test_datetime_clean_disabled_callable_initial_microseconds(self): """ Cleaning a form with a disabled DateTimeField and callable initial removes microseconds. """ form = self.get_datetime_form_with_callable_initial( disabled=True, microseconds=123456, ) self.assertEqual(form.errors, {}) self.assertEqual( form.cleaned_data, { "dt": datetime.datetime(2006, 10, 25, 14, 30, 46), }, ) def test_datetime_clean_disabled_callable_initial_bound_field(self): """ The cleaned value for a form with a disabled DateTimeField and callable initial matches the bound field's cached initial value. """ form = self.get_datetime_form_with_callable_initial(disabled=True) self.assertEqual(form.errors, {}) cleaned = form.cleaned_data["dt"] self.assertEqual(cleaned, datetime.datetime(2006, 10, 25, 14, 30, 46)) bf = form["dt"] self.assertEqual(cleaned, bf.initial) def test_datetime_changed_data_callable_with_microseconds(self): class DateTimeForm(forms.Form): dt = DateTimeField( initial=lambda: datetime.datetime(2006, 10, 25, 14, 30, 45, 123456), disabled=True, ) form = DateTimeForm({"dt": "2006-10-25 14:30:45"}) self.assertEqual(form.changed_data, []) def test_help_text(self): # You can specify descriptive text for a field by using the 'help_text' # argument. class UserRegistration(Form): username = CharField(max_length=10, help_text="e.g., [email protected]") password = CharField( widget=PasswordInput, help_text="Wählen Sie mit Bedacht." ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></li> <li>Password: <input type="password" name="password" required> <span class="helptext">Wählen Sie mit Bedacht.</span></li>""", ) self.assertHTMLEqual( p.as_p(), """<p>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></p> <p>Password: <input type="password" name="password" required> <span class="helptext">Wählen Sie mit Bedacht.</span></p>""", ) self.assertHTMLEqual( p.as_table(), """ <tr><th>Username:</th><td> <input type="text" name="username" maxlength="10" required><br> <span class="helptext">e.g., [email protected]</span></td></tr> <tr><th>Password:</th><td><input type="password" name="password" required> <br> <span class="helptext">Wählen Sie mit Bedacht.</span></td></tr>""", ) self.assertHTMLEqual( p.as_div(), '<div>Username: <div class="helptext">e.g., [email protected]</div>' '<input type="text" name="username" maxlength="10" required></div>' '<div>Password: <div class="helptext">Wählen Sie mit Bedacht.</div>' '<input type="password" name="password" required></div>', ) # 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(), '<li>Username: <input type="text" name="username" value="foo" ' 'maxlength="10" required>' '<span class="helptext">e.g., [email protected]</span></li>' '<li><ul class="errorlist"><li>This field is required.</li></ul>' 'Password: <input type="password" name="password" required>' '<span class="helptext">Wählen Sie mit Bedacht.</span></li>', ) # help_text is not displayed for hidden fields. It can be used for documentation # purposes, though. class UserRegistration(Form): username = CharField(max_length=10, help_text="e.g., [email protected]") password = CharField(widget=PasswordInput) next = CharField( widget=HiddenInput, initial="/", help_text="Redirect destination" ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></li> <li>Password: <input type="password" name="password" required> <input type="hidden" name="next" value="/"></li>""", ) def test_help_text_html_safe(self): """help_text should not be escaped.""" class UserRegistration(Form): username = CharField(max_length=10, help_text="e.g., [email protected]") password = CharField( widget=PasswordInput, help_text="Help text is <strong>escaped</strong>.", ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), '<li>Username: <input type="text" name="username" maxlength="10" required>' '<span class="helptext">e.g., [email protected]</span></li>' '<li>Password: <input type="password" name="password" required>' '<span class="helptext">Help text is <strong>escaped</strong>.</span></li>', ) self.assertHTMLEqual( p.as_p(), '<p>Username: <input type="text" name="username" maxlength="10" required>' '<span class="helptext">e.g., [email protected]</span></p>' '<p>Password: <input type="password" name="password" required>' '<span class="helptext">Help text is <strong>escaped</strong>.</span></p>', ) self.assertHTMLEqual( p.as_table(), "<tr><th>Username:</th><td>" '<input type="text" name="username" maxlength="10" required><br>' '<span class="helptext">e.g., [email protected]</span></td></tr>' "<tr><th>Password:</th><td>" '<input type="password" name="password" required><br>' '<span class="helptext">Help text is <strong>escaped</strong>.</span>' "</td></tr>", ) def test_widget_attrs_custom_aria_describedby(self): # aria-describedby provided to the widget overrides the default. class UserRegistration(Form): username = CharField( max_length=255, help_text="e.g., [email protected]", widget=TextInput(attrs={"aria-describedby": "custom-description"}), ) password = CharField( widget=PasswordInput, help_text="Wählen Sie mit Bedacht." ) p = UserRegistration() self.assertHTMLEqual( p.as_div(), '<div><label for="id_username">Username:</label>' '<div class="helptext" id="id_username_helptext">e.g., [email protected]' '</div><input type="text" name="username" maxlength="255" required ' 'aria-describedby="custom-description" id="id_username">' "</div><div>" '<label for="id_password">Password:</label>' '<div class="helptext" id="id_password_helptext">Wählen Sie mit Bedacht.' '</div><input type="password" name="password" required ' 'aria-describedby="id_password_helptext" id="id_password"></div>', ) self.assertHTMLEqual( p.as_ul(), '<li><label for="id_username">Username:</label><input type="text" ' 'name="username" maxlength="255" required ' 'aria-describedby="custom-description" id="id_username">' '<span class="helptext" id="id_username_helptext">e.g., [email protected]' "</span></li><li>" '<label for="id_password">Password:</label>' '<input type="password" name="password" required ' 'aria-describedby="id_password_helptext" id="id_password">' '<span class="helptext" id="id_password_helptext">Wählen Sie mit Bedacht.' "</span></li>", ) self.assertHTMLEqual( p.as_p(), '<p><label for="id_username">Username:</label><input type="text" ' 'name="username" maxlength="255" required ' 'aria-describedby="custom-description" id="id_username">' '<span class="helptext" id="id_username_helptext">e.g., [email protected]' "</span></p><p>" '<label for="id_password">Password:</label>' '<input type="password" name="password" required ' 'aria-describedby="id_password_helptext" id="id_password">' '<span class="helptext" id="id_password_helptext">Wählen Sie mit Bedacht.' "</span></p>", ) self.assertHTMLEqual( p.as_table(), '<tr><th><label for="id_username">Username:</label></th><td>' '<input type="text" name="username" maxlength="255" required ' 'aria-describedby="custom-description" id="id_username"><br>' '<span class="helptext" id="id_username_helptext">e.g., [email protected]' "</span></td></tr><tr><th>" '<label for="id_password">Password:</label></th><td>' '<input type="password" name="password" required ' 'aria-describedby="id_password_helptext" id="id_password"><br>' '<span class="helptext" id="id_password_helptext">Wählen Sie mit Bedacht.' "</span></td></tr>", ) def test_as_widget_custom_aria_describedby(self): class FoodForm(Form): intl_name = CharField(help_text="The food's international name.") form = FoodForm({"intl_name": "Rendang"}) self.assertHTMLEqual( form["intl_name"].as_widget(attrs={"aria-describedby": "some_custom_id"}), '<input type="text" name="intl_name" value="Rendang"' 'aria-describedby="some_custom_id" required id="id_intl_name">', ) def test_subclassing_forms(self): # You can subclass a Form to add fields. The resulting form subclass will have # all of the fields of the parent Form, plus whichever fields you define in the # subclass. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class Musician(Person): instrument = CharField() p = Person(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li>""", ) m = Musician(auto_id=False) self.assertHTMLEqual( m.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li> <li>Instrument: <input type="text" name="instrument" required></li>""", ) # Yes, you can subclass multiple forms. The fields are added in the order in # which the parent classes are listed. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class Instrument(Form): instrument = CharField() class Beatle(Person, Instrument): haircut_type = CharField() b = Beatle(auto_id=False) self.assertHTMLEqual( b.as_ul(), """<li>Instrument: <input type="text" name="instrument" required></li> <li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li> <li>Haircut type: <input type="text" name="haircut_type" required></li>""", ) def test_forms_with_prefixes(self): # Sometimes it's necessary to have multiple forms display on the same # HTML page, or multiple copies of the same form. We can accomplish # this with form prefixes. Pass the keyword argument 'prefix' to the # Form constructor to use this feature. This value will be prepended to # each HTML form field name. One way to think about this is "namespaces # for HTML forms". Notice that in the data argument, each field's key # has the prefix, in this case 'person1', prepended to the actual field # name. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() data = { "person1-first_name": "John", "person1-last_name": "Lennon", "person1-birthday": "1940-10-9", } p = Person(data, prefix="person1") self.assertHTMLEqual( p.as_ul(), """ <li><label for="id_person1-first_name">First name:</label> <input type="text" name="person1-first_name" value="John" id="id_person1-first_name" required></li> <li><label for="id_person1-last_name">Last name:</label> <input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" required></li> <li><label for="id_person1-birthday">Birthday:</label> <input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" required></li> """, ) self.assertHTMLEqual( str(p["first_name"]), '<input type="text" name="person1-first_name" value="John" ' 'id="id_person1-first_name" required>', ) self.assertHTMLEqual( str(p["last_name"]), '<input type="text" name="person1-last_name" value="Lennon" ' 'id="id_person1-last_name" required>', ) self.assertHTMLEqual( str(p["birthday"]), '<input type="text" name="person1-birthday" value="1940-10-9" ' 'id="id_person1-birthday" required>', ) self.assertEqual(p.errors, {}) self.assertTrue(p.is_valid()) 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)) # Let's try submitting some bad data to make sure form.errors and field.errors # work as expected. data = { "person1-first_name": "", "person1-last_name": "", "person1-birthday": "", } p = Person(data, prefix="person1") self.assertEqual(p.errors["first_name"], ["This field is required."]) self.assertEqual(p.errors["last_name"], ["This field is required."]) self.assertEqual(p.errors["birthday"], ["This field is required."]) self.assertEqual(p["first_name"].errors, ["This field is required."]) # Accessing a nonexistent field. with self.assertRaises(KeyError): p["person1-first_name"].errors # In this example, the data doesn't have a prefix, but the form requires it, so # the form doesn't "see" the fields. data = {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"} p = Person(data, prefix="person1") self.assertEqual(p.errors["first_name"], ["This field is required."]) self.assertEqual(p.errors["last_name"], ["This field is required."]) self.assertEqual(p.errors["birthday"], ["This field is required."]) # With prefixes, a single data dictionary can hold data for multiple instances # of the same form. data = { "person1-first_name": "John", "person1-last_name": "Lennon", "person1-birthday": "1940-10-9", "person2-first_name": "Jim", "person2-last_name": "Morrison", "person2-birthday": "1943-12-8", } p1 = Person(data, prefix="person1") self.assertTrue(p1.is_valid()) self.assertEqual(p1.cleaned_data["first_name"], "John") self.assertEqual(p1.cleaned_data["last_name"], "Lennon") self.assertEqual(p1.cleaned_data["birthday"], datetime.date(1940, 10, 9)) p2 = Person(data, prefix="person2") self.assertTrue(p2.is_valid()) self.assertEqual(p2.cleaned_data["first_name"], "Jim") self.assertEqual(p2.cleaned_data["last_name"], "Morrison") self.assertEqual(p2.cleaned_data["birthday"], datetime.date(1943, 12, 8)) # By default, forms append a hyphen between the prefix and the field name, but a # form can alter that behavior by implementing the add_prefix() method. This # method takes a field name and returns the prefixed field, according to # self.prefix. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() def add_prefix(self, field_name): return ( "%s-prefix-%s" % (self.prefix, field_name) if self.prefix else field_name ) p = Person(prefix="foo") self.assertHTMLEqual( p.as_ul(), """ <li><label for="id_foo-prefix-first_name">First name:</label> <input type="text" name="foo-prefix-first_name" id="id_foo-prefix-first_name" required></li> <li><label for="id_foo-prefix-last_name">Last name:</label> <input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name" required></li> <li><label for="id_foo-prefix-birthday">Birthday:</label> <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" required></li> """, ) data = { "foo-prefix-first_name": "John", "foo-prefix-last_name": "Lennon", "foo-prefix-birthday": "1940-10-9", } p = Person(data, prefix="foo") self.assertTrue(p.is_valid()) 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)) def test_class_prefix(self): # Prefix can be also specified at the class level. class Person(Form): first_name = CharField() prefix = "foo" p = Person() self.assertEqual(p.prefix, "foo") p = Person(prefix="bar") self.assertEqual(p.prefix, "bar") def test_forms_with_null_boolean(self): # NullBooleanField is a bit of a special case because its presentation (widget) # is different than its data. This is handled transparently, though. class Person(Form): name = CharField() is_cool = NullBooleanField() p = Person({"name": "Joe"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "1"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "2"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true" selected>Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "3"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true">Yes</option> <option value="false" selected>No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": True}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true" selected>Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": False}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true">Yes</option> <option value="false" selected>No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "unknown"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "true"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true" selected>Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "false"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true">Yes</option> <option value="false" selected>No</option> </select>""", ) def test_forms_with_file_fields(self): # FileFields are a special case because they take their data from the # request.FILES, not request.POST. class FileForm(Form): file1 = FileField() f = FileForm(auto_id=False) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<input type="file" name="file1" required></td></tr>', ) f = FileForm(data={}, files={}, auto_id=False) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="file" name="file1" required></td></tr>', ) f = FileForm( data={}, files={"file1": SimpleUploadedFile("name", b"")}, auto_id=False ) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<ul class="errorlist"><li>The submitted file is empty.</li></ul>' '<input type="file" name="file1" required></td></tr>', ) f = FileForm( data={}, files={"file1": "something that is not a file"}, auto_id=False ) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<ul class="errorlist"><li>No file was submitted. Check the ' "encoding type on the form.</li></ul>" '<input type="file" name="file1" required></td></tr>', ) f = FileForm( data={}, files={"file1": SimpleUploadedFile("name", b"some content")}, auto_id=False, ) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<input type="file" name="file1" required></td></tr>', ) self.assertTrue(f.is_valid()) file1 = SimpleUploadedFile( "我隻氣墊船裝滿晒鱔.txt", "मेरी मँडराने वाली नाव सर्पमीनों से भरी ह".encode() ) f = FileForm(data={}, files={"file1": file1}, auto_id=False) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<input type="file" name="file1" required></td></tr>', ) # A required file field with initial data should not contain the # required HTML attribute. The file input is left blank by the user to # keep the existing, initial value. f = FileForm(initial={"file1": "resume.txt"}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1"></td></tr>', ) def test_filefield_initial_callable(self): class FileForm(forms.Form): file1 = forms.FileField(initial=lambda: "resume.txt") f = FileForm({}) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["file1"], "resume.txt") def test_filefield_with_fileinput_required(self): class FileForm(Form): file1 = forms.FileField(widget=FileInput) f = FileForm(auto_id=False) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<input type="file" name="file1" required></td></tr>', ) # A required file field with initial data doesn't contain the required # HTML attribute. The file input is left blank by the user to keep the # existing, initial value. f = FileForm(initial={"file1": "resume.txt"}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1"></td></tr>', ) def test_empty_permitted(self): # Sometimes (pretty much in formsets) we want to allow a form to pass validation # if it is completely empty. We can accomplish this by using the empty_permitted # argument to a form constructor. class SongForm(Form): artist = CharField() name = CharField() # First let's show what happens id empty_permitted=False (the default): data = {"artist": "", "song": ""} form = SongForm(data, empty_permitted=False) self.assertFalse(form.is_valid()) self.assertEqual( form.errors, { "name": ["This field is required."], "artist": ["This field is required."], }, ) self.assertEqual(form.cleaned_data, {}) # Now let's show what happens when empty_permitted=True and the form is empty. form = SongForm(data, empty_permitted=True, use_required_attribute=False) self.assertTrue(form.is_valid()) self.assertEqual(form.errors, {}) self.assertEqual(form.cleaned_data, {}) # But if we fill in data for one of the fields, the form is no longer empty and # the whole thing must pass validation. data = {"artist": "The Doors", "song": ""} form = SongForm(data, empty_permitted=False) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {"name": ["This field is required."]}) self.assertEqual(form.cleaned_data, {"artist": "The Doors"}) # If a field is not given in the data then None is returned for its data. Lets # make sure that when checking for empty_permitted that None is treated # accordingly. data = {"artist": None, "song": ""} form = SongForm(data, empty_permitted=True, use_required_attribute=False) self.assertTrue(form.is_valid()) # However, we *really* need to be sure we are checking for None as any data in # initial that returns False on a boolean call needs to be treated literally. class PriceForm(Form): amount = FloatField() qty = IntegerField() data = {"amount": "0.0", "qty": ""} form = PriceForm( data, initial={"amount": 0.0}, empty_permitted=True, use_required_attribute=False, ) self.assertTrue(form.is_valid()) def test_empty_permitted_and_use_required_attribute(self): msg = ( "The empty_permitted and use_required_attribute arguments may not " "both be True." ) with self.assertRaisesMessage(ValueError, msg): Person(empty_permitted=True, use_required_attribute=True) def test_extracting_hidden_and_visible(self): class SongForm(Form): token = CharField(widget=HiddenInput) artist = CharField() name = CharField() form = SongForm() self.assertEqual([f.name for f in form.hidden_fields()], ["token"]) self.assertEqual([f.name for f in form.visible_fields()], ["artist", "name"]) def test_hidden_initial_gets_id(self): class MyForm(Form): field1 = CharField(max_length=50, show_hidden_initial=True) self.assertHTMLEqual( MyForm().as_table(), '<tr><th><label for="id_field1">Field1:</label></th><td>' '<input id="id_field1" type="text" name="field1" maxlength="50" required>' '<input type="hidden" name="initial-field1" id="initial-id_field1">' "</td></tr>", ) def test_error_html_required_html_classes(self): class Person(Form): name = CharField() is_cool = NullBooleanField() email = EmailField(required=False) age = IntegerField() p = Person({}) p.error_css_class = "error" p.required_css_class = "required" self.assertHTMLEqual( p.as_ul(), """ <li class="required error"><ul class="errorlist"> <li>This field is required.</li></ul> <label class="required" for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></li> <li class="required"> <label class="required" for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select></li> <li><label for="id_email">Email:</label> <input type="email" name="email" id="id_email" maxlength="320"></li> <li class="required error"><ul class="errorlist"> <li>This field is required.</li></ul> <label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required></li>""", ) self.assertHTMLEqual( p.as_p(), """ <ul class="errorlist"><li>This field is required.</li></ul> <p class="required error"> <label class="required" for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></p> <p class="required"> <label class="required" for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select></p> <p><label for="id_email">Email:</label> <input type="email" name="email" id="id_email" maxlength="320"></p> <ul class="errorlist"><li>This field is required.</li></ul> <p class="required error"><label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required></p> """, ) self.assertHTMLEqual( p.as_table(), """<tr class="required error"> <th><label class="required" for="id_name">Name:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="name" id="id_name" required></td></tr> <tr class="required"><th><label class="required" for="id_is_cool">Is cool:</label></th> <td><select name="is_cool" id="id_is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select></td></tr> <tr><th><label for="id_email">Email:</label></th><td> <input type="email" name="email" id="id_email" maxlength="320"></td></tr> <tr class="required error"><th><label class="required" for="id_age">Age:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="number" name="age" id="id_age" required></td></tr>""", ) self.assertHTMLEqual( p.as_div(), '<div class="required error"><label for="id_name" class="required">Name:' '</label><ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="name" required id="id_name" /></div>' '<div class="required"><label for="id_is_cool" class="required">Is cool:' '</label><select name="is_cool" id="id_is_cool">' '<option value="unknown" selected>Unknown</option>' '<option value="true">Yes</option><option value="false">No</option>' '</select></div><div><label for="id_email">Email:</label>' '<input type="email" name="email" id="id_email" maxlength="320"/></div>' '<div class="required error"><label for="id_age" class="required">Age:' '</label><ul class="errorlist"><li>This field is required.</li></ul>' '<input type="number" name="age" required id="id_age" /></div>', ) def test_label_has_required_css_class(self): """ required_css_class is added to label_tag() and legend_tag() of required fields. """ class SomeForm(Form): required_css_class = "required" field = CharField(max_length=10) field2 = IntegerField(required=False) f = SomeForm({"field": "test"}) self.assertHTMLEqual( f["field"].label_tag(), '<label for="id_field" class="required">Field:</label>', ) self.assertHTMLEqual( f["field"].legend_tag(), '<legend for="id_field" class="required">Field:</legend>', ) self.assertHTMLEqual( f["field"].label_tag(attrs={"class": "foo"}), '<label for="id_field" class="foo required">Field:</label>', ) self.assertHTMLEqual( f["field"].legend_tag(attrs={"class": "foo"}), '<legend for="id_field" class="foo required">Field:</legend>', ) self.assertHTMLEqual( f["field2"].label_tag(), '<label for="id_field2">Field2:</label>' ) self.assertHTMLEqual( f["field2"].legend_tag(), '<legend for="id_field2">Field2:</legend>', ) def test_label_split_datetime_not_displayed(self): class EventForm(Form): happened_at = SplitDateTimeField(widget=SplitHiddenDateTimeWidget) form = EventForm() self.assertHTMLEqual( form.as_ul(), '<input type="hidden" name="happened_at_0" id="id_happened_at_0">' '<input type="hidden" name="happened_at_1" id="id_happened_at_1">', ) def test_multivalue_field_validation(self): def bad_names(value): if value == "bad value": raise ValidationError("bad value not allowed") class NameField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = ( CharField(label="First name", max_length=10), CharField(label="Last name", max_length=10), ) super().__init__(fields=fields, *args, **kwargs) def compress(self, data_list): return " ".join(data_list) class NameForm(Form): name = NameField(validators=[bad_names]) form = NameForm(data={"name": ["bad", "value"]}) form.full_clean() self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {"name": ["bad value not allowed"]}) form = NameForm(data={"name": ["should be overly", "long for the field names"]}) self.assertFalse(form.is_valid()) self.assertEqual( form.errors, { "name": [ "Ensure this value has at most 10 characters (it has 16).", "Ensure this value has at most 10 characters (it has 24).", ], }, ) form = NameForm(data={"name": ["fname", "lname"]}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data, {"name": "fname lname"}) def test_multivalue_deep_copy(self): """ #19298 -- MultiValueField needs to override the default as it needs to deep-copy subfields: """ class ChoicesField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = ( ChoiceField(label="Rank", choices=((1, 1), (2, 2))), CharField(label="Name", max_length=10), ) super().__init__(fields=fields, *args, **kwargs) field = ChoicesField() field2 = copy.deepcopy(field) self.assertIsInstance(field2, ChoicesField) self.assertIsNot(field2.fields, field.fields) self.assertIsNot(field2.fields[0].choices, field.fields[0].choices) def test_multivalue_initial_data(self): """ #23674 -- invalid initial data should not break form.changed_data() """ class DateAgeField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = (DateField(label="Date"), IntegerField(label="Age")) super().__init__(fields=fields, *args, **kwargs) class DateAgeForm(Form): date_age = DateAgeField() data = {"date_age": ["1998-12-06", 16]} form = DateAgeForm(data, initial={"date_age": ["200-10-10", 14]}) self.assertTrue(form.has_changed()) def test_multivalue_optional_subfields(self): class PhoneField(MultiValueField): def __init__(self, *args, **kwargs): fields = ( CharField( label="Country Code", validators=[ RegexValidator( r"^\+[0-9]{1,2}$", message="Enter a valid country code." ) ], ), CharField(label="Phone Number"), CharField( label="Extension", error_messages={"incomplete": "Enter an extension."}, ), CharField( label="Label", required=False, help_text="E.g. home, work." ), ) super().__init__(fields, *args, **kwargs) def compress(self, data_list): if data_list: return "%s.%s ext. %s (label: %s)" % tuple(data_list) return None # An empty value for any field will raise a `required` error on a # required `MultiValueField`. f = PhoneField() with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean([]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(["+61"]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(["+61", "287654321", "123"]) self.assertEqual( "+61.287654321 ext. 123 (label: Home)", f.clean(["+61", "287654321", "123", "Home"]), ) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(["61", "287654321", "123", "Home"]) # Empty values for fields will NOT raise a `required` error on an # optional `MultiValueField` f = PhoneField(required=False) self.assertIsNone(f.clean("")) self.assertIsNone(f.clean(None)) self.assertIsNone(f.clean([])) self.assertEqual("+61. ext. (label: )", f.clean(["+61"])) self.assertEqual( "+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"]) ) self.assertEqual( "+61.287654321 ext. 123 (label: Home)", f.clean(["+61", "287654321", "123", "Home"]), ) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(["61", "287654321", "123", "Home"]) # For a required `MultiValueField` with `require_all_fields=False`, a # `required` error will only be raised if all fields are empty. Fields # can individually be required or optional. An empty value for any # required field will raise an `incomplete` error. f = PhoneField(require_all_fields=False) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean([]) with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): f.clean(["+61"]) self.assertEqual( "+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"]) ) with self.assertRaisesMessage( ValidationError, "'Enter a complete value.', 'Enter an extension.'" ): f.clean(["", "", "", "Home"]) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(["61", "287654321", "123", "Home"]) # For an optional `MultiValueField` with `require_all_fields=False`, we # don't get any `required` error but we still get `incomplete` errors. f = PhoneField(required=False, require_all_fields=False) self.assertIsNone(f.clean("")) self.assertIsNone(f.clean(None)) self.assertIsNone(f.clean([])) with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): f.clean(["+61"]) self.assertEqual( "+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"]) ) with self.assertRaisesMessage( ValidationError, "'Enter a complete value.', 'Enter an extension.'" ): f.clean(["", "", "", "Home"]) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(["61", "287654321", "123", "Home"]) def test_multivalue_optional_subfields_rendering(self): class PhoneWidget(MultiWidget): def __init__(self, attrs=None): widgets = [TextInput(), TextInput()] super().__init__(widgets, attrs) def decompress(self, value): return [None, None] class PhoneField(MultiValueField): def __init__(self, *args, **kwargs): fields = [CharField(), CharField(required=False)] super().__init__(fields, *args, **kwargs) class PhoneForm(Form): phone1 = PhoneField(widget=PhoneWidget) phone2 = PhoneField(widget=PhoneWidget, required=False) phone3 = PhoneField(widget=PhoneWidget, require_all_fields=False) phone4 = PhoneField( widget=PhoneWidget, required=False, require_all_fields=False, ) form = PhoneForm(auto_id=False) self.assertHTMLEqual( form.as_p(), """ <p>Phone1:<input type="text" name="phone1_0" required> <input type="text" name="phone1_1" required></p> <p>Phone2:<input type="text" name="phone2_0"> <input type="text" name="phone2_1"></p> <p>Phone3:<input type="text" name="phone3_0" required> <input type="text" name="phone3_1"></p> <p>Phone4:<input type="text" name="phone4_0"> <input type="text" name="phone4_1"></p> """, ) def test_custom_empty_values(self): """ Form fields can customize what is considered as an empty value for themselves (#19997). """ class CustomJSONField(CharField): empty_values = [None, ""] def to_python(self, value): # Fake json.loads if value == "{}": return {} return super().to_python(value) class JSONForm(forms.Form): json = CustomJSONField() form = JSONForm(data={"json": "{}"}) form.full_clean() self.assertEqual(form.cleaned_data, {"json": {}}) def test_boundfield_label_tag(self): class SomeForm(Form): field = CharField() boundfield = SomeForm()["field"] testcases = [ # (args, kwargs, expected) # without anything: just print the <label> ((), {}, '<%(tag)s for="id_field">Field:</%(tag)s>'), # passing just one argument: overrides the field's label (("custom",), {}, '<%(tag)s for="id_field">custom:</%(tag)s>'), # the overridden label is escaped (("custom&",), {}, '<%(tag)s for="id_field">custom&amp;:</%(tag)s>'), ((mark_safe("custom&"),), {}, '<%(tag)s for="id_field">custom&:</%(tag)s>'), # Passing attrs to add extra attributes on the <label> ( (), {"attrs": {"class": "pretty"}}, '<%(tag)s for="id_field" class="pretty">Field:</%(tag)s>', ), ] for args, kwargs, expected in testcases: with self.subTest(args=args, kwargs=kwargs): self.assertHTMLEqual( boundfield.label_tag(*args, **kwargs), expected % {"tag": "label"}, ) self.assertHTMLEqual( boundfield.legend_tag(*args, **kwargs), expected % {"tag": "legend"}, ) def test_boundfield_label_tag_no_id(self): """ If a widget has no id, label_tag() and legend_tag() return the text with no surrounding <label>. """ class SomeForm(Form): field = CharField() boundfield = SomeForm(auto_id="")["field"] self.assertHTMLEqual(boundfield.label_tag(), "Field:") self.assertHTMLEqual(boundfield.legend_tag(), "Field:") self.assertHTMLEqual(boundfield.label_tag("Custom&"), "Custom&amp;:") self.assertHTMLEqual(boundfield.legend_tag("Custom&"), "Custom&amp;:") def test_boundfield_label_tag_custom_widget_id_for_label(self): class CustomIdForLabelTextInput(TextInput): def id_for_label(self, id): return "custom_" + id class EmptyIdForLabelTextInput(TextInput): def id_for_label(self, id): return None class SomeForm(Form): custom = CharField(widget=CustomIdForLabelTextInput) empty = CharField(widget=EmptyIdForLabelTextInput) form = SomeForm() self.assertHTMLEqual( form["custom"].label_tag(), '<label for="custom_id_custom">Custom:</label>' ) self.assertHTMLEqual( form["custom"].legend_tag(), '<legend for="custom_id_custom">Custom:</legend>', ) self.assertHTMLEqual(form["empty"].label_tag(), "<label>Empty:</label>") self.assertHTMLEqual(form["empty"].legend_tag(), "<legend>Empty:</legend>") def test_boundfield_empty_label(self): class SomeForm(Form): field = CharField(label="") boundfield = SomeForm()["field"] self.assertHTMLEqual(boundfield.label_tag(), '<label for="id_field"></label>') self.assertHTMLEqual( boundfield.legend_tag(), '<legend for="id_field"></legend>', ) def test_boundfield_id_for_label(self): class SomeForm(Form): field = CharField(label="") self.assertEqual(SomeForm()["field"].id_for_label, "id_field") def test_boundfield_id_for_label_override_by_attrs(self): """ If an id is provided in `Widget.attrs`, it overrides the generated ID, unless it is `None`. """ class SomeForm(Form): field = CharField(widget=TextInput(attrs={"id": "myCustomID"})) field_none = CharField(widget=TextInput(attrs={"id": None})) form = SomeForm() self.assertEqual(form["field"].id_for_label, "myCustomID") self.assertEqual(form["field_none"].id_for_label, "id_field_none") def test_boundfield_subwidget_id_for_label(self): """ If auto_id is provided when initializing the form, the generated ID in subwidgets must reflect that prefix. """ class SomeForm(Form): field = MultipleChoiceField( choices=[("a", "A"), ("b", "B")], widget=CheckboxSelectMultiple, ) form = SomeForm(auto_id="prefix_%s") subwidgets = form["field"].subwidgets self.assertEqual(subwidgets[0].id_for_label, "prefix_field_0") self.assertEqual(subwidgets[1].id_for_label, "prefix_field_1") def test_boundfield_widget_type(self): class SomeForm(Form): first_name = CharField() birthday = SplitDateTimeField(widget=SplitHiddenDateTimeWidget) f = SomeForm() self.assertEqual(f["first_name"].widget_type, "text") self.assertEqual(f["birthday"].widget_type, "splithiddendatetime") def test_boundfield_css_classes(self): form = Person() field = form["first_name"] self.assertEqual(field.css_classes(), "") self.assertEqual(field.css_classes(extra_classes=""), "") self.assertEqual(field.css_classes(extra_classes="test"), "test") self.assertEqual(field.css_classes(extra_classes="test test"), "test") def test_label_suffix_override(self): """ BoundField label_suffix (if provided) overrides Form label_suffix """ class SomeForm(Form): field = CharField() boundfield = SomeForm(label_suffix="!")["field"] self.assertHTMLEqual( boundfield.label_tag(label_suffix="$"), '<label for="id_field">Field$</label>', ) self.assertHTMLEqual( boundfield.legend_tag(label_suffix="$"), '<legend for="id_field">Field$</legend>', ) def test_error_dict(self): class MyForm(Form): foo = CharField() bar = CharField() def clean(self): raise ValidationError( "Non-field error.", code="secret", params={"a": 1, "b": 2} ) form = MyForm({}) self.assertIs(form.is_valid(), False) errors = form.errors.as_text() control = [ "* foo\n * This field is required.", "* bar\n * This field is required.", "* __all__\n * Non-field error.", ] for error in control: self.assertIn(error, errors) errors = form.errors.as_ul() control = [ '<li>foo<ul class="errorlist"><li>This field is required.</li></ul></li>', '<li>bar<ul class="errorlist"><li>This field is required.</li></ul></li>', '<li>__all__<ul class="errorlist nonfield"><li>Non-field error.</li></ul>' "</li>", ] for error in control: self.assertInHTML(error, errors) errors = form.errors.get_json_data() control = { "foo": [{"code": "required", "message": "This field is required."}], "bar": [{"code": "required", "message": "This field is required."}], "__all__": [{"code": "secret", "message": "Non-field error."}], } self.assertEqual(errors, control) self.assertEqual(json.dumps(errors), form.errors.as_json()) def test_error_dict_as_json_escape_html(self): """#21962 - adding html escape flag to ErrorDict""" class MyForm(Form): foo = CharField() bar = CharField() def clean(self): raise ValidationError( "<p>Non-field error.</p>", code="secret", params={"a": 1, "b": 2}, ) control = { "foo": [{"code": "required", "message": "This field is required."}], "bar": [{"code": "required", "message": "This field is required."}], "__all__": [{"code": "secret", "message": "<p>Non-field error.</p>"}], } form = MyForm({}) self.assertFalse(form.is_valid()) errors = json.loads(form.errors.as_json()) self.assertEqual(errors, control) escaped_error = "&lt;p&gt;Non-field error.&lt;/p&gt;" self.assertEqual( form.errors.get_json_data(escape_html=True)["__all__"][0]["message"], escaped_error, ) errors = json.loads(form.errors.as_json(escape_html=True)) control["__all__"][0]["message"] = escaped_error self.assertEqual(errors, control) def test_error_list(self): e = ErrorList() e.append("Foo") e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"})) self.assertIsInstance(e, list) self.assertIn("Foo", e) self.assertIn("Foo", ValidationError(e)) self.assertEqual(e.as_text(), "* Foo\n* Foobar") self.assertEqual( e.as_ul(), '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>' ) errors = e.get_json_data() self.assertEqual( errors, [{"message": "Foo", "code": ""}, {"message": "Foobar", "code": "foobar"}], ) self.assertEqual(json.dumps(errors), e.as_json()) def test_error_list_class_not_specified(self): e = ErrorList() e.append("Foo") e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"})) self.assertEqual( e.as_ul(), '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>' ) def test_error_list_class_has_one_class_specified(self): e = ErrorList(error_class="foobar-error-class") e.append("Foo") e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"})) self.assertEqual( e.as_ul(), '<ul class="errorlist foobar-error-class"><li>Foo</li><li>Foobar</li></ul>', ) def test_error_list_with_hidden_field_errors_has_correct_class(self): class Person(Form): first_name = CharField() last_name = CharField(widget=HiddenInput) p = Person({"first_name": "John"}) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist nonfield"> <li>(Hidden field last_name) This field is required.</li></ul></li><li> <label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></li>""", ) self.assertHTMLEqual( p.as_p(), """ <ul class="errorlist nonfield"> <li>(Hidden field last_name) This field is required.</li></ul> <p><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></p> """, ) self.assertHTMLEqual( p.as_table(), """<tr><td colspan="2"><ul class="errorlist nonfield"> <li>(Hidden field last_name) This field is required.</li></ul></td></tr> <tr><th><label for="id_first_name">First name:</label></th><td> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></td></tr>""", ) self.assertHTMLEqual( p.as_div(), '<ul class="errorlist nonfield"><li>(Hidden field last_name) This field ' 'is required.</li></ul><div><label for="id_first_name">First name:</label>' '<input id="id_first_name" name="first_name" type="text" value="John" ' 'required><input id="id_last_name" name="last_name" type="hidden"></div>', ) def test_error_list_with_non_field_errors_has_correct_class(self): class Person(Form): first_name = CharField() last_name = CharField() def clean(self): raise ValidationError("Generic validation error") p = Person({"first_name": "John", "last_name": "Lennon"}) self.assertHTMLEqual( str(p.non_field_errors()), '<ul class="errorlist nonfield"><li>Generic validation error</li></ul>', ) self.assertHTMLEqual( p.as_ul(), """<li> <ul class="errorlist nonfield"><li>Generic validation error</li></ul></li> <li><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required></li> <li><label for="id_last_name">Last name:</label> <input id="id_last_name" name="last_name" type="text" value="Lennon" required></li>""", ) self.assertHTMLEqual( p.non_field_errors().as_text(), "* Generic validation error" ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist nonfield"><li>Generic validation error</li></ul> <p><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required></p> <p><label for="id_last_name">Last name:</label> <input id="id_last_name" name="last_name" type="text" value="Lennon" required></p>""", ) self.assertHTMLEqual( p.as_table(), """ <tr><td colspan="2"><ul class="errorlist nonfield"> <li>Generic validation error</li></ul></td></tr> <tr><th><label for="id_first_name">First name:</label></th><td> <input id="id_first_name" name="first_name" type="text" value="John" required> </td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input id="id_last_name" name="last_name" type="text" value="Lennon" required> </td></tr> """, ) self.assertHTMLEqual( p.as_div(), '<ul class="errorlist nonfield"><li>Generic validation error</li></ul>' '<div><label for="id_first_name">First name:</label><input ' 'id="id_first_name" name="first_name" type="text" value="John" required>' '</div><div><label for="id_last_name">Last name:</label><input ' 'id="id_last_name" name="last_name" type="text" value="Lennon" required>' "</div>", ) def test_error_escaping(self): class TestForm(Form): hidden = CharField(widget=HiddenInput(), required=False) visible = CharField() def clean_hidden(self): raise ValidationError('Foo & "bar"!') clean_visible = clean_hidden form = TestForm({"hidden": "a", "visible": "b"}) form.is_valid() self.assertHTMLEqual( form.as_ul(), '<li><ul class="errorlist nonfield">' "<li>(Hidden field hidden) Foo &amp; &quot;bar&quot;!</li></ul></li>" '<li><ul class="errorlist"><li>Foo &amp; &quot;bar&quot;!</li></ul>' '<label for="id_visible">Visible:</label> ' '<input type="text" name="visible" value="b" id="id_visible" required>' '<input type="hidden" name="hidden" value="a" id="id_hidden"></li>', ) def test_baseform_repr(self): """ BaseForm.__repr__() should contain some basic information about the form. """ p = Person() self.assertEqual( repr(p), "<Person bound=False, valid=Unknown, " "fields=(first_name;last_name;birthday)>", ) p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"} ) self.assertEqual( repr(p), "<Person bound=True, valid=Unknown, " "fields=(first_name;last_name;birthday)>", ) p.is_valid() self.assertEqual( repr(p), "<Person bound=True, valid=True, fields=(first_name;last_name;birthday)>", ) p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "fakedate"} ) p.is_valid() self.assertEqual( repr(p), "<Person bound=True, valid=False, fields=(first_name;last_name;birthday)>", ) def test_baseform_repr_dont_trigger_validation(self): """ BaseForm.__repr__() shouldn't trigger the form validation. """ p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "fakedate"} ) repr(p) with self.assertRaises(AttributeError): p.cleaned_data self.assertFalse(p.is_valid()) self.assertEqual(p.cleaned_data, {"first_name": "John", "last_name": "Lennon"}) def test_accessing_clean(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): data = self.cleaned_data if not self.errors: data["username"] = data["username"].lower() return data f = UserForm({"username": "SirRobin", "password": "blue"}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["username"], "sirrobin") def test_changing_cleaned_data_nothing_returned(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): self.cleaned_data["username"] = self.cleaned_data["username"].lower() # don't return anything f = UserForm({"username": "SirRobin", "password": "blue"}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["username"], "sirrobin") def test_changing_cleaned_data_in_clean(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): data = self.cleaned_data # Return a different dict. We have not changed self.cleaned_data. return { "username": data["username"].lower(), "password": "this_is_not_a_secret", } f = UserForm({"username": "SirRobin", "password": "blue"}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["username"], "sirrobin") def test_multipart_encoded_form(self): class FormWithoutFile(Form): username = CharField() class FormWithFile(Form): username = CharField() file = FileField() class FormWithImage(Form): image = ImageField() self.assertFalse(FormWithoutFile().is_multipart()) self.assertTrue(FormWithFile().is_multipart()) self.assertTrue(FormWithImage().is_multipart()) def test_html_safe(self): class SimpleForm(Form): username = CharField() form = SimpleForm() self.assertTrue(hasattr(SimpleForm, "__html__")) self.assertEqual(str(form), form.__html__()) self.assertTrue(hasattr(form["username"], "__html__")) self.assertEqual(str(form["username"]), form["username"].__html__()) def test_use_required_attribute_true(self): class MyForm(Form): use_required_attribute = True f1 = CharField(max_length=30) f2 = CharField(max_length=30, required=False) f3 = CharField(widget=Textarea) f4 = ChoiceField(choices=[("P", "Python"), ("J", "Java")]) form = MyForm() self.assertHTMLEqual( form.as_p(), '<p><label for="id_f1">F1:</label>' '<input id="id_f1" maxlength="30" name="f1" type="text" required></p>' '<p><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></p>' '<p><label for="id_f3">F3:</label>' '<textarea cols="40" id="id_f3" name="f3" rows="10" required>' "</textarea></p>" '<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></p>", ) self.assertHTMLEqual( form.as_ul(), '<li><label for="id_f1">F1:</label> ' '<input id="id_f1" maxlength="30" name="f1" type="text" required></li>' '<li><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></li>' '<li><label for="id_f3">F3:</label>' '<textarea cols="40" id="id_f3" name="f3" rows="10" required>' "</textarea></li>" '<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></li>", ) self.assertHTMLEqual( form.as_table(), '<tr><th><label for="id_f1">F1:</label></th>' '<td><input id="id_f1" maxlength="30" name="f1" type="text" required>' "</td></tr>" '<tr><th><label for="id_f2">F2:</label></th>' '<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>' '<tr><th><label for="id_f3">F3:</label></th>' '<td><textarea cols="40" id="id_f3" name="f3" rows="10" required>' "</textarea></td></tr>" '<tr><th><label for="id_f4">F4:</label></th><td>' '<select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></td></tr>", ) self.assertHTMLEqual( form.render(form.template_name_div), '<div><label for="id_f1">F1:</label><input id="id_f1" maxlength="30" ' 'name="f1" type="text" required></div><div><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></div><div><label ' 'for="id_f3">F3:</label><textarea cols="40" id="id_f3" name="f3" ' 'rows="10" required></textarea></div><div><label for="id_f4">F4:</label>' '<select id="id_f4" name="f4"><option value="P">Python</option>' '<option value="J">Java</option></select></div>', ) def test_use_required_attribute_false(self): class MyForm(Form): use_required_attribute = False f1 = CharField(max_length=30) f2 = CharField(max_length=30, required=False) f3 = CharField(widget=Textarea) f4 = ChoiceField(choices=[("P", "Python"), ("J", "Java")]) form = MyForm() self.assertHTMLEqual( form.as_p(), '<p><label for="id_f1">F1:</label>' '<input id="id_f1" maxlength="30" name="f1" type="text"></p>' '<p><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></p>' '<p><label for="id_f3">F3:</label>' '<textarea cols="40" id="id_f3" name="f3" rows="10"></textarea></p>' '<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></p>", ) self.assertHTMLEqual( form.as_ul(), '<li><label for="id_f1">F1:</label>' '<input id="id_f1" maxlength="30" name="f1" type="text"></li>' '<li><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></li>' '<li><label for="id_f3">F3:</label>' '<textarea cols="40" id="id_f3" name="f3" rows="10"></textarea></li>' '<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></li>", ) self.assertHTMLEqual( form.as_table(), '<tr><th><label for="id_f1">F1:</label></th>' '<td><input id="id_f1" maxlength="30" name="f1" type="text"></td></tr>' '<tr><th><label for="id_f2">F2:</label></th>' '<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>' '<tr><th><label for="id_f3">F3:</label></th><td>' '<textarea cols="40" id="id_f3" name="f3" rows="10">' "</textarea></td></tr>" '<tr><th><label for="id_f4">F4:</label></th><td>' '<select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></td></tr>", ) self.assertHTMLEqual( form.render(form.template_name_div), '<div><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" ' 'name="f1" type="text"></div><div><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></div><div>' '<label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" ' 'rows="10"></textarea></div><div><label for="id_f4">F4:</label>' '<select id="id_f4" name="f4"><option value="P">Python</option>' '<option value="J">Java</option></select></div>', ) def test_only_hidden_fields(self): # A form with *only* hidden fields that has errors is going to be very unusual. class HiddenForm(Form): data = IntegerField(widget=HiddenInput) f = HiddenForm({}) self.assertHTMLEqual( f.as_p(), '<ul class="errorlist nonfield">' "<li>(Hidden field data) This field is required.</li></ul>\n<p> " '<input type="hidden" name="data" id="id_data"></p>', ) self.assertHTMLEqual( f.as_table(), '<tr><td colspan="2"><ul class="errorlist nonfield">' "<li>(Hidden field data) This field is required.</li></ul>" '<input type="hidden" name="data" id="id_data"></td></tr>', ) def test_field_named_data(self): class DataForm(Form): data = CharField(max_length=10) f = DataForm({"data": "xyzzy"}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data, {"data": "xyzzy"}) def test_empty_data_files_multi_value_dict(self): p = Person() self.assertIsInstance(p.data, MultiValueDict) self.assertIsInstance(p.files, MultiValueDict) def test_field_deep_copy_error_messages(self): class CustomCharField(CharField): def __init__(self, **kwargs): kwargs["error_messages"] = {"invalid": "Form custom error message."} super().__init__(**kwargs) field = CustomCharField() field_copy = copy.deepcopy(field) self.assertIsInstance(field_copy, CustomCharField) self.assertIsNot(field_copy.error_messages, field.error_messages) def test_label_does_not_include_new_line(self): form = Person() field = form["first_name"] self.assertEqual( field.label_tag(), '<label for="id_first_name">First name:</label>' ) self.assertEqual( field.legend_tag(), '<legend for="id_first_name">First name:</legend>', ) @override_settings(USE_THOUSAND_SEPARATOR=True) def test_label_attrs_not_localized(self): form = Person() field = form["first_name"] self.assertHTMLEqual( field.label_tag(attrs={"number": 9999}), '<label number="9999" for="id_first_name">First name:</label>', ) self.assertHTMLEqual( field.legend_tag(attrs={"number": 9999}), '<legend number="9999" for="id_first_name">First name:</legend>', ) def test_remove_cached_field(self): class TestForm(Form): name = CharField(max_length=10) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Populate fields cache. [field for field in self] # Removed cached field. del self.fields["name"] f = TestForm({"name": "abcde"}) with self.assertRaises(KeyError): f["name"] @jinja2_tests class Jinja2FormsTestCase(FormsTestCase): pass class CustomRenderer(DjangoTemplates): form_template_name = "forms_tests/form_snippet.html" field_template_name = "forms_tests/custom_field.html" class RendererTests(SimpleTestCase): def test_default(self): form = Form() self.assertEqual(form.renderer, get_default_renderer()) def test_kwarg_instance(self): custom = CustomRenderer() form = Form(renderer=custom) self.assertEqual(form.renderer, custom) def test_kwarg_class(self): custom = CustomRenderer() form = Form(renderer=custom) self.assertEqual(form.renderer, custom) def test_attribute_instance(self): class CustomForm(Form): default_renderer = DjangoTemplates() form = CustomForm() self.assertEqual(form.renderer, CustomForm.default_renderer) def test_attribute_class(self): class CustomForm(Form): default_renderer = CustomRenderer form = CustomForm() self.assertIsInstance(form.renderer, CustomForm.default_renderer) def test_attribute_override(self): class CustomForm(Form): default_renderer = DjangoTemplates() custom = CustomRenderer() form = CustomForm(renderer=custom) self.assertEqual(form.renderer, custom) class TemplateTests(SimpleTestCase): def test_iterate_radios(self): f = FrameworkForm(auto_id="id_%s") t = Template( "{% for radio in form.language %}" '<div class="myradio">{{ radio }}</div>' "{% endfor %}" ) self.assertHTMLEqual( t.render(Context({"form": f})), '<div class="myradio"><label for="id_language_0">' '<input id="id_language_0" name="language" type="radio" value="P" ' "required> Python</label></div>" '<div class="myradio"><label for="id_language_1">' '<input id="id_language_1" name="language" type="radio" value="J" ' "required> Java</label></div>", ) def test_iterate_checkboxes(self): f = SongForm({"composers": ["J", "P"]}, auto_id=False) t = Template( "{% for checkbox in form.composers %}" '<div class="mycheckbox">{{ checkbox }}</div>' "{% endfor %}" ) self.assertHTMLEqual( t.render(Context({"form": f})), '<div class="mycheckbox"><label>' '<input checked name="composers" type="checkbox" value="J"> ' "John Lennon</label></div>" '<div class="mycheckbox"><label>' '<input checked name="composers" type="checkbox" value="P"> ' "Paul McCartney</label></div>", ) def test_templates_with_forms(self): class UserRegistration(Form): username = CharField( max_length=10, help_text=("Good luck picking a username that doesn't already exist."), ) password1 = CharField(widget=PasswordInput) 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"] ): raise ValidationError("Please make sure your passwords match.") return self.cleaned_data # There is full flexibility in displaying form fields in a template. # Just pass a Form instance to the template, and use "dot" access to # refer to individual fields. However, this flexibility comes with the # responsibility of displaying all the errors, including any that might # not be associated with a particular field. t = Template( "<form>" "{{ form.username.errors.as_ul }}" "<p><label>Your username: {{ form.username }}</label></p>" "{{ form.password1.errors.as_ul }}" "<p><label>Password: {{ form.password1 }}</label></p>" "{{ form.password2.errors.as_ul }}" "<p><label>Password (again): {{ form.password2 }}</label></p>" '<input type="submit" required>' "</form>" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p><label>Your username: " '<input type="text" name="username" maxlength="10" required></label></p>' "<p><label>Password: " '<input type="password" name="password1" required></label></p>' "<p><label>Password (again): " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) f = UserRegistration({"username": "django"}, auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p><label>Your username: " '<input type="text" name="username" value="django" maxlength="10" required>' "</label></p>" '<ul class="errorlist"><li>This field is required.</li></ul><p>' "<label>Password: " '<input type="password" name="password1" required></label></p>' '<ul class="errorlist"><li>This field is required.</li></ul>' "<p><label>Password (again): " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) # Use form.[field].label to output a field's label. 'label' for a field # can by specified by using the 'label' argument to a Field class. If # 'label' is not specified, Django will use the field name with # underscores converted to spaces, and the initial letter capitalized. t = Template( "<form>" "<p><label>{{ form.username.label }}: {{ form.username }}</label></p>" "<p><label>{{ form.password1.label }}: {{ form.password1 }}</label></p>" "<p><label>{{ form.password2.label }}: {{ form.password2 }}</label></p>" '<input type="submit" required>' "</form>" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p><label>Username: " '<input type="text" name="username" maxlength="10" required></label></p>' "<p><label>Password1: " '<input type="password" name="password1" required></label></p>' "<p><label>Password2: " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) # Use form.[field].label_tag to output a field's label with a <label> # tag wrapped around it, but *only* if the given field has an "id" # attribute. Recall from above that passing the "auto_id" argument to a # Form gives each field an "id" attribute. t = Template( "<form>" "<p>{{ form.username.label_tag }} {{ form.username }}</p>" "<p>{{ form.password1.label_tag }} {{ form.password1 }}</p>" "<p>{{ form.password2.label_tag }} {{ form.password2 }}</p>" '<input type="submit" required>' "</form>" ) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p>Username: " '<input type="text" name="username" maxlength="10" required></p>' '<p>Password1: <input type="password" name="password1" required></p>' '<p>Password2: <input type="password" name="password2" required></p>' '<input type="submit" required>' "</form>", ) f = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" '<p><label for="id_username">Username:</label>' '<input id="id_username" type="text" name="username" maxlength="10" ' 'aria-describedby="id_username_helptext" required></p>' '<p><label for="id_password1">Password1:</label>' '<input type="password" name="password1" id="id_password1" required></p>' '<p><label for="id_password2">Password2:</label>' '<input type="password" name="password2" id="id_password2" required></p>' '<input type="submit" required>' "</form>", ) # Use form.[field].legend_tag to output a field's label with a <legend> # tag wrapped around it, but *only* if the given field has an "id" # attribute. Recall from above that passing the "auto_id" argument to a # Form gives each field an "id" attribute. t = Template( "<form>" "<p>{{ form.username.legend_tag }} {{ form.username }}</p>" "<p>{{ form.password1.legend_tag }} {{ form.password1 }}</p>" "<p>{{ form.password2.legend_tag }} {{ form.password2 }}</p>" '<input type="submit" required>' "</form>" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p>Username: " '<input type="text" name="username" maxlength="10" required></p>' '<p>Password1: <input type="password" name="password1" required></p>' '<p>Password2: <input type="password" name="password2" required></p>' '<input type="submit" required>' "</form>", ) f = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" '<p><legend for="id_username">Username:</legend>' '<input id="id_username" type="text" name="username" maxlength="10" ' 'aria-describedby="id_username_helptext" required></p>' '<p><legend for="id_password1">Password1:</legend>' '<input type="password" name="password1" id="id_password1" required></p>' '<p><legend for="id_password2">Password2:</legend>' '<input type="password" name="password2" id="id_password2" required></p>' '<input type="submit" required>' "</form>", ) # Use form.[field].help_text to output a field's help text. If the # given field does not have help text, nothing will be output. t = Template( "<form>" "<p>{{ form.username.label_tag }} {{ form.username }}<br>" "{{ form.username.help_text }}</p>" "<p>{{ form.password1.label_tag }} {{ form.password1 }}</p>" "<p>{{ form.password2.label_tag }} {{ form.password2 }}</p>" '<input type="submit" required>' "</form>" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p>Username: " '<input type="text" name="username" maxlength="10" required><br>' "Good luck picking a username that doesn&#x27;t already exist.</p>" '<p>Password1: <input type="password" name="password1" required></p>' '<p>Password2: <input type="password" name="password2" required></p>' '<input type="submit" required>' "</form>", ) self.assertEqual( Template("{{ form.password1.help_text }}").render(Context({"form": f})), "", ) # 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 template. If used on its own, it # is displayed as a <ul> (or an empty string, if the list of errors is # empty). t = Template( "<form>" "{{ form.username.errors.as_ul }}" "<p><label>Your username: {{ form.username }}</label></p>" "{{ form.password1.errors.as_ul }}" "<p><label>Password: {{ form.password1 }}</label></p>" "{{ form.password2.errors.as_ul }}" "<p><label>Password (again): {{ form.password2 }}</label></p>" '<input type="submit" required>' "</form>" ) f = UserRegistration( {"username": "django", "password1": "foo", "password2": "bar"}, auto_id=False, ) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p><label>Your username: " '<input type="text" name="username" value="django" maxlength="10" required>' "</label></p>" "<p><label>Password: " '<input type="password" name="password1" required></label></p>' "<p><label>Password (again): " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) t = Template( "<form>" "{{ form.non_field_errors }}" "{{ form.username.errors.as_ul }}" "<p><label>Your username: {{ form.username }}</label></p>" "{{ form.password1.errors.as_ul }}" "<p><label>Password: {{ form.password1 }}</label></p>" "{{ form.password2.errors.as_ul }}" "<p><label>Password (again): {{ form.password2 }}</label></p>" '<input type="submit" required>' "</form>" ) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" '<ul class="errorlist nonfield">' "<li>Please make sure your passwords match.</li></ul>" "<p><label>Your username: " '<input type="text" name="username" value="django" maxlength="10" required>' "</label></p>" "<p><label>Password: " '<input type="password" name="password1" required></label></p>' "<p><label>Password (again): " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) def test_basic_processing_in_view(self): class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) 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"] ): raise ValidationError("Please make sure your passwords match.") return self.cleaned_data def my_function(method, post_data): if method == "POST": form = UserRegistration(post_data, auto_id=False) else: form = UserRegistration(auto_id=False) if form.is_valid(): return "VALID: %r" % sorted(form.cleaned_data.items()) t = Template( '<form method="post">' "{{ form }}" '<input type="submit" required>' "</form>" ) return t.render(Context({"form": form})) # GET with an empty form and no errors. self.assertHTMLEqual( my_function("GET", {}), '<form method="post">' "<div>Username:" '<input type="text" name="username" maxlength="10" required></div>' "<div>Password1:" '<input type="password" name="password1" required></div>' "<div>Password2:" '<input type="password" name="password2" required></div>' '<input type="submit" required>' "</form>", ) # POST with erroneous data, a redisplayed form, with errors. self.assertHTMLEqual( my_function( "POST", { "username": "this-is-a-long-username", "password1": "foo", "password2": "bar", }, ), '<form method="post">' '<ul class="errorlist nonfield">' "<li>Please make sure your passwords match.</li></ul>" '<div>Username:<ul class="errorlist">' "<li>Ensure this value has at most 10 characters (it has 23).</li></ul>" '<input type="text" name="username" ' 'value="this-is-a-long-username" maxlength="10" required></div>' "<div>Password1:" '<input type="password" name="password1" required></div>' "<div>Password2:" '<input type="password" name="password2" required></div>' '<input type="submit" required>' "</form>", ) # POST with valid data (the success message). self.assertEqual( my_function( "POST", { "username": "adrian", "password1": "secret", "password2": "secret", }, ), "VALID: [('password1', 'secret'), ('password2', 'secret'), " "('username', 'adrian')]", ) def test_custom_field_template(self): class MyForm(Form): first_name = CharField(template_name="forms_tests/custom_field.html") f = MyForm() self.assertHTMLEqual( f.render(), '<div><label for="id_first_name">First name:</label><p>Custom Field<p>' '<input type="text" name="first_name" required id="id_first_name"></div>', ) def test_custom_field_render_template(self): class MyForm(Form): first_name = CharField() f = MyForm() self.assertHTMLEqual( f["first_name"].render(template_name="forms_tests/custom_field.html"), '<label for="id_first_name">First name:</label><p>Custom Field<p>' '<input type="text" name="first_name" required id="id_first_name">', ) class OverrideTests(SimpleTestCase): @override_settings(FORM_RENDERER="forms_tests.tests.test_forms.CustomRenderer") def test_custom_renderer_template_name(self): class Person(Form): first_name = CharField() get_default_renderer.cache_clear() t = Template("{{ form }}") html = t.render(Context({"form": Person()})) expected = """ <div class="fieldWrapper"><label for="id_first_name">First name:</label> <input type="text" name="first_name" required id="id_first_name"></div> """ self.assertHTMLEqual(html, expected) get_default_renderer.cache_clear() @override_settings(FORM_RENDERER="forms_tests.tests.test_forms.CustomRenderer") def test_custom_renderer_field_template_name(self): class Person(Form): first_name = CharField() get_default_renderer.cache_clear() t = Template("{{ form.first_name.as_field_group }}") html = t.render(Context({"form": Person()})) expected = """ <label for="id_first_name">First name:</label> <p>Custom Field<p> <input type="text" name="first_name" required id="id_first_name"> """ self.assertHTMLEqual(html, expected) get_default_renderer.cache_clear() def test_per_form_template_name(self): class Person(Form): first_name = CharField() template_name = "forms_tests/form_snippet.html" t = Template("{{ form }}") html = t.render(Context({"form": Person()})) expected = """ <div class="fieldWrapper"><label for="id_first_name">First name:</label> <input type="text" name="first_name" required id="id_first_name"></div> """ self.assertHTMLEqual(html, expected) def test_errorlist_override(self): class CustomErrorList(ErrorList): template_name = "forms_tests/error.html" class CommentForm(Form): name = CharField(max_length=50, required=False) email = EmailField() comment = CharField() data = {"email": "invalid"} f = CommentForm(data, auto_id=False, error_class=CustomErrorList) self.assertHTMLEqual( f.as_p(), '<p>Name: <input type="text" name="name" maxlength="50"></p>' '<div class="errorlist">' '<div class="error">Enter a valid email address.</div></div>' "<p>Email: " '<input type="email" name="email" value="invalid" maxlength="320" required>' '</p><div class="errorlist">' '<div class="error">This field is required.</div></div>' '<p>Comment: <input type="text" name="comment" required></p>', ) def test_cyclic_context_boundfield_render(self): class FirstNameForm(Form): first_name = CharField() template_name_label = "forms_tests/cyclic_context_boundfield_render.html" f = FirstNameForm() try: f.render() except RecursionError: self.fail("Cyclic reference in BoundField.render().") def test_legend_tag(self): class CustomFrameworkForm(FrameworkForm): template_name = "forms_tests/legend_test.html" required_css_class = "required" f = CustomFrameworkForm() self.assertHTMLEqual( str(f), '<label for="id_name" class="required">Name:</label>' '<legend class="required">Language:</legend>', )
54b3e87efb6d49e984621a054cbca5168c6e9a68290d8005b42bd405d5433a90
from django import template from django.template.defaultfilters import stringfilter from django.utils.html import escape, format_html from django.utils.safestring import mark_safe register = template.Library() @register.filter @stringfilter def trim(value, num): return value[:num] @register.filter @mark_safe def make_data_div(value): """A filter that uses a decorator (@mark_safe).""" return '<div data-name="%s"></div>' % value @register.filter def noop(value, param=None): """A noop filter that always return its first argument and does nothing with its second (optional) one. Useful for testing out whitespace in filter arguments (see #19882).""" return value @register.simple_tag(takes_context=True) def context_stack_length(context): return len(context.dicts) @register.simple_tag def no_params(): """Expected no_params __doc__""" return "no_params - Expected result" no_params.anything = "Expected no_params __dict__" @register.simple_tag def one_param(arg): """Expected one_param __doc__""" return "one_param - Expected result: %s" % arg one_param.anything = "Expected one_param __dict__" @register.simple_tag(takes_context=False) def explicit_no_context(arg): """Expected explicit_no_context __doc__""" return "explicit_no_context - Expected result: %s" % arg explicit_no_context.anything = "Expected explicit_no_context __dict__" @register.simple_tag(takes_context=True) def no_params_with_context(context): """Expected no_params_with_context __doc__""" return ( "no_params_with_context - Expected result (context value: %s)" % context["value"] ) no_params_with_context.anything = "Expected no_params_with_context __dict__" @register.simple_tag(takes_context=True) def params_and_context(context, arg): """Expected params_and_context __doc__""" return "params_and_context - Expected result (context value: %s): %s" % ( context["value"], arg, ) params_and_context.anything = "Expected params_and_context __dict__" @register.simple_tag def simple_two_params(one, two): """Expected simple_two_params __doc__""" return "simple_two_params - Expected result: %s, %s" % (one, two) simple_two_params.anything = "Expected simple_two_params __dict__" @register.simple_tag def simple_keyword_only_param(*, kwarg): return "simple_keyword_only_param - Expected result: %s" % kwarg @register.simple_tag def simple_keyword_only_default(*, kwarg=42): return "simple_keyword_only_default - Expected result: %s" % kwarg @register.simple_tag def simple_one_default(one, two="hi"): """Expected simple_one_default __doc__""" return "simple_one_default - Expected result: %s, %s" % (one, two) 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(str(arg) for arg in [one, two, *args]) ) simple_unlimited_args.anything = "Expected simple_unlimited_args __dict__" @register.simple_tag def simple_only_unlimited_args(*args): """Expected simple_only_unlimited_args __doc__""" return "simple_only_unlimited_args - Expected result: %s" % ", ".join( str(arg) for arg in args ) simple_only_unlimited_args.anything = "Expected simple_only_unlimited_args __dict__" @register.simple_tag def simple_unlimited_args_kwargs(one, two="hi", *args, **kwargs): """Expected simple_unlimited_args_kwargs __doc__""" return "simple_unlimited_args_kwargs - Expected result: %s / %s" % ( ", ".join(str(arg) for arg in [one, two, *args]), ", ".join("%s=%s" % (k, v) for (k, v) in kwargs.items()), ) simple_unlimited_args_kwargs.anything = "Expected simple_unlimited_args_kwargs __dict__" @register.simple_tag(takes_context=True) def simple_tag_without_context_parameter(arg): """Expected simple_tag_without_context_parameter __doc__""" return "Expected result" simple_tag_without_context_parameter.anything = ( "Expected simple_tag_without_context_parameter __dict__" ) @register.simple_tag(takes_context=True) def simple_tag_takes_context_without_params(): """Expected simple_tag_takes_context_without_params __doc__""" return "Expected result" simple_tag_takes_context_without_params.anything = ( "Expected simple_tag_takes_context_without_params __dict__" ) @register.simple_tag(takes_context=True) def escape_naive(context): """A tag that doesn't even think about escaping issues""" return "Hello {}!".format(context["name"]) @register.simple_tag(takes_context=True) def escape_explicit(context): """A tag that uses escape explicitly""" return escape("Hello {}!".format(context["name"])) @register.simple_tag(takes_context=True) def escape_format_html(context): """A tag that uses format_html""" return format_html("Hello {0}!", context["name"]) @register.simple_tag(takes_context=True) def current_app(context): return str(context.current_app) @register.simple_tag(takes_context=True) def use_l10n(context): return str(context.use_l10n) @register.simple_tag(name="minustwo") def minustwo_overridden_name(value): return value - 2 register.simple_tag(lambda x: x - 1, name="minusone") @register.tag("counter") def counter(parser, token): return CounterNode() class CounterNode(template.Node): def __init__(self): self.count = 0 def render(self, context): count = self.count self.count = count + 1 return str(count)
7ecf9f6bcc793b25f590a00c79d001b92002881996b54fb952d858159e20acef
from django.template import Engine, Library engine = Engine(app_dirs=True) register = Library() @register.inclusion_tag("inclusion.html") def inclusion_no_params(): """Expected inclusion_no_params __doc__""" return {"result": "inclusion_no_params - Expected result"} inclusion_no_params.anything = "Expected inclusion_no_params __dict__" @register.inclusion_tag(engine.get_template("inclusion.html")) def inclusion_no_params_from_template(): """Expected inclusion_no_params_from_template __doc__""" return {"result": "inclusion_no_params_from_template - Expected result"} inclusion_no_params_from_template.anything = ( "Expected inclusion_no_params_from_template __dict__" ) @register.inclusion_tag("inclusion.html") def inclusion_one_param(arg): """Expected inclusion_one_param __doc__""" return {"result": "inclusion_one_param - Expected result: %s" % arg} inclusion_one_param.anything = "Expected inclusion_one_param __dict__" @register.inclusion_tag(engine.get_template("inclusion.html")) def inclusion_one_param_from_template(arg): """Expected inclusion_one_param_from_template __doc__""" return {"result": "inclusion_one_param_from_template - Expected result: %s" % arg} inclusion_one_param_from_template.anything = ( "Expected inclusion_one_param_from_template __dict__" ) @register.inclusion_tag("inclusion.html", takes_context=False) def inclusion_explicit_no_context(arg): """Expected inclusion_explicit_no_context __doc__""" return {"result": "inclusion_explicit_no_context - Expected result: %s" % arg} inclusion_explicit_no_context.anything = ( "Expected inclusion_explicit_no_context __dict__" ) @register.inclusion_tag(engine.get_template("inclusion.html"), takes_context=False) def inclusion_explicit_no_context_from_template(arg): """Expected inclusion_explicit_no_context_from_template __doc__""" return { "result": "inclusion_explicit_no_context_from_template - Expected result: %s" % arg } inclusion_explicit_no_context_from_template.anything = ( "Expected inclusion_explicit_no_context_from_template __dict__" ) @register.inclusion_tag("inclusion.html", takes_context=True) def inclusion_no_params_with_context(context): """Expected inclusion_no_params_with_context __doc__""" return { "result": ( "inclusion_no_params_with_context - Expected result (context value: %s)" ) % context["value"] } inclusion_no_params_with_context.anything = ( "Expected inclusion_no_params_with_context __dict__" ) @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__" ) @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) } 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) ) } inclusion_params_and_context_from_template.anything = ( "Expected inclusion_params_and_context_from_template __dict__" ) @register.inclusion_tag("inclusion.html") def inclusion_two_params(one, two): """Expected inclusion_two_params __doc__""" return {"result": "inclusion_two_params - Expected result: %s, %s" % (one, two)} inclusion_two_params.anything = "Expected inclusion_two_params __dict__" @register.inclusion_tag(engine.get_template("inclusion.html")) def inclusion_two_params_from_template(one, two): """Expected inclusion_two_params_from_template __doc__""" return { "result": "inclusion_two_params_from_template - Expected result: %s, %s" % (one, two) } inclusion_two_params_from_template.anything = ( "Expected inclusion_two_params_from_template __dict__" ) @register.inclusion_tag("inclusion.html") def inclusion_one_default(one, two="hi"): """Expected inclusion_one_default __doc__""" return {"result": "inclusion_one_default - Expected result: %s, %s" % (one, two)} inclusion_one_default.anything = "Expected inclusion_one_default __dict__" @register.inclusion_tag("inclusion.html") def inclusion_keyword_only_default(*, kwarg=42): return { "result": ("inclusion_keyword_only_default - Expected result: %s" % kwarg), } @register.inclusion_tag(engine.get_template("inclusion.html")) def inclusion_one_default_from_template(one, two="hi"): """Expected inclusion_one_default_from_template __doc__""" return { "result": "inclusion_one_default_from_template - Expected result: %s, %s" % (one, two) } inclusion_one_default_from_template.anything = ( "Expected inclusion_one_default_from_template __dict__" ) @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(str(arg) for arg in [one, two, *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(str(arg) for arg in [one, two, *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(str(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(str(arg) for arg in args)) } inclusion_only_unlimited_args_from_template.anything = ( "Expected inclusion_only_unlimited_args_from_template __dict__" ) @register.inclusion_tag("test_incl_tag_use_l10n.html", takes_context=True) def inclusion_tag_use_l10n(context): """Expected inclusion_tag_use_l10n __doc__""" return {} inclusion_tag_use_l10n.anything = "Expected inclusion_tag_use_l10n __dict__" @register.inclusion_tag("inclusion.html") def inclusion_unlimited_args_kwargs(one, two="hi", *args, **kwargs): """Expected inclusion_unlimited_args_kwargs __doc__""" return { "result": "inclusion_unlimited_args_kwargs - Expected result: %s / %s" % ( ", ".join(str(arg) for arg in [one, two, *args]), ", ".join("%s=%s" % (k, v) for (k, v) in kwargs.items()), ) } inclusion_unlimited_args_kwargs.anything = ( "Expected inclusion_unlimited_args_kwargs __dict__" ) @register.inclusion_tag("inclusion.html", takes_context=True) def inclusion_tag_without_context_parameter(arg): """Expected inclusion_tag_without_context_parameter __doc__""" return {} inclusion_tag_without_context_parameter.anything = ( "Expected inclusion_tag_without_context_parameter __dict__" ) @register.inclusion_tag("inclusion.html", takes_context=True) def inclusion_tag_takes_context_without_params(): """Expected inclusion_tag_takes_context_without_params __doc__""" return {} inclusion_tag_takes_context_without_params.anything = ( "Expected inclusion_tag_takes_context_without_params __dict__" ) @register.inclusion_tag("inclusion_extends1.html") def inclusion_extends1(): return {} @register.inclusion_tag("inclusion_extends2.html") def inclusion_extends2(): return {}
478c2b66eedbd0ab7d255f7d1eae6c27b33a0c69582ce9d57288d0095d70f450
from django.urls import path urlpatterns = [ path("<int:angle_bracket>", lambda x: x), ]
8623cd2ee1b54297be1c74e85dc6f1eb89d56cd3e1439abc1fbcaea90bac70b8
from django.urls import path urlpatterns = [ path("beginning-with/<angle_bracket", lambda x: x), path("ending-with/angle_bracket>", lambda x: x), path("closed_angle>/x/<opened_angle", lambda x: x), path("<mixed>angle_bracket>", lambda x: x), ]
b336a95478fbc08f8134c1be6465f6b69073b4f80386964e8f99e1ebb6633f72
from django.utils.translation import gettext as _ string1 = _("This is a translatable string.") # Obsolete string. # string2 = _("Obsolete string.")
21569dc1fd27f63450d4c3c548bdb08c4f19d63bdaef9eeb49382707b8d410ed
import builtins import collections.abc import datetime import decimal import enum import functools import math import os import pathlib import re import types import uuid from django.conf import SettingsReference from django.db import models from django.db.migrations.operations.base import Operation from django.db.migrations.utils import COMPILED_REGEX_TYPE, RegexObject from django.utils.functional import LazyObject, Promise from django.utils.version import PY311, get_docs_version class BaseSerializer: def __init__(self, value): self.value = value def serialize(self): raise NotImplementedError( "Subclasses of BaseSerializer must implement the serialize() method." ) class BaseSequenceSerializer(BaseSerializer): def _format(self): raise NotImplementedError( "Subclasses of BaseSequenceSerializer must implement the _format() method." ) def serialize(self): imports = set() strings = [] for item in self.value: item_string, item_imports = serializer_factory(item).serialize() imports.update(item_imports) strings.append(item_string) value = self._format() return value % (", ".join(strings)), imports class BaseUnorderedSequenceSerializer(BaseSequenceSerializer): def __init__(self, value): super().__init__(sorted(value, key=repr)) class BaseSimpleSerializer(BaseSerializer): def serialize(self): return repr(self.value), set() class ChoicesSerializer(BaseSerializer): def serialize(self): return serializer_factory(self.value.value).serialize() class DateTimeSerializer(BaseSerializer): """For datetime.*, except datetime.datetime.""" def serialize(self): return repr(self.value), {"import datetime"} class DatetimeDatetimeSerializer(BaseSerializer): """For datetime.datetime.""" def serialize(self): if self.value.tzinfo is not None and self.value.tzinfo != datetime.timezone.utc: self.value = self.value.astimezone(datetime.timezone.utc) imports = ["import datetime"] return repr(self.value), set(imports) class DecimalSerializer(BaseSerializer): def serialize(self): return repr(self.value), {"from decimal import Decimal"} class DeconstructableSerializer(BaseSerializer): @staticmethod def serialize_deconstructed(path, args, kwargs): name, imports = DeconstructableSerializer._serialize_path(path) strings = [] for arg in args: arg_string, arg_imports = serializer_factory(arg).serialize() strings.append(arg_string) imports.update(arg_imports) for kw, arg in sorted(kwargs.items()): arg_string, arg_imports = serializer_factory(arg).serialize() imports.update(arg_imports) strings.append("%s=%s" % (kw, arg_string)) return "%s(%s)" % (name, ", ".join(strings)), imports @staticmethod def _serialize_path(path): module, name = path.rsplit(".", 1) if module == "django.db.models": imports = {"from django.db import models"} name = "models.%s" % name else: imports = {"import %s" % module} name = path return name, imports def serialize(self): return self.serialize_deconstructed(*self.value.deconstruct()) class DictionarySerializer(BaseSerializer): def serialize(self): imports = set() strings = [] for k, v in sorted(self.value.items()): k_string, k_imports = serializer_factory(k).serialize() v_string, v_imports = serializer_factory(v).serialize() imports.update(k_imports) imports.update(v_imports) strings.append((k_string, v_string)) return "{%s}" % (", ".join("%s: %s" % (k, v) for k, v in strings)), imports class EnumSerializer(BaseSerializer): def serialize(self): enum_class = self.value.__class__ module = enum_class.__module__ if issubclass(enum_class, enum.Flag): if PY311: members = list(self.value) else: members, _ = enum._decompose(enum_class, self.value) members = reversed(members) else: members = (self.value,) return ( " | ".join( [ f"{module}.{enum_class.__qualname__}[{item.name!r}]" for item in members ] ), {"import %s" % module}, ) class FloatSerializer(BaseSimpleSerializer): def serialize(self): if math.isnan(self.value) or math.isinf(self.value): return 'float("{}")'.format(self.value), set() return super().serialize() class FrozensetSerializer(BaseUnorderedSequenceSerializer): def _format(self): return "frozenset([%s])" class FunctionTypeSerializer(BaseSerializer): def serialize(self): if getattr(self.value, "__self__", None) and isinstance( self.value.__self__, type ): klass = self.value.__self__ module = klass.__module__ return "%s.%s.%s" % (module, klass.__name__, self.value.__name__), { "import %s" % module } # Further error checking if self.value.__name__ == "<lambda>": raise ValueError("Cannot serialize function: lambda") if self.value.__module__ is None: raise ValueError("Cannot serialize function %r: No module" % self.value) module_name = self.value.__module__ if "<" not in self.value.__qualname__: # Qualname can include <locals> return "%s.%s" % (module_name, self.value.__qualname__), { "import %s" % self.value.__module__ } raise ValueError( "Could not find function %s in %s.\n" % (self.value.__name__, module_name) ) class FunctoolsPartialSerializer(BaseSerializer): def serialize(self): # Serialize functools.partial() arguments func_string, func_imports = serializer_factory(self.value.func).serialize() args_string, args_imports = serializer_factory(self.value.args).serialize() keywords_string, keywords_imports = serializer_factory( self.value.keywords ).serialize() # Add any imports needed by arguments imports = {"import functools", *func_imports, *args_imports, *keywords_imports} return ( "functools.%s(%s, *%s, **%s)" % ( self.value.__class__.__name__, func_string, args_string, keywords_string, ), imports, ) class IterableSerializer(BaseSerializer): def serialize(self): imports = set() strings = [] for item in self.value: item_string, item_imports = serializer_factory(item).serialize() imports.update(item_imports) strings.append(item_string) # When len(strings)==0, the empty iterable should be serialized as # "()", not "(,)" because (,) is invalid Python syntax. value = "(%s)" if len(strings) != 1 else "(%s,)" return value % (", ".join(strings)), imports class ModelFieldSerializer(DeconstructableSerializer): def serialize(self): attr_name, path, args, kwargs = self.value.deconstruct() return self.serialize_deconstructed(path, args, kwargs) class ModelManagerSerializer(DeconstructableSerializer): def serialize(self): as_manager, manager_path, qs_path, args, kwargs = self.value.deconstruct() if as_manager: name, imports = self._serialize_path(qs_path) return "%s.as_manager()" % name, imports else: return self.serialize_deconstructed(manager_path, args, kwargs) class OperationSerializer(BaseSerializer): def serialize(self): from django.db.migrations.writer import OperationWriter string, imports = OperationWriter(self.value, indentation=0).serialize() # Nested operation, trailing comma is handled in upper OperationWriter._write() return string.rstrip(","), imports class PathLikeSerializer(BaseSerializer): def serialize(self): return repr(os.fspath(self.value)), {} class PathSerializer(BaseSerializer): def serialize(self): # Convert concrete paths to pure paths to avoid issues with migrations # generated on one platform being used on a different platform. prefix = "Pure" if isinstance(self.value, pathlib.Path) else "" return "pathlib.%s%r" % (prefix, self.value), {"import pathlib"} class RegexSerializer(BaseSerializer): def serialize(self): regex_pattern, pattern_imports = serializer_factory( self.value.pattern ).serialize() # Turn off default implicit flags (e.g. re.U) because regexes with the # same implicit and explicit flags aren't equal. flags = self.value.flags ^ re.compile("").flags regex_flags, flag_imports = serializer_factory(flags).serialize() imports = {"import re", *pattern_imports, *flag_imports} args = [regex_pattern] if flags: args.append(regex_flags) return "re.compile(%s)" % ", ".join(args), imports class SequenceSerializer(BaseSequenceSerializer): def _format(self): return "[%s]" class SetSerializer(BaseUnorderedSequenceSerializer): def _format(self): # Serialize as a set literal except when value is empty because {} # is an empty dict. return "{%s}" if self.value else "set(%s)" class SettingsReferenceSerializer(BaseSerializer): def serialize(self): return "settings.%s" % self.value.setting_name, { "from django.conf import settings" } class TupleSerializer(BaseSequenceSerializer): def _format(self): # When len(value)==0, the empty tuple should be serialized as "()", # not "(,)" because (,) is invalid Python syntax. return "(%s)" if len(self.value) != 1 else "(%s,)" class TypeSerializer(BaseSerializer): def serialize(self): special_cases = [ (models.Model, "models.Model", ["from django.db import models"]), (types.NoneType, "types.NoneType", ["import types"]), ] for case, string, imports in special_cases: if case is self.value: return string, set(imports) if hasattr(self.value, "__module__"): module = self.value.__module__ if module == builtins.__name__: return self.value.__name__, set() else: return "%s.%s" % (module, self.value.__qualname__), { "import %s" % module } class UUIDSerializer(BaseSerializer): def serialize(self): return "uuid.%s" % repr(self.value), {"import uuid"} class Serializer: _registry = { # Some of these are order-dependent. frozenset: FrozensetSerializer, list: SequenceSerializer, set: SetSerializer, tuple: TupleSerializer, dict: DictionarySerializer, models.Choices: ChoicesSerializer, enum.Enum: EnumSerializer, datetime.datetime: DatetimeDatetimeSerializer, (datetime.date, datetime.timedelta, datetime.time): DateTimeSerializer, SettingsReference: SettingsReferenceSerializer, float: FloatSerializer, (bool, int, types.NoneType, bytes, str, range): BaseSimpleSerializer, decimal.Decimal: DecimalSerializer, (functools.partial, functools.partialmethod): FunctoolsPartialSerializer, ( types.FunctionType, types.BuiltinFunctionType, types.MethodType, ): FunctionTypeSerializer, collections.abc.Iterable: IterableSerializer, (COMPILED_REGEX_TYPE, RegexObject): RegexSerializer, uuid.UUID: UUIDSerializer, pathlib.PurePath: PathSerializer, os.PathLike: PathLikeSerializer, } @classmethod def register(cls, type_, serializer): if not issubclass(serializer, BaseSerializer): raise ValueError( "'%s' must inherit from 'BaseSerializer'." % serializer.__name__ ) cls._registry[type_] = serializer @classmethod def unregister(cls, type_): cls._registry.pop(type_) def serializer_factory(value): if isinstance(value, Promise): value = str(value) elif isinstance(value, LazyObject): # The unwrapped value is returned as the first item of the arguments # tuple. value = value.__reduce__()[1][0] if isinstance(value, models.Field): return ModelFieldSerializer(value) if isinstance(value, models.manager.BaseManager): return ModelManagerSerializer(value) if isinstance(value, Operation): return OperationSerializer(value) if isinstance(value, type): return TypeSerializer(value) # Anything that knows how to deconstruct itself. if hasattr(value, "deconstruct"): return DeconstructableSerializer(value) for type_, serializer_cls in Serializer._registry.items(): if isinstance(value, type_): return serializer_cls(value) raise ValueError( "Cannot serialize: %r\nThere are some values Django cannot serialize into " "migration files.\nFor more, see https://docs.djangoproject.com/en/%s/" "topics/migrations/#migration-serializing" % (value, get_docs_version()) )
39799e56f88e3863264b9d9ed56ac85c3922789a8a052799692751797c5e9a09
import datetime import decimal import enum import functools import math import os import pathlib import re import sys import time import uuid import zoneinfo from types import NoneType from unittest import mock import custom_migration_operations.more_operations import custom_migration_operations.operations from django import get_version from django.conf import SettingsReference, settings from django.core.validators import EmailValidator, RegexValidator from django.db import migrations, models from django.db.migrations.serializer import BaseSerializer from django.db.migrations.writer import MigrationWriter, OperationWriter from django.test import SimpleTestCase from django.utils.deconstruct import deconstructible from django.utils.functional import SimpleLazyObject from django.utils.timezone import get_default_timezone, get_fixed_timezone from django.utils.translation import gettext_lazy as _ from .models import FoodManager, FoodQuerySet class DeconstructibleInstances: def deconstruct(self): return ("DeconstructibleInstances", [], {}) class Money(decimal.Decimal): def deconstruct(self): return ( "%s.%s" % (self.__class__.__module__, self.__class__.__name__), [str(self)], {}, ) class TestModel1: def upload_to(self): return "/somewhere/dynamic/" thing = models.FileField(upload_to=upload_to) class TextEnum(enum.Enum): A = "a-value" B = "value-b" class TextTranslatedEnum(enum.Enum): A = _("a-value") B = _("value-b") class BinaryEnum(enum.Enum): A = b"a-value" B = b"value-b" class IntEnum(enum.IntEnum): A = 1 B = 2 class IntFlagEnum(enum.IntFlag): A = 1 B = 2 class OperationWriterTests(SimpleTestCase): def test_empty_signature(self): operation = custom_migration_operations.operations.TestOperation() buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.TestOperation(\n),", ) def test_args_signature(self): operation = custom_migration_operations.operations.ArgsOperation(1, 2) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsOperation(\n" " arg1=1,\n" " arg2=2,\n" "),", ) def test_kwargs_signature(self): operation = custom_migration_operations.operations.KwargsOperation(kwarg1=1) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.KwargsOperation(\n" " kwarg1=1,\n" "),", ) def test_args_kwargs_signature(self): operation = custom_migration_operations.operations.ArgsKwargsOperation( 1, 2, kwarg2=4 ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsKwargsOperation(\n" " arg1=1,\n" " arg2=2,\n" " kwarg2=4,\n" "),", ) def test_nested_args_signature(self): operation = custom_migration_operations.operations.ArgsOperation( custom_migration_operations.operations.ArgsOperation(1, 2), custom_migration_operations.operations.KwargsOperation(kwarg1=3, kwarg2=4), ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsOperation(\n" " arg1=custom_migration_operations.operations.ArgsOperation(\n" " arg1=1,\n" " arg2=2,\n" " ),\n" " arg2=custom_migration_operations.operations.KwargsOperation(\n" " kwarg1=3,\n" " kwarg2=4,\n" " ),\n" "),", ) def test_multiline_args_signature(self): operation = custom_migration_operations.operations.ArgsOperation( "test\n arg1", "test\narg2" ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsOperation(\n" " arg1='test\\n arg1',\n" " arg2='test\\narg2',\n" "),", ) def test_expand_args_signature(self): operation = custom_migration_operations.operations.ExpandArgsOperation([1, 2]) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ExpandArgsOperation(\n" " arg=[\n" " 1,\n" " 2,\n" " ],\n" "),", ) def test_nested_operation_expand_args_signature(self): operation = custom_migration_operations.operations.ExpandArgsOperation( arg=[ custom_migration_operations.operations.KwargsOperation( kwarg1=1, kwarg2=2, ), ] ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ExpandArgsOperation(\n" " arg=[\n" " custom_migration_operations.operations.KwargsOperation(\n" " kwarg1=1,\n" " kwarg2=2,\n" " ),\n" " ],\n" "),", ) class WriterTests(SimpleTestCase): """ Tests the migration writer (makes migration files from Migration instances) """ class NestedEnum(enum.IntEnum): A = 1 B = 2 class NestedChoices(models.TextChoices): X = "X", "X value" Y = "Y", "Y value" def safe_exec(self, string, value=None): d = {} try: exec(string, globals(), d) except Exception as e: if value: self.fail( "Could not exec %r (from value %r): %s" % (string.strip(), value, e) ) else: self.fail("Could not exec %r: %s" % (string.strip(), e)) return d def serialize_round_trip(self, value): string, imports = MigrationWriter.serialize(value) return self.safe_exec( "%s\ntest_value_result = %s" % ("\n".join(imports), string), value )["test_value_result"] def assertSerializedEqual(self, value): self.assertEqual(self.serialize_round_trip(value), value) def assertSerializedResultEqual(self, value, target): self.assertEqual(MigrationWriter.serialize(value), target) def assertSerializedFieldEqual(self, value): new_value = self.serialize_round_trip(value) self.assertEqual(value.__class__, new_value.__class__) self.assertEqual(value.max_length, new_value.max_length) self.assertEqual(value.null, new_value.null) self.assertEqual(value.unique, new_value.unique) def test_serialize_numbers(self): self.assertSerializedEqual(1) self.assertSerializedEqual(1.2) self.assertTrue(math.isinf(self.serialize_round_trip(float("inf")))) self.assertTrue(math.isinf(self.serialize_round_trip(float("-inf")))) self.assertTrue(math.isnan(self.serialize_round_trip(float("nan")))) self.assertSerializedEqual(decimal.Decimal("1.3")) self.assertSerializedResultEqual( decimal.Decimal("1.3"), ("Decimal('1.3')", {"from decimal import Decimal"}) ) self.assertSerializedEqual(Money("1.3")) self.assertSerializedResultEqual( Money("1.3"), ("migrations.test_writer.Money('1.3')", {"import migrations.test_writer"}), ) def test_serialize_constants(self): self.assertSerializedEqual(None) self.assertSerializedEqual(True) self.assertSerializedEqual(False) def test_serialize_strings(self): self.assertSerializedEqual(b"foobar") string, imports = MigrationWriter.serialize(b"foobar") self.assertEqual(string, "b'foobar'") self.assertSerializedEqual("föobár") string, imports = MigrationWriter.serialize("foobar") self.assertEqual(string, "'foobar'") def test_serialize_multiline_strings(self): self.assertSerializedEqual(b"foo\nbar") string, imports = MigrationWriter.serialize(b"foo\nbar") self.assertEqual(string, "b'foo\\nbar'") self.assertSerializedEqual("föo\nbár") string, imports = MigrationWriter.serialize("foo\nbar") self.assertEqual(string, "'foo\\nbar'") def test_serialize_collections(self): self.assertSerializedEqual({1: 2}) self.assertSerializedEqual(["a", 2, True, None]) self.assertSerializedEqual({2, 3, "eighty"}) self.assertSerializedEqual({"lalalala": ["yeah", "no", "maybe"]}) self.assertSerializedEqual(_("Hello")) def test_serialize_builtin_types(self): self.assertSerializedEqual([list, tuple, dict, set, frozenset]) self.assertSerializedResultEqual( [list, tuple, dict, set, frozenset], ("[list, tuple, dict, set, frozenset]", set()), ) def test_serialize_lazy_objects(self): pattern = re.compile(r"^foo$") lazy_pattern = SimpleLazyObject(lambda: pattern) self.assertEqual(self.serialize_round_trip(lazy_pattern), pattern) def test_serialize_enums(self): self.assertSerializedResultEqual( TextEnum.A, ("migrations.test_writer.TextEnum['A']", {"import migrations.test_writer"}), ) self.assertSerializedResultEqual( TextTranslatedEnum.A, ( "migrations.test_writer.TextTranslatedEnum['A']", {"import migrations.test_writer"}, ), ) self.assertSerializedResultEqual( BinaryEnum.A, ( "migrations.test_writer.BinaryEnum['A']", {"import migrations.test_writer"}, ), ) self.assertSerializedResultEqual( IntEnum.B, ("migrations.test_writer.IntEnum['B']", {"import migrations.test_writer"}), ) self.assertSerializedResultEqual( self.NestedEnum.A, ( "migrations.test_writer.WriterTests.NestedEnum['A']", {"import migrations.test_writer"}, ), ) self.assertSerializedEqual(self.NestedEnum.A) field = models.CharField( default=TextEnum.B, choices=[(m.value, m) for m in TextEnum] ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.CharField(choices=[" "('a-value', migrations.test_writer.TextEnum['A']), " "('value-b', migrations.test_writer.TextEnum['B'])], " "default=migrations.test_writer.TextEnum['B'])", ) field = models.CharField( default=TextTranslatedEnum.A, choices=[(m.value, m) for m in TextTranslatedEnum], ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.CharField(choices=[" "('a-value', migrations.test_writer.TextTranslatedEnum['A']), " "('value-b', migrations.test_writer.TextTranslatedEnum['B'])], " "default=migrations.test_writer.TextTranslatedEnum['A'])", ) field = models.CharField( default=BinaryEnum.B, choices=[(m.value, m) for m in BinaryEnum] ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.CharField(choices=[" "(b'a-value', migrations.test_writer.BinaryEnum['A']), " "(b'value-b', migrations.test_writer.BinaryEnum['B'])], " "default=migrations.test_writer.BinaryEnum['B'])", ) field = models.IntegerField( default=IntEnum.A, choices=[(m.value, m) for m in IntEnum] ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.IntegerField(choices=[" "(1, migrations.test_writer.IntEnum['A']), " "(2, migrations.test_writer.IntEnum['B'])], " "default=migrations.test_writer.IntEnum['A'])", ) def test_serialize_enum_flags(self): self.assertSerializedResultEqual( IntFlagEnum.A, ( "migrations.test_writer.IntFlagEnum['A']", {"import migrations.test_writer"}, ), ) self.assertSerializedResultEqual( IntFlagEnum.B, ( "migrations.test_writer.IntFlagEnum['B']", {"import migrations.test_writer"}, ), ) field = models.IntegerField( default=IntFlagEnum.A, choices=[(m.value, m) for m in IntFlagEnum] ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.IntegerField(choices=[" "(1, migrations.test_writer.IntFlagEnum['A']), " "(2, migrations.test_writer.IntFlagEnum['B'])], " "default=migrations.test_writer.IntFlagEnum['A'])", ) self.assertSerializedResultEqual( IntFlagEnum.A | IntFlagEnum.B, ( "migrations.test_writer.IntFlagEnum['A'] | " "migrations.test_writer.IntFlagEnum['B']", {"import migrations.test_writer"}, ), ) def test_serialize_choices(self): class TextChoices(models.TextChoices): A = "A", "A value" B = "B", "B value" class IntegerChoices(models.IntegerChoices): A = 1, "One" B = 2, "Two" class DateChoices(datetime.date, models.Choices): DATE_1 = 1969, 7, 20, "First date" DATE_2 = 1969, 11, 19, "Second date" self.assertSerializedResultEqual(TextChoices.A, ("'A'", set())) self.assertSerializedResultEqual(IntegerChoices.A, ("1", set())) self.assertSerializedResultEqual( DateChoices.DATE_1, ("datetime.date(1969, 7, 20)", {"import datetime"}), ) field = models.CharField(default=TextChoices.B, choices=TextChoices) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.CharField(choices=[('A', 'A value'), ('B', 'B value')], " "default='B')", ) field = models.IntegerField(default=IntegerChoices.B, choices=IntegerChoices) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.IntegerField(choices=[(1, 'One'), (2, 'Two')], default=2)", ) field = models.DateField(default=DateChoices.DATE_2, choices=DateChoices) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.DateField(choices=[" "(datetime.date(1969, 7, 20), 'First date'), " "(datetime.date(1969, 11, 19), 'Second date')], " "default=datetime.date(1969, 11, 19))", ) def test_serialize_nested_class(self): for nested_cls in [self.NestedEnum, self.NestedChoices]: cls_name = nested_cls.__name__ with self.subTest(cls_name): self.assertSerializedResultEqual( nested_cls, ( "migrations.test_writer.WriterTests.%s" % cls_name, {"import migrations.test_writer"}, ), ) def test_serialize_uuid(self): self.assertSerializedEqual(uuid.uuid1()) self.assertSerializedEqual(uuid.uuid4()) uuid_a = uuid.UUID("5c859437-d061-4847-b3f7-e6b78852f8c8") uuid_b = uuid.UUID("c7853ec1-2ea3-4359-b02d-b54e8f1bcee2") self.assertSerializedResultEqual( uuid_a, ("uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8')", {"import uuid"}), ) self.assertSerializedResultEqual( uuid_b, ("uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2')", {"import uuid"}), ) field = models.UUIDField( choices=((uuid_a, "UUID A"), (uuid_b, "UUID B")), default=uuid_a ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.UUIDField(choices=[" "(uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8'), 'UUID A'), " "(uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2'), 'UUID B')], " "default=uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8'))", ) def test_serialize_pathlib(self): # Pure path objects work in all platforms. self.assertSerializedEqual(pathlib.PurePosixPath()) self.assertSerializedEqual(pathlib.PureWindowsPath()) path = pathlib.PurePosixPath("/path/file.txt") expected = ("pathlib.PurePosixPath('/path/file.txt')", {"import pathlib"}) self.assertSerializedResultEqual(path, expected) path = pathlib.PureWindowsPath("A:\\File.txt") expected = ("pathlib.PureWindowsPath('A:/File.txt')", {"import pathlib"}) self.assertSerializedResultEqual(path, expected) # Concrete path objects work on supported platforms. if sys.platform == "win32": self.assertSerializedEqual(pathlib.WindowsPath.cwd()) path = pathlib.WindowsPath("A:\\File.txt") expected = ("pathlib.PureWindowsPath('A:/File.txt')", {"import pathlib"}) self.assertSerializedResultEqual(path, expected) else: self.assertSerializedEqual(pathlib.PosixPath.cwd()) path = pathlib.PosixPath("/path/file.txt") expected = ("pathlib.PurePosixPath('/path/file.txt')", {"import pathlib"}) self.assertSerializedResultEqual(path, expected) field = models.FilePathField(path=pathlib.PurePosixPath("/home/user")) string, imports = MigrationWriter.serialize(field) self.assertEqual( string, "models.FilePathField(path=pathlib.PurePosixPath('/home/user'))", ) self.assertIn("import pathlib", imports) def test_serialize_path_like(self): with os.scandir(os.path.dirname(__file__)) as entries: path_like = list(entries)[0] expected = (repr(path_like.path), {}) self.assertSerializedResultEqual(path_like, expected) field = models.FilePathField(path=path_like) string = MigrationWriter.serialize(field)[0] self.assertEqual(string, "models.FilePathField(path=%r)" % path_like.path) def test_serialize_functions(self): with self.assertRaisesMessage(ValueError, "Cannot serialize function: lambda"): self.assertSerializedEqual(lambda x: 42) self.assertSerializedEqual(models.SET_NULL) string, imports = MigrationWriter.serialize(models.SET(42)) self.assertEqual(string, "models.SET(42)") self.serialize_round_trip(models.SET(42)) def test_serialize_datetime(self): self.assertSerializedEqual(datetime.datetime.now()) self.assertSerializedEqual(datetime.datetime.now) self.assertSerializedEqual(datetime.datetime.today()) self.assertSerializedEqual(datetime.datetime.today) self.assertSerializedEqual(datetime.date.today()) self.assertSerializedEqual(datetime.date.today) self.assertSerializedEqual(datetime.datetime.now().time()) self.assertSerializedEqual( datetime.datetime(2014, 1, 1, 1, 1, tzinfo=get_default_timezone()) ) self.assertSerializedEqual( datetime.datetime(2013, 12, 31, 22, 1, tzinfo=get_fixed_timezone(180)) ) self.assertSerializedResultEqual( datetime.datetime(2014, 1, 1, 1, 1), ("datetime.datetime(2014, 1, 1, 1, 1)", {"import datetime"}), ) self.assertSerializedResultEqual( datetime.datetime(2012, 1, 1, 1, 1, tzinfo=datetime.timezone.utc), ( "datetime.datetime(2012, 1, 1, 1, 1, tzinfo=datetime.timezone.utc)", {"import datetime"}, ), ) self.assertSerializedResultEqual( datetime.datetime( 2012, 1, 1, 2, 1, tzinfo=zoneinfo.ZoneInfo("Europe/Paris") ), ( "datetime.datetime(2012, 1, 1, 1, 1, tzinfo=datetime.timezone.utc)", {"import datetime"}, ), ) def test_serialize_fields(self): self.assertSerializedFieldEqual(models.CharField(max_length=255)) self.assertSerializedResultEqual( models.CharField(max_length=255), ("models.CharField(max_length=255)", {"from django.db import models"}), ) self.assertSerializedFieldEqual(models.TextField(null=True, blank=True)) self.assertSerializedResultEqual( models.TextField(null=True, blank=True), ( "models.TextField(blank=True, null=True)", {"from django.db import models"}, ), ) def test_serialize_settings(self): self.assertSerializedEqual( SettingsReference(settings.AUTH_USER_MODEL, "AUTH_USER_MODEL") ) self.assertSerializedResultEqual( SettingsReference("someapp.model", "AUTH_USER_MODEL"), ("settings.AUTH_USER_MODEL", {"from django.conf import settings"}), ) def test_serialize_iterators(self): self.assertSerializedResultEqual( ((x, x * x) for x in range(3)), ("((0, 0), (1, 1), (2, 4))", set()) ) def test_serialize_compiled_regex(self): """ Make sure compiled regex can be serialized. """ regex = re.compile(r"^\w+$") self.assertSerializedEqual(regex) def test_serialize_class_based_validators(self): """ Ticket #22943: Test serialization of class-based validators, including compiled regexes. """ validator = RegexValidator(message="hello") string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.RegexValidator(message='hello')" ) self.serialize_round_trip(validator) # Test with a compiled regex. validator = RegexValidator(regex=re.compile(r"^\w+$")) string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.RegexValidator(regex=re.compile('^\\\\w+$'))", ) self.serialize_round_trip(validator) # Test a string regex with flag validator = RegexValidator(r"^[0-9]+$", flags=re.S) string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.RegexValidator('^[0-9]+$', " "flags=re.RegexFlag['DOTALL'])", ) self.serialize_round_trip(validator) # Test message and code validator = RegexValidator("^[-a-zA-Z0-9_]+$", "Invalid", "invalid") string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', " "'invalid')", ) self.serialize_round_trip(validator) # Test with a subclass. validator = EmailValidator(message="hello") string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.EmailValidator(message='hello')" ) self.serialize_round_trip(validator) validator = deconstructible(path="migrations.test_writer.EmailValidator")( EmailValidator )(message="hello") string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "migrations.test_writer.EmailValidator(message='hello')" ) validator = deconstructible(path="custom.EmailValidator")(EmailValidator)( message="hello" ) with self.assertRaisesMessage(ImportError, "No module named 'custom'"): MigrationWriter.serialize(validator) validator = deconstructible(path="django.core.validators.EmailValidator2")( EmailValidator )(message="hello") with self.assertRaisesMessage( ValueError, "Could not find object EmailValidator2 in django.core.validators.", ): MigrationWriter.serialize(validator) def test_serialize_complex_func_index(self): index = models.Index( models.Func("rating", function="ABS"), models.Case( models.When(name="special", then=models.Value("X")), default=models.Value("other"), ), models.ExpressionWrapper( models.F("pages"), output_field=models.IntegerField(), ), models.OrderBy(models.F("name").desc()), name="complex_func_index", ) string, imports = MigrationWriter.serialize(index) self.assertEqual( string, "models.Index(models.Func('rating', function='ABS'), " "models.Case(models.When(name='special', then=models.Value('X')), " "default=models.Value('other')), " "models.ExpressionWrapper(" "models.F('pages'), output_field=models.IntegerField()), " "models.OrderBy(models.OrderBy(models.F('name'), descending=True)), " "name='complex_func_index')", ) self.assertEqual(imports, {"from django.db import models"}) def test_serialize_empty_nonempty_tuple(self): """ Ticket #22679: makemigrations generates invalid code for (an empty tuple) default_permissions = () """ empty_tuple = () one_item_tuple = ("a",) many_items_tuple = ("a", "b", "c") self.assertSerializedEqual(empty_tuple) self.assertSerializedEqual(one_item_tuple) self.assertSerializedEqual(many_items_tuple) def test_serialize_range(self): string, imports = MigrationWriter.serialize(range(1, 5)) self.assertEqual(string, "range(1, 5)") self.assertEqual(imports, set()) def test_serialize_builtins(self): string, imports = MigrationWriter.serialize(range) self.assertEqual(string, "range") self.assertEqual(imports, set()) def test_serialize_unbound_method_reference(self): """An unbound method used within a class body can be serialized.""" self.serialize_round_trip(TestModel1.thing) def test_serialize_local_function_reference(self): """A reference in a local scope can't be serialized.""" class TestModel2: def upload_to(self): return "somewhere dynamic" thing = models.FileField(upload_to=upload_to) with self.assertRaisesMessage( ValueError, "Could not find function upload_to in migrations.test_writer" ): self.serialize_round_trip(TestModel2.thing) def test_serialize_managers(self): self.assertSerializedEqual(models.Manager()) self.assertSerializedResultEqual( FoodQuerySet.as_manager(), ( "migrations.models.FoodQuerySet.as_manager()", {"import migrations.models"}, ), ) self.assertSerializedEqual(FoodManager("a", "b")) self.assertSerializedEqual(FoodManager("x", "y", c=3, d=4)) def test_serialize_frozensets(self): self.assertSerializedEqual(frozenset()) self.assertSerializedEqual(frozenset("let it go")) self.assertSerializedResultEqual( frozenset("cba"), ("frozenset(['a', 'b', 'c'])", set()) ) def test_serialize_set(self): self.assertSerializedEqual(set()) self.assertSerializedResultEqual(set(), ("set()", set())) self.assertSerializedEqual({"a"}) self.assertSerializedResultEqual({"a"}, ("{'a'}", set())) self.assertSerializedEqual({"c", "b", "a"}) self.assertSerializedResultEqual({"c", "b", "a"}, ("{'a', 'b', 'c'}", set())) def test_serialize_timedelta(self): self.assertSerializedEqual(datetime.timedelta()) self.assertSerializedEqual(datetime.timedelta(minutes=42)) def test_serialize_functools_partial(self): value = functools.partial(datetime.timedelta, 1, seconds=2) result = self.serialize_round_trip(value) self.assertEqual(result.func, value.func) self.assertEqual(result.args, value.args) self.assertEqual(result.keywords, value.keywords) def test_serialize_functools_partialmethod(self): value = functools.partialmethod(datetime.timedelta, 1, seconds=2) result = self.serialize_round_trip(value) self.assertIsInstance(result, functools.partialmethod) self.assertEqual(result.func, value.func) self.assertEqual(result.args, value.args) self.assertEqual(result.keywords, value.keywords) def test_serialize_type_none(self): self.assertSerializedEqual(NoneType) def test_serialize_type_model(self): self.assertSerializedEqual(models.Model) self.assertSerializedResultEqual( MigrationWriter.serialize(models.Model), ("('models.Model', {'from django.db import models'})", set()), ) def test_simple_migration(self): """ Tests serializing a simple migration. """ fields = { "charfield": models.DateTimeField(default=datetime.datetime.now), "datetimefield": models.DateTimeField(default=datetime.datetime.now), } options = { "verbose_name": "My model", "verbose_name_plural": "My models", } migration = type( "Migration", (migrations.Migration,), { "operations": [ migrations.CreateModel( "MyModel", tuple(fields.items()), options, (models.Model,) ), migrations.CreateModel( "MyModel2", tuple(fields.items()), bases=(models.Model,) ), migrations.CreateModel( name="MyModel3", fields=tuple(fields.items()), options=options, bases=(models.Model,), ), migrations.DeleteModel("MyModel"), migrations.AddField( "OtherModel", "datetimefield", fields["datetimefield"] ), ], "dependencies": [("testapp", "some_other_one")], }, ) writer = MigrationWriter(migration) output = writer.as_string() # We don't test the output formatting - that's too fragile. # Just make sure it runs for now, and that things look alright. result = self.safe_exec(output) self.assertIn("Migration", result) def test_migration_path(self): test_apps = [ "migrations.migrations_test_apps.normal", "migrations.migrations_test_apps.with_package_model", "migrations.migrations_test_apps.without_init_file", ] base_dir = os.path.dirname(os.path.dirname(__file__)) for app in test_apps: with self.modify_settings(INSTALLED_APPS={"append": app}): migration = migrations.Migration("0001_initial", app.split(".")[-1]) expected_path = os.path.join( base_dir, *(app.split(".") + ["migrations", "0001_initial.py"]) ) writer = MigrationWriter(migration) self.assertEqual(writer.path, expected_path) def test_custom_operation(self): migration = type( "Migration", (migrations.Migration,), { "operations": [ custom_migration_operations.operations.TestOperation(), custom_migration_operations.operations.CreateModel(), migrations.CreateModel("MyModel", (), {}, (models.Model,)), custom_migration_operations.more_operations.TestOperation(), ], "dependencies": [], }, ) writer = MigrationWriter(migration) output = writer.as_string() result = self.safe_exec(output) self.assertIn("custom_migration_operations", result) self.assertNotEqual( result["custom_migration_operations"].operations.TestOperation, result["custom_migration_operations"].more_operations.TestOperation, ) def test_sorted_dependencies(self): migration = type( "Migration", (migrations.Migration,), { "operations": [ migrations.AddField("mymodel", "myfield", models.IntegerField()), ], "dependencies": [ ("testapp10", "0005_fifth"), ("testapp02", "0005_third"), ("testapp02", "0004_sixth"), ("testapp01", "0001_initial"), ], }, ) output = MigrationWriter(migration, include_header=False).as_string() self.assertIn( " dependencies = [\n" " ('testapp01', '0001_initial'),\n" " ('testapp02', '0004_sixth'),\n" " ('testapp02', '0005_third'),\n" " ('testapp10', '0005_fifth'),\n" " ]", output, ) def test_sorted_imports(self): """ #24155 - Tests ordering of imports. """ migration = type( "Migration", (migrations.Migration,), { "operations": [ migrations.AddField( "mymodel", "myfield", models.DateTimeField( default=datetime.datetime( 2012, 1, 1, 1, 1, tzinfo=datetime.timezone.utc ), ), ), migrations.AddField( "mymodel", "myfield2", models.FloatField(default=time.time), ), ] }, ) writer = MigrationWriter(migration) output = writer.as_string() self.assertIn( "import datetime\nimport time\nfrom django.db import migrations, models\n", output, ) def test_migration_file_header_comments(self): """ Test comments at top of file. """ migration = type("Migration", (migrations.Migration,), {"operations": []}) dt = datetime.datetime(2015, 7, 31, 4, 40, 0, 0, tzinfo=datetime.timezone.utc) with mock.patch("django.db.migrations.writer.now", lambda: dt): for include_header in (True, False): with self.subTest(include_header=include_header): writer = MigrationWriter(migration, include_header) output = writer.as_string() self.assertEqual( include_header, output.startswith( "# Generated by Django %s on 2015-07-31 04:40\n\n" % get_version() ), ) if not include_header: # Make sure the output starts with something that's not # a comment or indentation or blank line self.assertRegex( output.splitlines(keepends=True)[0], r"^[^#\s]+" ) def test_models_import_omitted(self): """ django.db.models shouldn't be imported if unused. """ migration = type( "Migration", (migrations.Migration,), { "operations": [ migrations.AlterModelOptions( name="model", options={ "verbose_name": "model", "verbose_name_plural": "models", }, ), ] }, ) writer = MigrationWriter(migration) output = writer.as_string() self.assertIn("from django.db import migrations\n", output) def test_deconstruct_class_arguments(self): # Yes, it doesn't make sense to use a class as a default for a # CharField. It does make sense for custom fields though, for example # an enumfield that takes the enum class as an argument. string = MigrationWriter.serialize( models.CharField(default=DeconstructibleInstances) )[0] self.assertEqual( string, "models.CharField(default=migrations.test_writer.DeconstructibleInstances)", ) def test_register_serializer(self): class ComplexSerializer(BaseSerializer): def serialize(self): return "complex(%r)" % self.value, {} MigrationWriter.register_serializer(complex, ComplexSerializer) self.assertSerializedEqual(complex(1, 2)) MigrationWriter.unregister_serializer(complex) with self.assertRaisesMessage(ValueError, "Cannot serialize: (1+2j)"): self.assertSerializedEqual(complex(1, 2)) def test_register_non_serializer(self): with self.assertRaisesMessage( ValueError, "'TestModel1' must inherit from 'BaseSerializer'." ): MigrationWriter.register_serializer(complex, TestModel1)
930754ed6f0af39c10220b40d285ee401c1394a07ac560a567578ffc5e46b7ed
import os import sys from distutils.sysconfig import get_python_lib from setuptools import find_packages, setup # Warn if we are installing over top of an existing installation. This can # cause issues where files that were deleted from a more recent Django are # still present in site-packages. See #18115. overlay_warning = False if "install" in sys.argv: lib_paths = [get_python_lib()] if lib_paths[0].startswith("/usr/lib/"): # We have to try also with an explicit prefix of /usr/local in order to # catch Debian's custom user site-packages directory. lib_paths.append(get_python_lib(prefix="/usr/local")) for lib_path in lib_paths: existing_path = os.path.abspath(os.path.join(lib_path, "django")) if os.path.exists(existing_path): # We note the need for the warning here, but present it after the # command is run, so it's more likely to be seen. overlay_warning = True break EXCLUDE_FROM_PACKAGES = ['django.conf.project_template', 'django.conf.app_template', 'django.bin'] # Dynamically calculate the version based on django.VERSION. version = __import__('django').get_version() setup( name='Django', version=version, url='https://www.djangoproject.com/', author='Django Software Foundation', author_email='[email protected]', description=('A high-level Python Web framework that encourages ' 'rapid development and clean, pragmatic design.'), license='BSD', packages=find_packages(exclude=EXCLUDE_FROM_PACKAGES), include_package_data=True, scripts=['django/bin/django-admin.py'], entry_points={'console_scripts': [ 'django-admin = django.core.management:execute_from_command_line', ]}, install_requires=['pytz'], extras_require={ "bcrypt": ["bcrypt"], "argon2": ["argon2-cffi >= 16.1.0"], }, zip_safe=False, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Internet :: WWW/HTTP :: WSGI', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: Software Development :: Libraries :: Python Modules', ], ) if overlay_warning: sys.stderr.write(""" ======== WARNING! ======== You have just installed Django over top of an existing installation, without removing it first. Because of this, your install may now include extraneous files from a previous version that have since been removed from Django. This is known to cause a variety of problems. You should manually remove the %(existing_path)s directory and re-install Django. """ % {"existing_path": existing_path})
e42e774b8b1398774c16f6acd4b0da0d281bc481ca83ae5aed21786abd3b066e
#!/usr/bin/env python # # This python file contains utility scripts to manage Django translations. # It has to be run inside the django git root directory. # # The following commands are available: # # * update_catalogs: check for new strings in core and contrib catalogs, and # output how much strings are new/changed. # # * lang_stats: output statistics for each catalog/language combination # # * fetch: fetch translations from transifex.com # # Each command support the --languages and --resources options to limit their # operation to the specified language or resource. For example, to get stats # for Spanish in contrib.admin, run: # # $ python scripts/manage_translations.py lang_stats --language=es --resources=admin import os from argparse import ArgumentParser from subprocess import PIPE, Popen, call import django from django.conf import settings from django.core.management import call_command HAVE_JS = ['admin'] def _get_locale_dirs(resources, include_core=True): """ Return a tuple (contrib name, absolute path) for all locale directories, optionally including the django core catalog. If resources list is not None, filter directories matching resources content. """ contrib_dir = os.path.join(os.getcwd(), 'django', 'contrib') dirs = [] # Collect all locale directories for contrib_name in os.listdir(contrib_dir): path = os.path.join(contrib_dir, contrib_name, 'locale') if os.path.isdir(path): dirs.append((contrib_name, path)) if contrib_name in HAVE_JS: dirs.append(("%s-js" % contrib_name, path)) if include_core: dirs.insert(0, ('core', os.path.join(os.getcwd(), 'django', 'conf', 'locale'))) # Filter by resources, if any if resources is not None: res_names = [d[0] for d in dirs] dirs = [ld for ld in dirs if ld[0] in resources] if len(resources) > len(dirs): print("You have specified some unknown resources. " "Available resource names are: %s" % (', '.join(res_names),)) exit(1) return dirs def _tx_resource_for_name(name): """ Return the Transifex resource name """ if name == 'core': return "django.core" else: return "django.contrib-%s" % name def _check_diff(cat_name, base_path): """ Output the approximate number of changed/added strings in the en catalog. """ po_path = '%(path)s/en/LC_MESSAGES/django%(ext)s.po' % { 'path': base_path, 'ext': 'js' if cat_name.endswith('-js') else ''} p = Popen("git diff -U0 %s | egrep '^[-+]msgid' | wc -l" % po_path, stdout=PIPE, stderr=PIPE, shell=True) output, errors = p.communicate() num_changes = int(output.strip()) print("%d changed/added messages in '%s' catalog." % (num_changes, cat_name)) def update_catalogs(resources=None, languages=None): """ Update the en/LC_MESSAGES/django.po (main and contrib) files with new/updated translatable strings. """ settings.configure() django.setup() if resources is not None: print("`update_catalogs` will always process all resources.") contrib_dirs = _get_locale_dirs(None, include_core=False) os.chdir(os.path.join(os.getcwd(), 'django')) print("Updating en catalogs for Django and contrib apps...") call_command('makemessages', locale=['en']) print("Updating en JS catalogs for Django and contrib apps...") call_command('makemessages', locale=['en'], domain='djangojs') # Output changed stats _check_diff('core', os.path.join(os.getcwd(), 'conf', 'locale')) for name, dir_ in contrib_dirs: _check_diff(name, dir_) def lang_stats(resources=None, languages=None): """ Output language statistics of committed translation files for each Django catalog. If resources is provided, it should be a list of translation resource to limit the output (e.g. ['core', 'gis']). """ locale_dirs = _get_locale_dirs(resources) for name, dir_ in locale_dirs: print("\nShowing translations stats for '%s':" % name) langs = sorted([d for d in os.listdir(dir_) if not d.startswith('_')]) for lang in langs: if languages and lang not in languages: continue # TODO: merge first with the latest en catalog p = Popen("msgfmt -vc -o /dev/null %(path)s/%(lang)s/LC_MESSAGES/django%(ext)s.po" % { 'path': dir_, 'lang': lang, 'ext': 'js' if name.endswith('-js') else ''}, stdout=PIPE, stderr=PIPE, shell=True) output, errors = p.communicate() if p.returncode == 0: # msgfmt output stats on stderr print("%s: %s" % (lang, errors.strip())) else: print("Errors happened when checking %s translation for %s:\n%s" % ( lang, name, errors)) def fetch(resources=None, languages=None): """ Fetch translations from Transifex, wrap long lines, generate mo files. """ locale_dirs = _get_locale_dirs(resources) errors = [] for name, dir_ in locale_dirs: # Transifex pull if languages is None: call('tx pull -r %(res)s -a -f --minimum-perc=5' % {'res': _tx_resource_for_name(name)}, shell=True) target_langs = sorted([d for d in os.listdir(dir_) if not d.startswith('_') and d != 'en']) else: for lang in languages: call('tx pull -r %(res)s -f -l %(lang)s' % { 'res': _tx_resource_for_name(name), 'lang': lang}, shell=True) target_langs = languages # msgcat to wrap lines and msgfmt for compilation of .mo file for lang in target_langs: po_path = '%(path)s/%(lang)s/LC_MESSAGES/django%(ext)s.po' % { 'path': dir_, 'lang': lang, 'ext': 'js' if name.endswith('-js') else ''} if not os.path.exists(po_path): print("No %(lang)s translation for resource %(name)s" % { 'lang': lang, 'name': name}) continue call('msgcat --no-location -o %s %s' % (po_path, po_path), shell=True) res = call('msgfmt -c -o %s.mo %s' % (po_path[:-3], po_path), shell=True) if res != 0: errors.append((name, lang)) if errors: print("\nWARNING: Errors have occurred in following cases:") for resource, lang in errors: print("\tResource %s for language %s" % (resource, lang)) exit(1) if __name__ == "__main__": RUNABLE_SCRIPTS = ('update_catalogs', 'lang_stats', 'fetch') parser = ArgumentParser() parser.add_argument('cmd', nargs=1, choices=RUNABLE_SCRIPTS) parser.add_argument("-r", "--resources", action='append', help="limit operation to the specified resources") parser.add_argument("-l", "--languages", action='append', help="limit operation to the specified languages") options = parser.parse_args() eval(options.cmd[0])(options.resources, options.languages)
af63aa15b9e34c41a37928cca6df6e73e92c47a4a758aa7af2dc408a03e5defe
""" This module collects helper functions and classes that "span" multiple levels of MVC. In other words, these functions/classes introduce controlled coupling for convenience's sake. """ from django.http import ( Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect, ) from django.template import loader from django.urls import NoReverseMatch, reverse from django.utils import six from django.utils.encoding import force_text from django.utils.functional import Promise def render_to_response(template_name, context=None, content_type=None, status=None, using=None): """ Returns a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments. """ content = loader.render_to_string(template_name, context, using=using) return HttpResponse(content, content_type, status) def render(request, template_name, context=None, content_type=None, status=None, using=None): """ Returns a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments. """ content = loader.render_to_string(template_name, context, request, using=using) return HttpResponse(content, content_type, status) def redirect(to, *args, **kwargs): """ Returns an HttpResponseRedirect to the appropriate URL for the arguments passed. The arguments could be: * A model: the model's `get_absolute_url()` function will be called. * A view name, possibly with arguments: `urls.reverse()` will be used to reverse-resolve the name. * A URL, which will be used as-is for the redirect location. By default issues a temporary redirect; pass permanent=True to issue a permanent redirect """ if kwargs.pop('permanent', False): redirect_class = HttpResponsePermanentRedirect else: redirect_class = HttpResponseRedirect return redirect_class(resolve_url(to, *args, **kwargs)) def _get_queryset(klass): """ Return a QuerySet or a Manager. Duck typing in action: any class with a `get()` method (for get_object_or_404) or a `filter()` method (for get_list_or_404) might do the job. """ # If it is a model class or anything else with ._default_manager if hasattr(klass, '_default_manager'): return klass._default_manager.all() return klass def get_object_or_404(klass, *args, **kwargs): """ Uses get() to return an object, or raises a Http404 exception if the object does not exist. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the get() query. Note: Like with get(), an MultipleObjectsReturned will be raised if more than one object is found. """ queryset = _get_queryset(klass) try: return queryset.get(*args, **kwargs) except AttributeError: klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__ raise ValueError( "First argument to get_object_or_404() must be a Model, Manager, " "or QuerySet, not '%s'." % klass__name ) except queryset.model.DoesNotExist: raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) def get_list_or_404(klass, *args, **kwargs): """ Uses filter() to return a list of objects, or raise a Http404 exception if the list is empty. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the filter() query. """ queryset = _get_queryset(klass) try: obj_list = list(queryset.filter(*args, **kwargs)) except AttributeError: klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__ raise ValueError( "First argument to get_list_or_404() must be a Model, Manager, or " "QuerySet, not '%s'." % klass__name ) if not obj_list: raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) return obj_list def resolve_url(to, *args, **kwargs): """ Return a URL appropriate for the arguments passed. The arguments could be: * A model: the model's `get_absolute_url()` function will be called. * A view name, possibly with arguments: `urls.reverse()` will be used to reverse-resolve the name. * A URL, which will be returned as-is. """ # If it's a model, use get_absolute_url() if hasattr(to, 'get_absolute_url'): return to.get_absolute_url() if isinstance(to, Promise): # Expand the lazy instance, as it can cause issues when it is passed # further to some Python functions like urlparse. to = force_text(to) if isinstance(to, six.string_types): # Handle relative URLs if to.startswith(('./', '../')): return to # Next try a reverse URL resolution. try: return reverse(to, args=args, kwargs=kwargs) except NoReverseMatch: # If this is a callable, re-raise. if callable(to): raise # If this doesn't "feel" like a URL, re-raise. if '/' not in to and '.' not in to: raise # Finally, fall back and assume it's a URL return to
312bb60578e3acabf00d21f980c1c5a7eab6bd68b462b62cf0b4a36aa052e012
from __future__ import unicode_literals from django.utils.version import get_version VERSION = (1, 11, 0, 'alpha', 0) __version__ = get_version(VERSION) def setup(set_prefix=True): """ Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. Set the thread-local urlresolvers script prefix if `set_prefix` is True. """ from django.apps import apps from django.conf import settings from django.urls import set_script_prefix from django.utils.encoding import force_text from django.utils.log import configure_logging configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) if set_prefix: set_script_prefix( '/' if settings.FORCE_SCRIPT_NAME is None else force_text(settings.FORCE_SCRIPT_NAME) ) apps.populate(settings.INSTALLED_APPS)
341d3d71735ed39fec25f714ff19ce5fa0525853fe1bf9e11c52b86f27e37e9c
#!/usr/bin/env python import argparse import atexit import copy import os import shutil import subprocess import sys import tempfile import warnings import django from django.apps import apps from django.conf import settings from django.db import connection, connections from django.test import TestCase, TransactionTestCase from django.test.runner import default_test_processes from django.test.selenium import SeleniumTestCaseBase from django.test.utils import get_runner from django.utils import six from django.utils._os import upath from django.utils.deprecation import ( RemovedInDjango20Warning, RemovedInDjango21Warning, ) from django.utils.log import DEFAULT_LOGGING # Make deprecation warnings errors to ensure no usage of deprecated features. warnings.simplefilter("error", RemovedInDjango20Warning) warnings.simplefilter("error", RemovedInDjango21Warning) # Make runtime warning errors to ensure no usage of error prone patterns. warnings.simplefilter("error", RuntimeWarning) # Ignore known warnings in test dependencies. warnings.filterwarnings("ignore", "'U' mode is deprecated", DeprecationWarning, module='docutils.io') RUNTESTS_DIR = os.path.abspath(os.path.dirname(upath(__file__))) TEMPLATE_DIR = os.path.join(RUNTESTS_DIR, 'templates') # Create a specific subdirectory for the duration of the test suite. TMPDIR = tempfile.mkdtemp(prefix='django_') # Set the TMPDIR environment variable in addition to tempfile.tempdir # so that children processes inherit it. tempfile.tempdir = os.environ['TMPDIR'] = TMPDIR # Removing the temporary TMPDIR. Ensure we pass in unicode so that it will # successfully remove temp trees containing non-ASCII filenames on Windows. # (We're assuming the temp dir name itself only contains ASCII characters.) atexit.register(shutil.rmtree, six.text_type(TMPDIR)) SUBDIRS_TO_SKIP = [ 'data', 'import_error_package', 'test_discovery_sample', 'test_discovery_sample2', ] ALWAYS_INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.admin.apps.SimpleAdminConfig', 'django.contrib.staticfiles', ] ALWAYS_MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] # Need to add the associated contrib app to INSTALLED_APPS in some cases to # avoid "RuntimeError: Model class X doesn't declare an explicit app_label # and isn't in an application in INSTALLED_APPS." CONTRIB_TESTS_TO_APPS = { 'flatpages_tests': 'django.contrib.flatpages', 'redirects_tests': 'django.contrib.redirects', } def get_test_modules(): modules = [] discovery_paths = [ (None, RUNTESTS_DIR), # GIS tests are in nested apps ('gis_tests', os.path.join(RUNTESTS_DIR, 'gis_tests')), ] for modpath, dirpath in discovery_paths: for f in os.listdir(dirpath): if ('.' in f or os.path.basename(f) in SUBDIRS_TO_SKIP or os.path.isfile(f) or not os.path.exists(os.path.join(dirpath, f, '__init__.py'))): continue modules.append((modpath, f)) return modules def get_installed(): return [app_config.name for app_config in apps.get_app_configs()] def setup(verbosity, test_labels, parallel): if verbosity >= 1: msg = "Testing against Django installed in '%s'" % os.path.dirname(django.__file__) max_parallel = default_test_processes() if parallel == 0 else parallel if max_parallel > 1: msg += " with up to %d processes" % max_parallel print(msg) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATES': settings.TEMPLATES, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, 'MIDDLEWARE': settings.MIDDLEWARE, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TMPDIR, 'static') settings.TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }] settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 settings.MIDDLEWARE = ALWAYS_MIDDLEWARE settings.MIGRATION_MODULES = { # This lets us skip creating migrations for the test models as many of # them depend on one of the following contrib applications. 'auth': None, 'contenttypes': None, 'sessions': None, } log_config = copy.deepcopy(DEFAULT_LOGGING) # Filter out non-error logging so we don't have to capture it in lots of # tests. log_config['loggers']['django']['level'] = 'ERROR' settings.LOGGING = log_config warnings.filterwarnings( 'ignore', 'The GeoManager class is deprecated.', RemovedInDjango20Warning ) # Load all the ALWAYS_INSTALLED_APPS. django.setup() # Load all the test model apps. test_modules = get_test_modules() # Reduce given test labels to just the app module path test_labels_set = set() for label in test_labels: bits = label.split('.')[:1] test_labels_set.add('.'.join(bits)) installed_app_names = set(get_installed()) for modpath, module_name in test_modules: if modpath: module_label = '.'.join([modpath, module_name]) else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: module_found_in_labels = any( # exact match or ancestor match module_label == label or module_label.startswith(label + '.') for label in test_labels_set) if module_name in CONTRIB_TESTS_TO_APPS and module_found_in_labels: settings.INSTALLED_APPS.append(CONTRIB_TESTS_TO_APPS[module_name]) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) settings.INSTALLED_APPS.append(module_label) # Add contrib.gis to INSTALLED_APPS if needed (rather than requiring # @override_settings(INSTALLED_APPS=...) on all test cases. gis = 'django.contrib.gis' if connection.features.gis_enabled and gis not in settings.INSTALLED_APPS: if verbosity >= 2: print("Importing application %s" % gis) settings.INSTALLED_APPS.append(gis) apps.set_installed_apps(settings.INSTALLED_APPS) return state def teardown(state): # Restore the old settings. for key, value in state.items(): setattr(settings, key, value) def actual_test_processes(parallel): if parallel == 0: # This doesn't work before django.setup() on some databases. if all(conn.features.can_clone_databases for conn in connections.all()): return default_test_processes() else: return 1 else: return parallel class ActionSelenium(argparse.Action): """ Validate the comma-separated list of requested browsers. """ def __call__(self, parser, namespace, values, option_string=None): browsers = values.split(',') for browser in browsers: try: SeleniumTestCaseBase.import_webdriver(browser) except ImportError: raise argparse.ArgumentError(self, "Selenium browser specification '%s' is not valid." % browser) setattr(namespace, self.dest, browsers) def django_tests(verbosity, interactive, failfast, keepdb, reverse, test_labels, debug_sql, parallel, tags, exclude_tags): state = setup(verbosity, test_labels, parallel) extra_tests = [] # Run the test suite, including the extra validation tests. if not hasattr(settings, 'TEST_RUNNER'): settings.TEST_RUNNER = 'django.test.runner.DiscoverRunner' TestRunner = get_runner(settings) test_runner = TestRunner( verbosity=verbosity, interactive=interactive, failfast=failfast, keepdb=keepdb, reverse=reverse, debug_sql=debug_sql, parallel=actual_test_processes(parallel), tags=tags, exclude_tags=exclude_tags, ) failures = test_runner.run_tests( test_labels or get_installed(), extra_tests=extra_tests, ) teardown(state) return failures def get_subprocess_args(options): subprocess_args = [ sys.executable, upath(__file__), '--settings=%s' % options.settings ] if options.failfast: subprocess_args.append('--failfast') if options.verbosity: subprocess_args.append('--verbosity=%s' % options.verbosity) if not options.interactive: subprocess_args.append('--noinput') if options.tags: subprocess_args.append('--tag=%s' % options.tags) if options.exclude_tags: subprocess_args.append('--exclude_tag=%s' % options.exclude_tags) return subprocess_args def bisect_tests(bisection_label, options, test_labels, parallel): state = setup(options.verbosity, test_labels, parallel) test_labels = test_labels or get_installed() print('***** Bisecting test suite: %s' % ' '.join(test_labels)) # Make sure the bisection point isn't in the test list # Also remove tests that need to be run in specific combinations for label in [bisection_label, 'model_inheritance_same_model_name']: try: test_labels.remove(label) except ValueError: pass subprocess_args = get_subprocess_args(options) iteration = 1 while len(test_labels) > 1: midpoint = len(test_labels) // 2 test_labels_a = test_labels[:midpoint] + [bisection_label] test_labels_b = test_labels[midpoint:] + [bisection_label] print('***** Pass %da: Running the first half of the test suite' % iteration) print('***** Test labels: %s' % ' '.join(test_labels_a)) failures_a = subprocess.call(subprocess_args + test_labels_a) print('***** Pass %db: Running the second half of the test suite' % iteration) print('***** Test labels: %s' % ' '.join(test_labels_b)) print('') failures_b = subprocess.call(subprocess_args + test_labels_b) if failures_a and not failures_b: print("***** Problem found in first half. Bisecting again...") iteration += 1 test_labels = test_labels_a[:-1] elif failures_b and not failures_a: print("***** Problem found in second half. Bisecting again...") iteration += 1 test_labels = test_labels_b[:-1] elif failures_a and failures_b: print("***** Multiple sources of failure found") break else: print("***** No source of failure found... try pair execution (--pair)") break if len(test_labels) == 1: print("***** Source of error: %s" % test_labels[0]) teardown(state) def paired_tests(paired_test, options, test_labels, parallel): state = setup(options.verbosity, test_labels, parallel) test_labels = test_labels or get_installed() print('***** Trying paired execution') # Make sure the constant member of the pair isn't in the test list # Also remove tests that need to be run in specific combinations for label in [paired_test, 'model_inheritance_same_model_name']: try: test_labels.remove(label) except ValueError: pass subprocess_args = get_subprocess_args(options) for i, label in enumerate(test_labels): print('***** %d of %d: Check test pairing with %s' % ( i + 1, len(test_labels), label)) failures = subprocess.call(subprocess_args + [label, paired_test]) if failures: print('***** Found problem pair with %s' % label) return print('***** No problem pair found') teardown(state) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run the Django test suite.") parser.add_argument( 'modules', nargs='*', metavar='module', help='Optional path(s) to test modules; e.g. "i18n" or ' '"i18n.tests.TranslationTests.test_lazy_objects".', ) parser.add_argument( '-v', '--verbosity', default=1, type=int, choices=[0, 1, 2, 3], help='Verbosity level; 0=minimal output, 1=normal output, 2=all output', ) parser.add_argument( '--noinput', action='store_false', dest='interactive', default=True, help='Tells Django to NOT prompt the user for input of any kind.', ) parser.add_argument( '--failfast', action='store_true', dest='failfast', default=False, help='Tells Django to stop running the test suite after first failed test.', ) parser.add_argument( '-k', '--keepdb', action='store_true', dest='keepdb', default=False, help='Tells Django to preserve the test database between runs.', ) parser.add_argument( '--settings', help='Python path to settings module, e.g. "myproject.settings". If ' 'this isn\'t provided, either the DJANGO_SETTINGS_MODULE ' 'environment variable or "test_sqlite" will be used.', ) parser.add_argument( '--bisect', help='Bisect the test suite to discover a test that causes a test ' 'failure when combined with the named test.', ) parser.add_argument( '--pair', help='Run the test suite in pairs with the named test to find problem pairs.', ) parser.add_argument( '--reverse', action='store_true', default=False, help='Sort test suites and test cases in opposite order to debug ' 'test side effects not apparent with normal execution lineup.', ) parser.add_argument( '--selenium', dest='selenium', action=ActionSelenium, metavar='BROWSERS', help='A comma-separated list of browsers to run the Selenium tests against.', ) parser.add_argument( '--debug-sql', action='store_true', dest='debug_sql', default=False, help='Turn on the SQL query logger within tests.', ) parser.add_argument( '--parallel', dest='parallel', nargs='?', default=0, type=int, const=default_test_processes(), metavar='N', help='Run tests using up to N parallel processes.', ) parser.add_argument( '--tag', dest='tags', action='append', help='Run only tests with the specified tags. Can be used multiple times.', ) parser.add_argument( '--exclude-tag', dest='exclude_tags', action='append', help='Do not run tests with the specified tag. Can be used multiple times.', ) options = parser.parse_args() # mock is a required dependency try: from django.test import mock # NOQA except ImportError: print( "Please install test dependencies first: \n" "$ pip install -r requirements/py%s.txt" % sys.version_info.major ) sys.exit(1) # Allow including a trailing slash on app_labels for tab completion convenience options.modules = [os.path.normpath(labels) for labels in options.modules] if options.settings: os.environ['DJANGO_SETTINGS_MODULE'] = options.settings else: if "DJANGO_SETTINGS_MODULE" not in os.environ: os.environ['DJANGO_SETTINGS_MODULE'] = 'test_sqlite' options.settings = os.environ['DJANGO_SETTINGS_MODULE'] if options.selenium: if not options.tags: options.tags = ['selenium'] elif 'selenium' not in options.tags: options.tags.append('selenium') SeleniumTestCaseBase.browsers = options.selenium if options.bisect: bisect_tests(options.bisect, options, options.modules, options.parallel) elif options.pair: paired_tests(options.pair, options, options.modules, options.parallel) else: failures = django_tests( options.verbosity, options.interactive, options.failfast, options.keepdb, options.reverse, options.modules, options.debug_sql, options.parallel, options.tags, options.exclude_tags, ) if failures: sys.exit(1)
3274df0670a00bbc95f6d58ae045dcf79f74cd03d3b6fa170aa9214cc17fa01c
# -*- coding: utf-8 -*- # # Django documentation build configuration file, created by # sphinx-quickstart on Thu Mar 27 09:06:53 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't picklable (module imports are okay, they're removed automatically). # # All configuration values have a default; values that are commented out # serve to show the default. from __future__ import unicode_literals import sys from os.path import abspath, dirname, join # Workaround for sphinx-build recursion limit overflow: # pickle.dump(doctree, f, pickle.HIGHEST_PROTOCOL) # RuntimeError: maximum recursion depth exceeded while pickling an object # # Python's default allowed recursion depth is 1000 but this isn't enough for # building docs/ref/settings.txt sometimes. # https://groups.google.com/d/topic/sphinx-dev/MtRf64eGtv4/discussion sys.setrecursionlimit(2000) # Make sure we get the version of this copy of Django sys.path.insert(1, dirname(dirname(abspath(__file__)))) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.append(abspath(join(dirname(__file__), "_ext"))) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = '1.3' # Actually 1.3.4, but micro versions aren't supported here. # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ "djangodocs", "sphinx.ext.intersphinx", "sphinx.ext.viewcode", "ticket_role", "cve_role", ] # Spelling check needs an additional module that is not installed by default. # Add it only if spelling check is requested so docs can be generated without it. if 'spelling' in sys.argv: extensions.append("sphinxcontrib.spelling") # Spelling language. spelling_lang = 'en_US' # Location of word list. spelling_word_list_filename = 'spelling_wordlist' # Add any paths that contain templates here, relative to this directory. # templates_path = [] # The suffix of source filenames. source_suffix = '.txt' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'contents' # General substitutions. project = 'Django' copyright = 'Django Software Foundation and contributors' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.11' # The full version, including alpha/beta/rc tags. try: from django import VERSION, get_version except ImportError: release = version else: def django_release(): pep440ver = get_version() if VERSION[3:5] == ('alpha', 0) and 'dev' not in pep440ver: return pep440ver + '.dev' return pep440ver release = django_release() # The "development version" of Django django_next_version = '1.11' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # Location for .po/.mo translation files used when language is set locale_dirs = ['locale/'] # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = False # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'trac' # Links to Python's docs should reference the most recent version of the 3.x # branch, which is located at this URL. intersphinx_mapping = { 'python': ('https://docs.python.org/3/', None), 'sphinx': ('http://sphinx-doc.org/', None), 'six': ('https://pythonhosted.org/six/', None), 'formtools': ('https://django-formtools.readthedocs.io/en/latest/', None), 'psycopg2': ('http://initd.org/psycopg/docs/', None), } # Python's docs don't change every week. intersphinx_cache_limit = 90 # days # The 'versionadded' and 'versionchanged' directives are overridden. suppress_warnings = ['app.add_directive'] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "djangodocs" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ["_theme"] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. html_use_smartypants = True # HTML translator class for the builder html_translator_class = "djangodocs.DjangoHTMLTranslator" # Content template for the index page. # html_index = '' # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Djangodoc' modindex_common_prefix = ["django."] # Appended to every page rst_epilog = """ .. |django-users| replace:: :ref:`django-users <django-users-mailing-list>` .. |django-core-mentorship| replace:: :ref:`django-core-mentorship <django-core-mentorship-mailing-list>` .. |django-developers| replace:: :ref:`django-developers <django-developers-mailing-list>` .. |django-announce| replace:: :ref:`django-announce <django-announce-mailing-list>` .. |django-updates| replace:: :ref:`django-updates <django-updates-mailing-list>` """ # -- Options for LaTeX output -------------------------------------------------- latex_elements = { 'preamble': ( '\\DeclareUnicodeCharacter{2264}{\\ensuremath{\\le}}' '\\DeclareUnicodeCharacter{2265}{\\ensuremath{\\ge}}' '\\DeclareUnicodeCharacter{2665}{[unicode-heart]}' '\\DeclareUnicodeCharacter{2713}{[unicode-checkmark]}' ), } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). # latex_documents = [] latex_documents = [ ('contents', 'django.tex', 'Django Documentation', 'Django Software Foundation', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # 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 ), ] # -- Options for Texinfo output ------------------------------------------------ # List of tuples (startdocname, targetname, title, author, dir_entry, # description, category, toctree_only) texinfo_documents = [( master_doc, "django", "", "", "Django", "Documentation of the Django framework", "Web development", False )] # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = 'Django Software Foundation' epub_publisher = 'Django Software Foundation' epub_copyright = copyright # The basename for the epub file. It defaults to the project name. # epub_basename = 'Django' # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. epub_theme = 'djangodocs-epub' # The language of the text. It defaults to the language option # or en if the language is not set. # epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. # epub_scheme = '' # The unique identifier of the text. This can be an ISBN number # or the project homepage. # epub_identifier = '' # A unique identification for the text. # epub_uid = '' # A tuple containing the cover image and cover page html template filenames. epub_cover = ('', 'epub-cover.html') # A sequence of (type, uri, title) tuples for the guide element of content.opf. # epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. # epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. # epub_post_files = [] # A list of files that should not be packed into the epub file. # epub_exclude_files = [] # The depth of the table of contents in toc.ncx. # epub_tocdepth = 3 # Allow duplicate toc entries. # epub_tocdup = True # Choose between 'default' and 'includehidden'. # epub_tocscope = 'default' # Fix unsupported image types using the PIL. # epub_fix_images = False # Scale large images. # epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. # epub_show_urls = 'inline' # If false, no index is generated. # epub_use_index = True # -- custom extension options -------------------------------------------------- cve_url = 'https://web.nvd.nist.gov/view/vuln/detail?vulnId=%s' ticket_url = 'https://code.djangoproject.com/ticket/%s'
699b35aad8ce9e1cbc2d6ae273121dd40420a5251e7be58217e1330a3ea8eaab
"""Multi-consumer multi-producer dispatching mechanism Originally based on pydispatch (BSD) http://pypi.python.org/pypi/PyDispatcher/2.0.1 See license.txt for original license. Heavily modified for Django's purposes. """ from django.dispatch.dispatcher import Signal, receiver # NOQA
803207159c31e027e26050566afebd94c0b190d9764f54851889c555492c5997
import sys import threading import warnings import weakref from django.utils import six from django.utils.deprecation import RemovedInDjango20Warning from django.utils.inspect import func_accepts_kwargs from django.utils.six.moves import range if six.PY2: from .weakref_backports import WeakMethod else: from weakref import WeakMethod def _make_id(target): if hasattr(target, '__func__'): return (id(target.__self__), id(target.__func__)) return id(target) NONE_ID = _make_id(None) # A marker for caching NO_RECEIVERS = object() class Signal(object): """ Base class for all signals Internal attributes: receivers { receiverkey (id) : weakref(receiver) } """ def __init__(self, providing_args=None, use_caching=False): """ Create a new signal. providing_args A list of the arguments this signal can pass along in a send() call. """ self.receivers = [] if providing_args is None: providing_args = [] self.providing_args = set(providing_args) self.lock = threading.Lock() self.use_caching = use_caching # For convenience we create empty caches even if they are not used. # A note about caching: if use_caching is defined, then for each # distinct sender we cache the receivers that sender has in # 'sender_receivers_cache'. The cache is cleaned when .connect() or # .disconnect() is called and populated on send(). self.sender_receivers_cache = weakref.WeakKeyDictionary() if use_caching else {} self._dead_receivers = False def connect(self, receiver, sender=None, weak=True, dispatch_uid=None): """ Connect receiver to sender for signal. Arguments: receiver A function or an instance method which is to receive signals. Receivers must be hashable objects. If weak is True, then receiver must be weak referenceable. Receivers must be able to accept keyword arguments. If a receiver is connected with a dispatch_uid argument, it will not be added if another receiver was already connected with that dispatch_uid. sender The sender to which the receiver should respond. Must either be a Python object, or None to receive events from any sender. weak Whether to use weak references to the receiver. By default, the module will attempt to use weak references to the receiver objects. If this parameter is false, then strong references will be used. dispatch_uid An identifier used to uniquely identify a particular instance of a receiver. This will usually be a string, though it may be anything hashable. """ from django.conf import settings # If DEBUG is on, check that we got a good receiver if settings.configured and settings.DEBUG: assert callable(receiver), "Signal receivers must be callable." # Check for **kwargs if not func_accepts_kwargs(receiver): raise ValueError("Signal receivers must accept keyword arguments (**kwargs).") if dispatch_uid: lookup_key = (dispatch_uid, _make_id(sender)) else: lookup_key = (_make_id(receiver), _make_id(sender)) if weak: ref = weakref.ref receiver_object = receiver # Check for bound methods if hasattr(receiver, '__self__') and hasattr(receiver, '__func__'): ref = WeakMethod receiver_object = receiver.__self__ if six.PY3: receiver = ref(receiver) weakref.finalize(receiver_object, self._remove_receiver) else: receiver = ref(receiver, self._remove_receiver) with self.lock: self._clear_dead_receivers() for r_key, _ in self.receivers: if r_key == lookup_key: break else: self.receivers.append((lookup_key, receiver)) self.sender_receivers_cache.clear() def disconnect(self, receiver=None, sender=None, weak=None, dispatch_uid=None): """ Disconnect receiver from sender for signal. If weak references are used, disconnect need not be called. The receiver will be remove from dispatch automatically. Arguments: receiver The registered receiver to disconnect. May be none if dispatch_uid is specified. sender The registered sender to disconnect dispatch_uid the unique identifier of the receiver to disconnect """ if weak is not None: warnings.warn("Passing `weak` to disconnect has no effect.", RemovedInDjango20Warning, stacklevel=2) if dispatch_uid: lookup_key = (dispatch_uid, _make_id(sender)) else: lookup_key = (_make_id(receiver), _make_id(sender)) disconnected = False with self.lock: self._clear_dead_receivers() for index in range(len(self.receivers)): (r_key, _) = self.receivers[index] if r_key == lookup_key: disconnected = True del self.receivers[index] break self.sender_receivers_cache.clear() return disconnected def has_listeners(self, sender=None): return bool(self._live_receivers(sender)) def send(self, sender, **named): """ Send signal from sender to all connected receivers. If any receiver raises an error, the error propagates back through send, terminating the dispatch loop. So it's possible that all receivers won't be called if an error is raised. Arguments: sender The sender of the signal. Either a specific object or None. named Named arguments which will be passed to receivers. Returns a list of tuple pairs [(receiver, response), ... ]. """ responses = [] if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS: return responses for receiver in self._live_receivers(sender): response = receiver(signal=self, sender=sender, **named) responses.append((receiver, response)) return responses def send_robust(self, sender, **named): """ Send signal from sender to all connected receivers catching errors. Arguments: sender The sender of the signal. Can be any python object (normally one registered with a connect if you actually want something to occur). named Named arguments which will be passed to receivers. These arguments must be a subset of the argument names defined in providing_args. Return a list of tuple pairs [(receiver, response), ... ]. May raise DispatcherKeyError. If any receiver raises an error (specifically any subclass of Exception), the error instance is returned as the result for that receiver. The traceback is always attached to the error at ``__traceback__``. """ responses = [] if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS: return responses # Call each receiver with whatever arguments it can accept. # Return a list of tuple pairs [(receiver, response), ... ]. for receiver in self._live_receivers(sender): try: response = receiver(signal=self, sender=sender, **named) except Exception as err: if not hasattr(err, '__traceback__'): err.__traceback__ = sys.exc_info()[2] responses.append((receiver, err)) else: responses.append((receiver, response)) return responses def _clear_dead_receivers(self): # Note: caller is assumed to hold self.lock. if self._dead_receivers: self._dead_receivers = False new_receivers = [] for r in self.receivers: if isinstance(r[1], weakref.ReferenceType) and r[1]() is None: continue new_receivers.append(r) self.receivers = new_receivers def _live_receivers(self, sender): """ Filter sequence of receivers to get resolved, live receivers. This checks for weak references and resolves them, then returning only live receivers. """ receivers = None if self.use_caching and not self._dead_receivers: receivers = self.sender_receivers_cache.get(sender) # We could end up here with NO_RECEIVERS even if we do check this case in # .send() prior to calling _live_receivers() due to concurrent .send() call. if receivers is NO_RECEIVERS: return [] if receivers is None: with self.lock: self._clear_dead_receivers() senderkey = _make_id(sender) receivers = [] for (receiverkey, r_senderkey), receiver in self.receivers: if r_senderkey == NONE_ID or r_senderkey == senderkey: receivers.append(receiver) if self.use_caching: if not receivers: self.sender_receivers_cache[sender] = NO_RECEIVERS else: # Note, we must cache the weakref versions. self.sender_receivers_cache[sender] = receivers non_weak_receivers = [] for receiver in receivers: if isinstance(receiver, weakref.ReferenceType): # Dereference the weak reference. receiver = receiver() if receiver is not None: non_weak_receivers.append(receiver) else: non_weak_receivers.append(receiver) return non_weak_receivers def _remove_receiver(self, receiver=None): # Mark that the self.receivers list has dead weakrefs. If so, we will # clean those up in connect, disconnect and _live_receivers while # holding self.lock. Note that doing the cleanup here isn't a good # idea, _remove_receiver() will be called as side effect of garbage # collection, and so the call can happen while we are already holding # self.lock. self._dead_receivers = True def receiver(signal, **kwargs): """ A decorator for connecting receivers to signals. Used by passing in the signal (or list of signals) and keyword arguments to connect:: @receiver(post_save, sender=MyModel) def signal_receiver(sender, **kwargs): ... @receiver([post_save, post_delete], sender=MyModel) def signals_receiver(sender, **kwargs): ... """ def _decorator(func): if isinstance(signal, (list, tuple)): for s in signal: s.connect(func, **kwargs) else: signal.connect(func, **kwargs) return func return _decorator
7082df80374f819f01cc2ab310e5e0bc643bc72d49a5f65725baba92e03d7c1f
""" weakref_backports is a partial backport of the weakref module for python versions below 3.4. Copyright (C) 2013 Python Software Foundation, see LICENSE.python for details. The following changes were made to the original sources during backporting: * Added `self` to `super` calls. * Removed `from None` when raising exceptions. """ from weakref import ref class WeakMethod(ref): """ A custom `weakref.ref` subclass which simulates a weak reference to a bound method, working around the lifetime problem of bound methods. """ __slots__ = "_func_ref", "_meth_type", "_alive", "__weakref__" def __new__(cls, meth, callback=None): try: obj = meth.__self__ func = meth.__func__ except AttributeError: raise TypeError("argument should be a bound method, not {}" .format(type(meth))) def _cb(arg): # The self-weakref trick is needed to avoid creating a reference # cycle. self = self_wr() if self._alive: self._alive = False if callback is not None: callback(self) self = ref.__new__(cls, obj, _cb) self._func_ref = ref(func, _cb) self._meth_type = type(meth) self._alive = True self_wr = ref(self) return self def __call__(self): obj = super(WeakMethod, self).__call__() func = self._func_ref() if obj is None or func is None: return None return self._meth_type(func, obj) def __eq__(self, other): if isinstance(other, WeakMethod): if not self._alive or not other._alive: return self is other return ref.__eq__(self, other) and self._func_ref == other._func_ref return False def __ne__(self, other): if isinstance(other, WeakMethod): if not self._alive or not other._alive: return self is not other return ref.__ne__(self, other) or self._func_ref != other._func_ref return True __hash__ = ref.__hash__
62f834853c0be789ea73a3b13c2e18877e80f337e627eeb32cf0b2a1acec30eb
from __future__ import unicode_literals import sys import unittest from contextlib import contextmanager from django.test import LiveServerTestCase, tag from django.utils.module_loading import import_string from django.utils.six import with_metaclass from django.utils.text import capfirst class SeleniumTestCaseBase(type(LiveServerTestCase)): # List of browsers to dynamically create test classes for. browsers = [] # Sentinel value to differentiate browser-specific instances. browser = None def __new__(cls, name, bases, attrs): """ Dynamically create new classes and add them to the test module when multiple browsers specs are provided (e.g. --selenium=firefox,chrome). """ test_class = super(SeleniumTestCaseBase, cls).__new__(cls, name, bases, attrs) # If the test class is either browser-specific or a test base, return it. if test_class.browser or not any(name.startswith('test') and callable(value) for name, value in attrs.items()): return test_class elif test_class.browsers: # Reuse the created test class to make it browser-specific. # We can't rename it to include the browser name or create a # subclass like we do with the remaining browsers as it would # either duplicate tests or prevent pickling of its instances. first_browser = test_class.browsers[0] test_class.browser = first_browser # Create subclasses for each of the remaining browsers and expose # them through the test's module namespace. module = sys.modules[test_class.__module__] for browser in test_class.browsers[1:]: browser_test_class = cls.__new__( cls, str("%s%s" % (capfirst(browser), name)), (test_class,), {'browser': browser, '__module__': test_class.__module__} ) setattr(module, browser_test_class.__name__, browser_test_class) return test_class # If no browsers were specified, skip this class (it'll still be discovered). return unittest.skip('No browsers specified.')(test_class) @classmethod def import_webdriver(cls, browser): return import_string("selenium.webdriver.%s.webdriver.WebDriver" % browser) def create_webdriver(self): return self.import_webdriver(self.browser)() @tag('selenium') class SeleniumTestCase(with_metaclass(SeleniumTestCaseBase, LiveServerTestCase)): implicit_wait = 10 @classmethod def setUpClass(cls): cls.selenium = cls.create_webdriver() cls.selenium.implicitly_wait(cls.implicit_wait) super(SeleniumTestCase, cls).setUpClass() @classmethod def _tearDownClassInternal(cls): # quit() the WebDriver before attempting to terminate and join the # single-threaded LiveServerThread to avoid a dead lock if the browser # kept a connection alive. if hasattr(cls, 'selenium'): cls.selenium.quit() super(SeleniumTestCase, cls)._tearDownClassInternal() @contextmanager def disable_implicit_wait(self): """Context manager that disables the default implicit wait.""" self.selenium.implicitly_wait(0) try: yield finally: self.selenium.implicitly_wait(self.implicit_wait)
7b7cd69372fdd64f69c8b472cca96dfc10c085cf3e957b5bef1a18cfefa29c87
""" Django Unit Test and Doctest framework. """ from django.test.client import Client, RequestFactory from django.test.testcases import ( LiveServerTestCase, SimpleTestCase, TestCase, TransactionTestCase, skipIfDBFeature, skipUnlessAnyDBFeature, skipUnlessDBFeature, ) from django.test.utils import ( ignore_warnings, modify_settings, override_settings, override_system_checks, tag, ) __all__ = [ 'Client', 'RequestFactory', 'TestCase', 'TransactionTestCase', 'SimpleTestCase', 'LiveServerTestCase', 'skipIfDBFeature', 'skipUnlessAnyDBFeature', 'skipUnlessDBFeature', 'ignore_warnings', 'modify_settings', 'override_settings', 'override_system_checks', 'tag', ] # To simplify Django's test suite; not meant as a public API try: from unittest import mock # NOQA except ImportError: try: import mock # NOQA except ImportError: pass
8a2b691ed4237cfb16af8fb6443da294fcc108f4415bcf61460ccad2179dda7e
import ctypes import itertools import logging import multiprocessing import os import pickle import textwrap import unittest import warnings from importlib import import_module from django.db import connections from django.test import SimpleTestCase, TestCase from django.test.utils import ( setup_databases as _setup_databases, setup_test_environment, teardown_databases as _teardown_databases, teardown_test_environment, ) from django.utils.datastructures import OrderedSet from django.utils.deprecation import RemovedInDjango21Warning from django.utils.six import StringIO try: import tblib.pickling_support except ImportError: tblib = None class DebugSQLTextTestResult(unittest.TextTestResult): def __init__(self, stream, descriptions, verbosity): self.logger = logging.getLogger('django.db.backends') self.logger.setLevel(logging.DEBUG) super(DebugSQLTextTestResult, self).__init__(stream, descriptions, verbosity) def startTest(self, test): self.debug_sql_stream = StringIO() self.handler = logging.StreamHandler(self.debug_sql_stream) self.logger.addHandler(self.handler) super(DebugSQLTextTestResult, self).startTest(test) def stopTest(self, test): super(DebugSQLTextTestResult, self).stopTest(test) self.logger.removeHandler(self.handler) if self.showAll: self.debug_sql_stream.seek(0) self.stream.write(self.debug_sql_stream.read()) self.stream.writeln(self.separator2) def addError(self, test, err): super(DebugSQLTextTestResult, self).addError(test, err) self.debug_sql_stream.seek(0) self.errors[-1] = self.errors[-1] + (self.debug_sql_stream.read(),) def addFailure(self, test, err): super(DebugSQLTextTestResult, self).addFailure(test, err) self.debug_sql_stream.seek(0) self.failures[-1] = self.failures[-1] + (self.debug_sql_stream.read(),) def printErrorList(self, flavour, errors): for test, err, sql_debug in errors: self.stream.writeln(self.separator1) self.stream.writeln("%s: %s" % (flavour, self.getDescription(test))) self.stream.writeln(self.separator2) self.stream.writeln("%s" % err) self.stream.writeln(self.separator2) self.stream.writeln("%s" % sql_debug) class RemoteTestResult(object): """ Record information about which tests have succeeded and which have failed. The sole purpose of this class is to record events in the child processes so they can be replayed in the master process. As a consequence it doesn't inherit unittest.TestResult and doesn't attempt to implement all its API. The implementation matches the unpythonic coding style of unittest2. """ def __init__(self): if tblib is not None: tblib.pickling_support.install() self.events = [] self.failfast = False self.shouldStop = False self.testsRun = 0 @property def test_index(self): return self.testsRun - 1 def _confirm_picklable(self, obj): """ Confirm that obj can be pickled and unpickled as multiprocessing will need to pickle the exception in the child process and unpickle it in the parent process. Let the exception rise, if not. """ pickle.loads(pickle.dumps(obj)) def _print_unpicklable_subtest(self, test, subtest, pickle_exc): print(""" Subtest failed: test: {} subtest: {} Unfortunately, the subtest that failed cannot be pickled, so the parallel test runner cannot handle it cleanly. Here is the pickling error: > {} You should re-run this test with --parallel=1 to reproduce the failure with a cleaner failure message. """.format(test, subtest, pickle_exc)) def check_picklable(self, test, err): # Ensure that sys.exc_info() tuples are picklable. This displays a # clear multiprocessing.pool.RemoteTraceback generated in the child # process instead of a multiprocessing.pool.MaybeEncodingError, making # the root cause easier to figure out for users who aren't familiar # with the multiprocessing module. Since we're in a forked process, # our best chance to communicate with them is to print to stdout. try: self._confirm_picklable(err) except Exception as exc: original_exc_txt = repr(err[1]) original_exc_txt = textwrap.fill(original_exc_txt, 75, initial_indent=' ', subsequent_indent=' ') pickle_exc_txt = repr(exc) pickle_exc_txt = textwrap.fill(pickle_exc_txt, 75, initial_indent=' ', subsequent_indent=' ') if tblib is None: print(""" {} failed: {} Unfortunately, tracebacks cannot be pickled, making it impossible for the parallel test runner to handle this exception cleanly. In order to see the traceback, you should install tblib: pip install tblib """.format(test, original_exc_txt)) else: print(""" {} failed: {} Unfortunately, the exception it raised cannot be pickled, making it impossible for the parallel test runner to handle it cleanly. Here's the error encountered while trying to pickle the exception: {} You should re-run this test with the --parallel=1 option to reproduce the failure and get a correct traceback. """.format(test, original_exc_txt, pickle_exc_txt)) raise def check_subtest_picklable(self, test, subtest): try: self._confirm_picklable(subtest) except Exception as exc: self._print_unpicklable_subtest(test, subtest, exc) raise def stop_if_failfast(self): if self.failfast: self.stop() def stop(self): self.shouldStop = True def startTestRun(self): self.events.append(('startTestRun',)) def stopTestRun(self): self.events.append(('stopTestRun',)) def startTest(self, test): self.testsRun += 1 self.events.append(('startTest', self.test_index)) def stopTest(self, test): self.events.append(('stopTest', self.test_index)) def addError(self, test, err): self.check_picklable(test, err) self.events.append(('addError', self.test_index, err)) self.stop_if_failfast() def addFailure(self, test, err): self.check_picklable(test, err) self.events.append(('addFailure', self.test_index, err)) self.stop_if_failfast() def addSubTest(self, test, subtest, err): # Follow Python 3.5's implementation of unittest.TestResult.addSubTest() # by not doing anything when a subtest is successful. if err is not None: # Call check_picklable() before check_subtest_picklable() since # check_picklable() performs the tblib check. self.check_picklable(test, err) self.check_subtest_picklable(test, subtest) self.events.append(('addSubTest', self.test_index, subtest, err)) self.stop_if_failfast() def addSuccess(self, test): self.events.append(('addSuccess', self.test_index)) def addSkip(self, test, reason): self.events.append(('addSkip', self.test_index, reason)) def addExpectedFailure(self, test, err): # If tblib isn't installed, pickling the traceback will always fail. # However we don't want tblib to be required for running the tests # when they pass or fail as expected. Drop the traceback when an # expected failure occurs. if tblib is None: err = err[0], err[1], None self.check_picklable(test, err) self.events.append(('addExpectedFailure', self.test_index, err)) def addUnexpectedSuccess(self, test): self.events.append(('addUnexpectedSuccess', self.test_index)) self.stop_if_failfast() class RemoteTestRunner(object): """ Run tests and record everything but don't display anything. The implementation matches the unpythonic coding style of unittest2. """ resultclass = RemoteTestResult def __init__(self, failfast=False, resultclass=None): self.failfast = failfast if resultclass is not None: self.resultclass = resultclass def run(self, test): result = self.resultclass() unittest.registerResult(result) result.failfast = self.failfast test(result) return result def default_test_processes(): """ Default number of test processes when using the --parallel option. """ # The current implementation of the parallel test runner requires # multiprocessing to start subprocesses with fork(). # On Python 3.4+: if multiprocessing.get_start_method() != 'fork': if not hasattr(os, 'fork'): return 1 try: return int(os.environ['DJANGO_TEST_PROCESSES']) except KeyError: return multiprocessing.cpu_count() _worker_id = 0 def _init_worker(counter): """ Switch to databases dedicated to this worker. This helper lives at module-level because of the multiprocessing module's requirements. """ global _worker_id with counter.get_lock(): counter.value += 1 _worker_id = counter.value for alias in connections: connection = connections[alias] settings_dict = connection.creation.get_test_db_clone_settings(_worker_id) # connection.settings_dict must be updated in place for changes to be # reflected in django.db.connections. If the following line assigned # connection.settings_dict = settings_dict, new threads would connect # to the default database instead of the appropriate clone. connection.settings_dict.update(settings_dict) connection.close() def _run_subsuite(args): """ Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult. This helper lives at module-level and its arguments are wrapped in a tuple because of the multiprocessing module's requirements. """ runner_class, subsuite_index, subsuite, failfast = args runner = runner_class(failfast=failfast) result = runner.run(subsuite) return subsuite_index, result.events class ParallelTestSuite(unittest.TestSuite): """ Run a series of tests in parallel in several processes. While the unittest module's documentation implies that orchestrating the execution of tests is the responsibility of the test runner, in practice, it appears that TestRunner classes are more concerned with formatting and displaying test results. Since there are fewer use cases for customizing TestSuite than TestRunner, implementing parallelization at the level of the TestSuite improves interoperability with existing custom test runners. A single instance of a test runner can still collect results from all tests without being aware that they have been run in parallel. """ # In case someone wants to modify these in a subclass. init_worker = _init_worker run_subsuite = _run_subsuite runner_class = RemoteTestRunner def __init__(self, suite, processes, failfast=False): self.subsuites = partition_suite_by_case(suite) self.processes = processes self.failfast = failfast super(ParallelTestSuite, self).__init__() def run(self, result): """ Distribute test cases across workers. Return an identifier of each test case with its result in order to use imap_unordered to show results as soon as they're available. To minimize pickling errors when getting results from workers: - pass back numeric indexes in self.subsuites instead of tests - make tracebacks picklable with tblib, if available Even with tblib, errors may still occur for dynamically created exception classes such Model.DoesNotExist which cannot be unpickled. """ counter = multiprocessing.Value(ctypes.c_int, 0) pool = multiprocessing.Pool( processes=self.processes, initializer=self.init_worker.__func__, initargs=[counter]) args = [ (self.runner_class, index, subsuite, self.failfast) for index, subsuite in enumerate(self.subsuites) ] test_results = pool.imap_unordered(self.run_subsuite.__func__, args) while True: if result.shouldStop: pool.terminate() break try: subsuite_index, events = test_results.next(timeout=0.1) except multiprocessing.TimeoutError: continue except StopIteration: pool.close() break tests = list(self.subsuites[subsuite_index]) for event in events: event_name = event[0] handler = getattr(result, event_name, None) if handler is None: continue test = tests[event[1]] args = event[2:] handler(test, *args) pool.join() return result class DiscoverRunner(object): """ A Django test runner that uses unittest2 test discovery. """ test_suite = unittest.TestSuite parallel_test_suite = ParallelTestSuite test_runner = unittest.TextTestRunner test_loader = unittest.defaultTestLoader reorder_by = (TestCase, SimpleTestCase) def __init__(self, pattern=None, top_level=None, verbosity=1, interactive=True, failfast=False, keepdb=False, reverse=False, debug_mode=False, debug_sql=False, parallel=0, tags=None, exclude_tags=None, **kwargs): self.pattern = pattern self.top_level = top_level self.verbosity = verbosity self.interactive = interactive self.failfast = failfast self.keepdb = keepdb self.reverse = reverse self.debug_mode = debug_mode self.debug_sql = debug_sql self.parallel = parallel self.tags = set(tags or []) self.exclude_tags = set(exclude_tags or []) @classmethod def add_arguments(cls, parser): parser.add_argument( '-t', '--top-level-directory', action='store', dest='top_level', default=None, help='Top level of project for unittest discovery.', ) parser.add_argument( '-p', '--pattern', action='store', dest='pattern', default="test*.py", help='The test matching pattern. Defaults to test*.py.', ) parser.add_argument( '-k', '--keepdb', action='store_true', dest='keepdb', default=False, help='Preserves the test DB between runs.' ) parser.add_argument( '-r', '--reverse', action='store_true', dest='reverse', default=False, help='Reverses test cases order.', ) parser.add_argument( '--debug-mode', action='store_true', dest='debug_mode', default=False, help='Sets settings.DEBUG to True.', ) parser.add_argument( '-d', '--debug-sql', action='store_true', dest='debug_sql', default=False, help='Prints logged SQL queries on failure.', ) parser.add_argument( '--parallel', dest='parallel', nargs='?', default=1, type=int, const=default_test_processes(), metavar='N', help='Run tests using up to N parallel processes.', ) parser.add_argument( '--tag', action='append', dest='tags', help='Run only tests with the specified tag. Can be used multiple times.', ) parser.add_argument( '--exclude-tag', action='append', dest='exclude_tags', help='Do not run tests with the specified tag. Can be used multiple times.', ) def setup_test_environment(self, **kwargs): setup_test_environment(debug=self.debug_mode) unittest.installHandler() def build_suite(self, test_labels=None, extra_tests=None, **kwargs): suite = self.test_suite() test_labels = test_labels or ['.'] extra_tests = extra_tests or [] discover_kwargs = {} if self.pattern is not None: discover_kwargs['pattern'] = self.pattern if self.top_level is not None: discover_kwargs['top_level_dir'] = self.top_level for label in test_labels: kwargs = discover_kwargs.copy() tests = None label_as_path = os.path.abspath(label) # if a module, or "module.ClassName[.method_name]", just run those if not os.path.exists(label_as_path): tests = self.test_loader.loadTestsFromName(label) elif os.path.isdir(label_as_path) and not self.top_level: # Try to be a bit smarter than unittest about finding the # default top-level for a given directory path, to avoid # breaking relative imports. (Unittest's default is to set # top-level equal to the path, which means relative imports # will result in "Attempted relative import in non-package."). # We'd be happy to skip this and require dotted module paths # (which don't cause this problem) instead of file paths (which # do), but in the case of a directory in the cwd, which would # be equally valid if considered as a top-level module or as a # directory path, unittest unfortunately prefers the latter. top_level = label_as_path while True: init_py = os.path.join(top_level, '__init__.py') if os.path.exists(init_py): try_next = os.path.dirname(top_level) if try_next == top_level: # __init__.py all the way down? give up. break top_level = try_next continue break kwargs['top_level_dir'] = top_level if not (tests and tests.countTestCases()) and is_discoverable(label): # Try discovery if path is a package or directory tests = self.test_loader.discover(start_dir=label, **kwargs) # Make unittest forget the top-level dir it calculated from this # run, to support running tests from two different top-levels. self.test_loader._top_level_dir = None suite.addTests(tests) for test in extra_tests: suite.addTest(test) if self.tags or self.exclude_tags: suite = filter_tests_by_tags(suite, self.tags, self.exclude_tags) suite = reorder_suite(suite, self.reorder_by, self.reverse) if self.parallel > 1: parallel_suite = self.parallel_test_suite(suite, self.parallel, self.failfast) # Since tests are distributed across processes on a per-TestCase # basis, there's no need for more processes than TestCases. parallel_units = len(parallel_suite.subsuites) if self.parallel > parallel_units: self.parallel = parallel_units # If there's only one TestCase, parallelization isn't needed. if self.parallel > 1: suite = parallel_suite return suite def setup_databases(self, **kwargs): return _setup_databases( self.verbosity, self.interactive, self.keepdb, self.debug_sql, self.parallel, **kwargs ) def get_resultclass(self): return DebugSQLTextTestResult if self.debug_sql else None def get_test_runner_kwargs(self): return dict( failfast=self.failfast, resultclass=self.get_resultclass(), verbosity=self.verbosity, ) def run_suite(self, suite, **kwargs): kwargs = self.get_test_runner_kwargs() runner = self.test_runner(**kwargs) return runner.run(suite) def teardown_databases(self, old_config, **kwargs): """ Destroys all the non-mirror databases. """ _teardown_databases( old_config, verbosity=self.verbosity, parallel=self.parallel, keepdb=self.keepdb, ) def teardown_test_environment(self, **kwargs): unittest.removeHandler() teardown_test_environment() def suite_result(self, suite, result, **kwargs): return len(result.failures) + len(result.errors) def run_tests(self, test_labels, extra_tests=None, **kwargs): """ Run the unit tests for all the test labels in the provided list. Test labels should be dotted Python paths to test modules, test classes, or test methods. A list of 'extra' tests may also be provided; these tests will be added to the test suite. Returns the number of tests that failed. """ self.setup_test_environment() suite = self.build_suite(test_labels, extra_tests) old_config = self.setup_databases() result = self.run_suite(suite) self.teardown_databases(old_config) self.teardown_test_environment() return self.suite_result(suite, result) def is_discoverable(label): """ Check if a test label points to a python package or file directory. Relative labels like "." and ".." are seen as directories. """ try: mod = import_module(label) except (ImportError, TypeError): pass else: return hasattr(mod, '__path__') return os.path.isdir(os.path.abspath(label)) def reorder_suite(suite, classes, reverse=False): """ Reorders a test suite by test type. `classes` is a sequence of types All tests of type classes[0] are placed first, then tests of type classes[1], etc. Tests with no match in classes are placed last. If `reverse` is True, tests within classes are sorted in opposite order, but test classes are not reversed. """ class_count = len(classes) suite_class = type(suite) bins = [OrderedSet() for i in range(class_count + 1)] partition_suite_by_type(suite, classes, bins, reverse=reverse) reordered_suite = suite_class() for i in range(class_count + 1): reordered_suite.addTests(bins[i]) return reordered_suite def partition_suite_by_type(suite, classes, bins, reverse=False): """ Partitions a test suite by test type. Also prevents duplicated tests. classes is a sequence of types bins is a sequence of TestSuites, one more than classes reverse changes the ordering of tests within bins Tests of type classes[i] are added to bins[i], tests with no match found in classes are place in bins[-1] """ suite_class = type(suite) if reverse: suite = reversed(tuple(suite)) for test in suite: if isinstance(test, suite_class): partition_suite_by_type(test, classes, bins, reverse=reverse) else: for i in range(len(classes)): if isinstance(test, classes[i]): bins[i].add(test) break else: bins[-1].add(test) def partition_suite_by_case(suite): """ Partitions a test suite by test case, preserving the order of tests. """ groups = [] suite_class = type(suite) for test_type, test_group in itertools.groupby(suite, type): if issubclass(test_type, unittest.TestCase): groups.append(suite_class(test_group)) else: for item in test_group: groups.extend(partition_suite_by_case(item)) return groups def setup_databases(*args, **kwargs): warnings.warn( '`django.test.runner.setup_databases()` has moved to ' '`django.test.utils.setup_databases()`.', RemovedInDjango21Warning, stacklevel=2, ) return _setup_databases(*args, **kwargs) def filter_tests_by_tags(suite, tags, exclude_tags): suite_class = type(suite) filtered_suite = suite_class() for test in suite: if isinstance(test, suite_class): filtered_suite.addTests(filter_tests_by_tags(test, tags, exclude_tags)) else: test_tags = set(getattr(test, 'tags', set())) test_fn_name = getattr(test, '_testMethodName', str(test)) test_fn = getattr(test, test_fn_name, test) test_fn_tags = set(getattr(test_fn, 'tags', set())) all_tags = test_tags.union(test_fn_tags) matched_tags = all_tags.intersection(tags) if (matched_tags or not tags) and not all_tags.intersection(exclude_tags): filtered_suite.addTest(test) return filtered_suite
3b86fd465c30ecf536bb2185c6ee74b99a16d18557c8a46ab14a1a6cd62895f5
from __future__ import unicode_literals import json import mimetypes import os import re import sys from copy import copy from importlib import import_module from io import BytesIO from django.conf import settings from django.core.handlers.base import BaseHandler from django.core.handlers.wsgi import ISO_8859_1, UTF_8, WSGIRequest from django.core.signals import ( got_request_exception, request_finished, request_started, ) from django.db import close_old_connections from django.http import HttpRequest, QueryDict, SimpleCookie from django.template import TemplateDoesNotExist from django.test import signals from django.test.utils import ContextList from django.urls import resolve from django.utils import six from django.utils.encoding import force_bytes, force_str, uri_to_iri from django.utils.functional import SimpleLazyObject, curry from django.utils.http import urlencode from django.utils.itercompat import is_iterable from django.utils.six.moves.urllib.parse import urljoin, urlparse, urlsplit __all__ = ('Client', 'RedirectCycleError', 'RequestFactory', 'encode_file', 'encode_multipart') BOUNDARY = 'BoUnDaRyStRiNg' MULTIPART_CONTENT = 'multipart/form-data; boundary=%s' % BOUNDARY CONTENT_TYPE_RE = re.compile(r'.*; charset=([\w\d-]+);?') class RedirectCycleError(Exception): """ The test client has been asked to follow a redirect loop. """ def __init__(self, message, last_response): super(RedirectCycleError, self).__init__(message) self.last_response = last_response self.redirect_chain = last_response.redirect_chain class FakePayload(object): """ A wrapper around BytesIO that restricts what can be read since data from the network can't be seeked and cannot be read outside of its content length. This makes sure that views can't do anything under the test client that wouldn't work in Real Life. """ def __init__(self, content=None): self.__content = BytesIO() self.__len = 0 self.read_started = False if content is not None: self.write(content) def __len__(self): return self.__len def read(self, num_bytes=None): if not self.read_started: self.__content.seek(0) self.read_started = True if num_bytes is None: num_bytes = self.__len or 0 assert self.__len >= num_bytes, "Cannot read more than the available bytes from the HTTP incoming data." content = self.__content.read(num_bytes) self.__len -= num_bytes return content def write(self, content): if self.read_started: raise ValueError("Unable to write a payload after he's been read") content = force_bytes(content) self.__content.write(content) self.__len += len(content) def closing_iterator_wrapper(iterable, close): try: for item in iterable: yield item finally: request_finished.disconnect(close_old_connections) close() # will fire request_finished request_finished.connect(close_old_connections) def conditional_content_removal(request, response): """ Simulate the behavior of most Web servers by removing the content of responses for HEAD requests, 1xx, 204, and 304 responses. Ensures compliance with RFC 7230, section 3.3.3. """ if 100 <= response.status_code < 200 or response.status_code in (204, 304): if response.streaming: response.streaming_content = [] else: response.content = b'' response['Content-Length'] = '0' if request.method == 'HEAD': if response.streaming: response.streaming_content = [] else: response.content = b'' return response class ClientHandler(BaseHandler): """ A HTTP Handler that can be used for testing purposes. Uses the WSGI interface to compose requests, but returns the raw HttpResponse object with the originating WSGIRequest attached to its ``wsgi_request`` attribute. """ def __init__(self, enforce_csrf_checks=True, *args, **kwargs): self.enforce_csrf_checks = enforce_csrf_checks super(ClientHandler, self).__init__(*args, **kwargs) def __call__(self, environ): # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._middleware_chain is None: self.load_middleware() request_started.disconnect(close_old_connections) request_started.send(sender=self.__class__, environ=environ) request_started.connect(close_old_connections) request = WSGIRequest(environ) # sneaky little hack so that we can easily get round # CsrfViewMiddleware. This makes life easier, and is probably # required for backwards compatibility with external tests against # admin views. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks # Request goes through middleware. response = self.get_response(request) # Simulate behaviors of most Web servers. conditional_content_removal(request, response) # Attach the originating request to the response so that it could be # later retrieved. response.wsgi_request = request # We're emulating a WSGI server; we must call the close method # on completion. if response.streaming: response.streaming_content = closing_iterator_wrapper( response.streaming_content, response.close) else: request_finished.disconnect(close_old_connections) response.close() # will fire request_finished request_finished.connect(close_old_connections) return response def store_rendered_templates(store, signal, sender, template, context, **kwargs): """ Stores templates and contexts that are rendered. The context is copied so that it is an accurate representation at the time of rendering. """ store.setdefault('templates', []).append(template) if 'context' not in store: store['context'] = ContextList() store['context'].append(copy(context)) def encode_multipart(boundary, data): """ Encodes multipart POST data from a dictionary of form values. The key will be used as the form data name; the value will be transmitted as content. If the value is a file, the contents of the file will be sent as an application/octet-stream; otherwise, str(value) will be sent. """ lines = [] def to_bytes(s): return force_bytes(s, settings.DEFAULT_CHARSET) # Not by any means perfect, but good enough for our purposes. def is_file(thing): return hasattr(thing, "read") and callable(thing.read) # Each bit of the multipart form data could be either a form value or a # file, or a *list* of form values and/or files. Remember that HTTP field # names can be duplicated! for (key, value) in data.items(): if is_file(value): lines.extend(encode_file(boundary, key, value)) elif not isinstance(value, six.string_types) and is_iterable(value): for item in value: if is_file(item): lines.extend(encode_file(boundary, key, item)) else: lines.extend(to_bytes(val) for val in [ '--%s' % boundary, 'Content-Disposition: form-data; name="%s"' % key, '', item ]) else: lines.extend(to_bytes(val) for val in [ '--%s' % boundary, 'Content-Disposition: form-data; name="%s"' % key, '', value ]) lines.extend([ to_bytes('--%s--' % boundary), b'', ]) return b'\r\n'.join(lines) def encode_file(boundary, key, file): def to_bytes(s): return force_bytes(s, settings.DEFAULT_CHARSET) # file.name might not be a string. For example, it's an int for # tempfile.TemporaryFile(). file_has_string_name = hasattr(file, 'name') and isinstance(file.name, six.string_types) filename = os.path.basename(file.name) if file_has_string_name else '' if hasattr(file, 'content_type'): content_type = file.content_type elif filename: content_type = mimetypes.guess_type(filename)[0] else: content_type = None if content_type is None: content_type = 'application/octet-stream' if not filename: filename = key return [ to_bytes('--%s' % boundary), to_bytes('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)), to_bytes('Content-Type: %s' % content_type), b'', to_bytes(file.read()) ] class RequestFactory(object): """ Class that lets you create mock Request objects for use in testing. Usage: rf = RequestFactory() get_request = rf.get('/hello/') post_request = rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, just as if that view had been hooked up using a URLconf. """ def __init__(self, **defaults): self.defaults = defaults self.cookies = SimpleCookie() self.errors = BytesIO() def _base_environ(self, **request): """ The base environment for a request. """ # This is a minimal valid WSGI environ dictionary, plus: # - HTTP_COOKIE: for cookie support, # - REMOTE_ADDR: often useful, see #8551. # See http://www.python.org/dev/peps/pep-3333/#environ-variables environ = { 'HTTP_COOKIE': self.cookies.output(header='', sep='; '), 'PATH_INFO': str('/'), 'REMOTE_ADDR': str('127.0.0.1'), 'REQUEST_METHOD': str('GET'), 'SCRIPT_NAME': str(''), 'SERVER_NAME': str('testserver'), 'SERVER_PORT': str('80'), 'SERVER_PROTOCOL': str('HTTP/1.1'), 'wsgi.version': (1, 0), 'wsgi.url_scheme': str('http'), 'wsgi.input': FakePayload(b''), 'wsgi.errors': self.errors, 'wsgi.multiprocess': True, 'wsgi.multithread': False, 'wsgi.run_once': False, } environ.update(self.defaults) environ.update(request) return environ def request(self, **request): "Construct a generic request object." return WSGIRequest(self._base_environ(**request)) def _encode_data(self, data, content_type): if content_type is MULTIPART_CONTENT: return encode_multipart(BOUNDARY, data) else: # Encode the content so that the byte representation is correct. match = CONTENT_TYPE_RE.match(content_type) if match: charset = match.group(1) else: charset = settings.DEFAULT_CHARSET return force_bytes(data, encoding=charset) def _get_path(self, parsed): path = force_str(parsed[2]) # If there are parameters, add them if parsed[3]: path += str(";") + force_str(parsed[3]) path = uri_to_iri(path).encode(UTF_8) # Under Python 3, non-ASCII values in the WSGI environ are arbitrarily # decoded with ISO-8859-1. We replicate this behavior here. # Refs comment in `get_bytes_from_wsgi()`. return path.decode(ISO_8859_1) if six.PY3 else path def get(self, path, data=None, secure=False, **extra): "Construct a GET request." data = {} if data is None else data r = { 'QUERY_STRING': urlencode(data, doseq=True), } r.update(extra) return self.generic('GET', path, secure=secure, **r) def post(self, path, data=None, content_type=MULTIPART_CONTENT, secure=False, **extra): "Construct a POST request." data = {} if data is None else data post_data = self._encode_data(data, content_type) return self.generic('POST', path, post_data, content_type, secure=secure, **extra) def head(self, path, data=None, secure=False, **extra): "Construct a HEAD request." data = {} if data is None else data r = { 'QUERY_STRING': urlencode(data, doseq=True), } r.update(extra) return self.generic('HEAD', path, secure=secure, **r) def trace(self, path, secure=False, **extra): "Construct a TRACE request." return self.generic('TRACE', path, secure=secure, **extra) def options(self, path, data='', content_type='application/octet-stream', secure=False, **extra): "Construct an OPTIONS request." return self.generic('OPTIONS', path, data, content_type, secure=secure, **extra) def put(self, path, data='', content_type='application/octet-stream', secure=False, **extra): "Construct a PUT request." return self.generic('PUT', path, data, content_type, secure=secure, **extra) def patch(self, path, data='', content_type='application/octet-stream', secure=False, **extra): "Construct a PATCH request." return self.generic('PATCH', path, data, content_type, secure=secure, **extra) def delete(self, path, data='', content_type='application/octet-stream', secure=False, **extra): "Construct a DELETE request." return self.generic('DELETE', path, data, content_type, secure=secure, **extra) def generic(self, method, path, data='', content_type='application/octet-stream', secure=False, **extra): """Constructs an arbitrary HTTP request.""" parsed = urlparse(force_str(path)) data = force_bytes(data, settings.DEFAULT_CHARSET) r = { 'PATH_INFO': self._get_path(parsed), 'REQUEST_METHOD': str(method), 'SERVER_PORT': str('443') if secure else str('80'), 'wsgi.url_scheme': str('https') if secure else str('http'), } if data: r.update({ 'CONTENT_LENGTH': len(data), 'CONTENT_TYPE': str(content_type), 'wsgi.input': FakePayload(data), }) r.update(extra) # If QUERY_STRING is absent or empty, we want to extract it from the URL. if not r.get('QUERY_STRING'): query_string = force_bytes(parsed[4]) # WSGI requires latin-1 encoded strings. See get_path_info(). if six.PY3: query_string = query_string.decode('iso-8859-1') r['QUERY_STRING'] = query_string return self.request(**r) class Client(RequestFactory): """ A class that can act as a client for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and templates that were rendered during the process of serving the request. Client objects are stateful - they will retain cookie (and thus session) details for the lifetime of the Client instance. This is not intended as a replacement for Twill/Selenium or the like - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ def __init__(self, enforce_csrf_checks=False, **defaults): super(Client, self).__init__(**defaults) self.handler = ClientHandler(enforce_csrf_checks) self.exc_info = None def store_exc_info(self, **kwargs): """ Stores exceptions when they are generated by a view. """ self.exc_info = sys.exc_info() @property def session(self): """ Obtains the current session variables. """ engine = import_module(settings.SESSION_ENGINE) cookie = self.cookies.get(settings.SESSION_COOKIE_NAME) if cookie: return engine.SessionStore(cookie.value) session = engine.SessionStore() session.save() self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key return session def request(self, **request): """ The master request method. Composes the environment dictionary and passes to the handler, returning the result of the handler. Assumes defaults for the query environment, which can be overridden using the arguments to the request. """ environ = self._base_environ(**request) # Curry a data dictionary into an instance of the template renderer # callback function. data = {} on_template_render = curry(store_rendered_templates, data) signal_uid = "template-render-%s" % id(request) signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid) # Capture exceptions created by the handler. exception_uid = "request-exception-%s" % id(request) got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid) try: try: response = self.handler(environ) except TemplateDoesNotExist as e: # If the view raises an exception, Django will attempt to show # the 500.html template. If that template is not available, # we should ignore the error in favor of re-raising the # underlying exception that caused the 500 error. Any other # template found to be missing during view error handling # should be reported as-is. if e.args != ('500.html',): raise # Look for a signalled exception, clear the current context # exception data, then re-raise the signalled exception. # Also make sure that the signalled exception is cleared from # the local cache! if self.exc_info: exc_info = self.exc_info self.exc_info = None six.reraise(*exc_info) # Save the client and request that stimulated the response. response.client = self response.request = request # Add any rendered template detail to the response. response.templates = data.get("templates", []) response.context = data.get("context") response.json = curry(self._parse_json, response) # Attach the ResolverMatch instance to the response response.resolver_match = SimpleLazyObject(lambda: resolve(request['PATH_INFO'])) # Flatten a single context. Not really necessary anymore thanks to # the __getattr__ flattening in ContextList, but has some edge-case # backwards-compatibility implications. if response.context and len(response.context) == 1: response.context = response.context[0] # Update persistent cookie data. if response.cookies: self.cookies.update(response.cookies) return response finally: signals.template_rendered.disconnect(dispatch_uid=signal_uid) got_request_exception.disconnect(dispatch_uid=exception_uid) def get(self, path, data=None, follow=False, secure=False, **extra): """ Requests a response from the server using GET. """ response = super(Client, self).get(path, data=data, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response def post(self, path, data=None, content_type=MULTIPART_CONTENT, follow=False, secure=False, **extra): """ Requests a response from the server using POST. """ response = super(Client, self).post(path, data=data, content_type=content_type, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response def head(self, path, data=None, follow=False, secure=False, **extra): """ Request a response from the server using HEAD. """ response = super(Client, self).head(path, data=data, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response def options(self, path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra): """ Request a response from the server using OPTIONS. """ response = super(Client, self).options(path, data=data, content_type=content_type, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response def put(self, path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra): """ Send a resource to the server using PUT. """ response = super(Client, self).put(path, data=data, content_type=content_type, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response def patch(self, path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra): """ Send a resource to the server using PATCH. """ response = super(Client, self).patch(path, data=data, content_type=content_type, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response def delete(self, path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra): """ Send a DELETE request to the server. """ response = super(Client, self).delete(path, data=data, content_type=content_type, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response def trace(self, path, data='', follow=False, secure=False, **extra): """ Send a TRACE request to the server. """ response = super(Client, self).trace(path, data=data, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response def login(self, **credentials): """ Sets the Factory to appear as if it has successfully logged into a site. Returns True if login is possible; False if the provided credentials are incorrect. """ from django.contrib.auth import authenticate user = authenticate(**credentials) if user: self._login(user) return True else: return False def force_login(self, user, backend=None): if backend is None: backend = settings.AUTHENTICATION_BACKENDS[0] user.backend = backend self._login(user, backend) def _login(self, user, backend=None): from django.contrib.auth import login engine = import_module(settings.SESSION_ENGINE) # Create a fake request to store login details. request = HttpRequest() if self.session: request.session = self.session else: request.session = engine.SessionStore() login(request, user, backend) # Save the session values. request.session.save() # Set the cookie to represent the session. session_cookie = settings.SESSION_COOKIE_NAME self.cookies[session_cookie] = request.session.session_key cookie_data = { 'max-age': None, 'path': '/', 'domain': settings.SESSION_COOKIE_DOMAIN, 'secure': settings.SESSION_COOKIE_SECURE or None, 'expires': None, } self.cookies[session_cookie].update(cookie_data) def logout(self): """ Removes the authenticated user's cookies and session object. Causes the authenticated user to be logged out. """ from django.contrib.auth import get_user, logout request = HttpRequest() engine = import_module(settings.SESSION_ENGINE) if self.session: request.session = self.session request.user = get_user(request) else: request.session = engine.SessionStore() logout(request) self.cookies = SimpleCookie() 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')) ) return json.loads(response.content.decode(), **extra) def _handle_redirects(self, response, **extra): "Follows any redirects by requesting responses from the server using GET." response.redirect_chain = [] while response.status_code in (301, 302, 303, 307): response_url = response.url redirect_chain = response.redirect_chain redirect_chain.append((response_url, response.status_code)) url = urlsplit(response_url) if url.scheme: extra['wsgi.url_scheme'] = url.scheme if url.hostname: extra['SERVER_NAME'] = url.hostname if url.port: extra['SERVER_PORT'] = str(url.port) # Prepend the request path to handle relative path redirects path = url.path if not path.startswith('/'): path = urljoin(response.request['PATH_INFO'], path) response = self.get(path, QueryDict(url.query), follow=False, **extra) response.redirect_chain = redirect_chain if redirect_chain[-1] in redirect_chain[:-1]: # Check that we're not redirecting to somewhere we've already # been to, to prevent loops. raise RedirectCycleError("Redirect loop detected.", last_response=response) if len(redirect_chain) > 20: # Such a lengthy chain likely also means a loop, but one with # a growing path, changing view, or changing query argument; # 20 is the value of "network.http.redirection-limit" from Firefox. raise RedirectCycleError("Too many redirects.", last_response=response) return response
e61c7f1382f93481cda29cc29ed03a74d33ecb03d9c0ffc5520a9bc0b1b404fa
from __future__ import unicode_literals import difflib import json import posixpath import sys import threading import unittest import warnings from collections import Counter from contextlib import contextmanager from copy import copy from functools import wraps from unittest.util import safe_repr from django.apps import apps from django.conf import settings from django.core import mail from django.core.exceptions import ValidationError from django.core.files import locks from django.core.handlers.wsgi import WSGIHandler, get_path_info from django.core.management import call_command from django.core.management.color import no_style from django.core.management.sql import emit_post_migrate_signal from django.core.servers.basehttp import WSGIRequestHandler, WSGIServer from django.db import DEFAULT_DB_ALIAS, connection, connections, transaction from django.forms.fields import CharField from django.http import QueryDict from django.http.request import split_domain_port, validate_host from django.test.client import Client from django.test.html import HTMLParseError, parse_html from django.test.signals import setting_changed, template_rendered from django.test.utils import ( CaptureQueriesContext, ContextList, compare_xml, modify_settings, override_settings, ) from django.utils import six from django.utils.decorators import classproperty from django.utils.deprecation import RemovedInDjango20Warning from django.utils.encoding import force_text from django.utils.six.moves.urllib.parse import ( unquote, urljoin, urlparse, urlsplit, urlunsplit, ) from django.utils.six.moves.urllib.request import url2pathname from django.views.static import serve __all__ = ('TestCase', 'TransactionTestCase', 'SimpleTestCase', 'skipIfDBFeature', 'skipUnlessDBFeature') def to_list(value): """ Puts value into a list if it's not already one. Returns an empty list if value is None. """ if value is None: value = [] elif not isinstance(value, list): value = [value] return value def assert_and_parse_html(self, html, user_msg, msg): try: dom = parse_html(html) except HTMLParseError as e: standardMsg = '%s\n%s' % (msg, e) self.fail(self._formatMessage(user_msg, standardMsg)) return dom class _AssertNumQueriesContext(CaptureQueriesContext): def __init__(self, test_case, num, connection): self.test_case = test_case self.num = num super(_AssertNumQueriesContext, self).__init__(connection) def __exit__(self, exc_type, exc_value, traceback): super(_AssertNumQueriesContext, self).__exit__(exc_type, exc_value, traceback) if exc_type is not None: return executed = len(self) self.test_case.assertEqual( executed, self.num, "%d queries executed, %d expected\nCaptured queries were:\n%s" % ( executed, self.num, '\n'.join( query['sql'] for query in self.captured_queries ) ) ) class _AssertTemplateUsedContext(object): def __init__(self, test_case, template_name): self.test_case = test_case self.template_name = template_name self.rendered_templates = [] self.rendered_template_names = [] self.context = ContextList() def on_template_render(self, sender, signal, template, context, **kwargs): self.rendered_templates.append(template) self.rendered_template_names.append(template.name) self.context.append(copy(context)) def test(self): return self.template_name in self.rendered_template_names def message(self): return '%s was not rendered.' % self.template_name def __enter__(self): template_rendered.connect(self.on_template_render) return self def __exit__(self, exc_type, exc_value, traceback): template_rendered.disconnect(self.on_template_render) if exc_type is not None: return if not self.test(): message = self.message() if len(self.rendered_templates) == 0: message += ' No template was rendered.' else: message += ' Following templates were rendered: %s' % ( ', '.join(self.rendered_template_names)) self.test_case.fail(message) class _AssertTemplateNotUsedContext(_AssertTemplateUsedContext): def test(self): return self.template_name not in self.rendered_template_names def message(self): return '%s was rendered.' % self.template_name class _CursorFailure(object): def __init__(self, cls_name, wrapped): self.cls_name = cls_name self.wrapped = wrapped def __call__(self): raise AssertionError( "Database queries aren't allowed in SimpleTestCase. " "Either use TestCase or TransactionTestCase to ensure proper test isolation or " "set %s.allow_database_queries to True to silence this failure." % self.cls_name ) class SimpleTestCase(unittest.TestCase): # The class we'll use for the test client self.client. # Can be overridden in derived classes. client_class = Client _overridden_settings = None _modified_settings = None # Tests shouldn't be allowed to query the database since # this base class doesn't enforce any isolation. allow_database_queries = False @classmethod def setUpClass(cls): super(SimpleTestCase, cls).setUpClass() if cls._overridden_settings: cls._cls_overridden_context = override_settings(**cls._overridden_settings) cls._cls_overridden_context.enable() if cls._modified_settings: cls._cls_modified_context = modify_settings(cls._modified_settings) cls._cls_modified_context.enable() if not cls.allow_database_queries: for alias in connections: connection = connections[alias] connection.cursor = _CursorFailure(cls.__name__, connection.cursor) @classmethod def tearDownClass(cls): if not cls.allow_database_queries: for alias in connections: connection = connections[alias] connection.cursor = connection.cursor.wrapped if hasattr(cls, '_cls_modified_context'): cls._cls_modified_context.disable() delattr(cls, '_cls_modified_context') if hasattr(cls, '_cls_overridden_context'): cls._cls_overridden_context.disable() delattr(cls, '_cls_overridden_context') super(SimpleTestCase, cls).tearDownClass() def __call__(self, result=None): """ Wrapper around default __call__ method to perform common Django test set up. This means that user-defined Test Cases aren't required to include a call to super().setUp(). """ testMethod = getattr(self, self._testMethodName) skipped = ( getattr(self.__class__, "__unittest_skip__", False) or getattr(testMethod, "__unittest_skip__", False) ) if not skipped: try: self._pre_setup() except Exception: result.addError(self, sys.exc_info()) return super(SimpleTestCase, self).__call__(result) if not skipped: try: self._post_teardown() except Exception: result.addError(self, sys.exc_info()) return def _pre_setup(self): """Performs any pre-test setup. This includes: * Creating a test client. * Clearing the mail test outbox. """ self.client = self.client_class() mail.outbox = [] def _post_teardown(self): """Perform any post-test things.""" pass def settings(self, **kwargs): """ A context manager that temporarily sets a setting and reverts to the original value when exiting the context. """ return override_settings(**kwargs) def modify_settings(self, **kwargs): """ A context manager that temporarily applies changes a list setting and reverts back to the original value when exiting the context. """ return modify_settings(**kwargs) def assertRedirects(self, response, expected_url, status_code=302, target_status_code=200, host=None, msg_prefix='', fetch_redirect_response=True): """Asserts that a response redirected to a specific URL, and that the redirect URL can be loaded. Note that assertRedirects won't work for external links since it uses TestClient to do a request (use fetch_redirect_response=False to check such links without fetching them). """ if host is not None: warnings.warn( "The host argument is deprecated and no longer used by assertRedirects", RemovedInDjango20Warning, stacklevel=2 ) if msg_prefix: msg_prefix += ": " if hasattr(response, 'redirect_chain'): # The request was a followed redirect self.assertTrue( len(response.redirect_chain) > 0, msg_prefix + "Response didn't redirect as expected: Response code was %d (expected %d)" % (response.status_code, status_code) ) self.assertEqual( response.redirect_chain[0][1], status_code, msg_prefix + "Initial response didn't redirect as expected: Response code was %d (expected %d)" % (response.redirect_chain[0][1], status_code) ) url, status_code = response.redirect_chain[-1] scheme, netloc, path, query, fragment = urlsplit(url) self.assertEqual( response.status_code, target_status_code, msg_prefix + "Response didn't redirect as expected: Final Response code was %d (expected %d)" % (response.status_code, target_status_code) ) else: # Not a followed redirect self.assertEqual( response.status_code, status_code, msg_prefix + "Response didn't redirect as expected: Response code was %d (expected %d)" % (response.status_code, status_code) ) url = response.url scheme, netloc, path, query, fragment = urlsplit(url) # Prepend the request path to handle relative path redirects. if not path.startswith('/'): url = urljoin(response.request['PATH_INFO'], url) path = urljoin(response.request['PATH_INFO'], path) if fetch_redirect_response: # netloc might be empty, or in cases where Django tests the # HTTP scheme, the convention is for netloc to be 'testserver'. # Trust both as "internal" URLs here. domain, port = split_domain_port(netloc) if domain and not validate_host(domain, settings.ALLOWED_HOSTS): raise ValueError( "The test client is unable to fetch remote URLs (got %s). " "If the host is served by Django, add '%s' to ALLOWED_HOSTS. " "Otherwise, use assertRedirects(..., fetch_redirect_response=False)." % (url, domain) ) redirect_response = response.client.get(path, QueryDict(query), secure=(scheme == 'https')) # Get the redirection page, using the same client that was used # to obtain the original response. self.assertEqual( redirect_response.status_code, target_status_code, msg_prefix + "Couldn't retrieve redirection page '%s': response code was %d (expected %d)" % (path, redirect_response.status_code, target_status_code) ) if url != expected_url: # For temporary backwards compatibility, try to compare with a relative url e_scheme, e_netloc, e_path, e_query, e_fragment = urlsplit(expected_url) relative_url = urlunsplit(('', '', e_path, e_query, e_fragment)) if url == relative_url: warnings.warn( "assertRedirects had to strip the scheme and domain from the " "expected URL, as it was always added automatically to URLs " "before Django 1.9. Please update your expected URLs by " "removing the scheme and domain.", RemovedInDjango20Warning, stacklevel=2) expected_url = relative_url self.assertEqual( url, expected_url, msg_prefix + "Response redirected to '%s', expected '%s'" % (url, expected_url) ) def _assert_contains(self, response, text, status_code, msg_prefix, html): # If the response supports deferred rendering and hasn't been rendered # yet, then ensure that it does get rendered before proceeding further. if hasattr(response, 'render') and callable(response.render) and not response.is_rendered: response.render() if msg_prefix: msg_prefix += ": " self.assertEqual( response.status_code, status_code, msg_prefix + "Couldn't retrieve content: Response code was %d" " (expected %d)" % (response.status_code, status_code) ) if response.streaming: content = b''.join(response.streaming_content) else: content = response.content if not isinstance(text, bytes) or html: text = force_text(text, encoding=response.charset) content = content.decode(response.charset) text_repr = "'%s'" % text else: text_repr = repr(text) if html: content = assert_and_parse_html(self, content, None, "Response's content is not valid HTML:") text = assert_and_parse_html(self, text, None, "Second argument is not valid HTML:") real_count = content.count(text) return (text_repr, real_count, msg_prefix) def assertContains(self, response, text, count=None, status_code=200, msg_prefix='', html=False): """ Asserts that a response indicates that some content was retrieved successfully, (i.e., the HTTP status code was as expected), and that ``text`` occurs ``count`` times in the content of the response. If ``count`` is None, the count doesn't matter - the assertion is true if the text occurs at least once in the response. """ text_repr, real_count, msg_prefix = self._assert_contains( response, text, status_code, msg_prefix, html) if count is not None: self.assertEqual( real_count, count, msg_prefix + "Found %d instances of %s in response (expected %d)" % (real_count, text_repr, count) ) else: self.assertTrue(real_count != 0, msg_prefix + "Couldn't find %s in response" % text_repr) def assertNotContains(self, response, text, status_code=200, msg_prefix='', html=False): """ Asserts that a response indicates that some content was retrieved successfully, (i.e., the HTTP status code was as expected), and that ``text`` doesn't occurs in the content of the response. """ text_repr, real_count, msg_prefix = self._assert_contains( response, text, status_code, msg_prefix, html) self.assertEqual(real_count, 0, msg_prefix + "Response should not contain %s" % text_repr) def assertFormError(self, response, form, field, errors, msg_prefix=''): """ Asserts that a form used to render the response has a specific field error. """ if msg_prefix: msg_prefix += ": " # Put context(s) into a list to simplify processing. contexts = to_list(response.context) if not contexts: self.fail(msg_prefix + "Response did not use any contexts to render the response") # Put error(s) into a list to simplify processing. errors = to_list(errors) # Search all contexts for the error. found_form = False for i, context in enumerate(contexts): if form not in context: continue found_form = True for err in errors: if field: if field in context[form].errors: field_errors = context[form].errors[field] self.assertTrue( err in field_errors, msg_prefix + "The field '%s' on form '%s' in" " context %d does not contain the error '%s'" " (actual errors: %s)" % (field, form, i, err, repr(field_errors)) ) elif field in context[form].fields: self.fail( msg_prefix + "The field '%s' on form '%s' in context %d contains no errors" % (field, form, i) ) else: self.fail( msg_prefix + "The form '%s' in context %d does not contain the field '%s'" % (form, i, field) ) else: non_field_errors = context[form].non_field_errors() self.assertTrue( err in non_field_errors, msg_prefix + "The form '%s' in context %d does not" " contain the non-field error '%s'" " (actual errors: %s)" % (form, i, err, non_field_errors) ) if not found_form: self.fail(msg_prefix + "The form '%s' was not used to render the response" % form) def assertFormsetError(self, response, formset, form_index, field, errors, msg_prefix=''): """ Asserts that a formset used to render the response has a specific error. For field errors, specify the ``form_index`` and the ``field``. For non-field errors, specify the ``form_index`` and the ``field`` as None. For non-form errors, specify ``form_index`` as None and the ``field`` as None. """ # Add punctuation to msg_prefix if msg_prefix: msg_prefix += ": " # Put context(s) into a list to simplify processing. contexts = to_list(response.context) if not contexts: self.fail(msg_prefix + 'Response did not use any contexts to ' 'render the response') # Put error(s) into a list to simplify processing. errors = to_list(errors) # Search all contexts for the error. found_formset = False for i, context in enumerate(contexts): if formset not in context: continue found_formset = True for err in errors: if field is not None: if field in context[formset].forms[form_index].errors: field_errors = context[formset].forms[form_index].errors[field] self.assertTrue( err in field_errors, msg_prefix + "The field '%s' on formset '%s', " "form %d in context %d does not contain the " "error '%s' (actual errors: %s)" % (field, formset, form_index, i, err, repr(field_errors)) ) elif field in context[formset].forms[form_index].fields: self.fail( msg_prefix + "The field '%s' on formset '%s', form %d in context %d contains no errors" % (field, formset, form_index, i) ) else: self.fail( msg_prefix + "The formset '%s', form %d in context %d does not contain the field '%s'" % (formset, form_index, i, field) ) elif form_index is not None: non_field_errors = context[formset].forms[form_index].non_field_errors() self.assertFalse( len(non_field_errors) == 0, msg_prefix + "The formset '%s', form %d in context %d " "does not contain any non-field errors." % (formset, form_index, i) ) self.assertTrue( err in non_field_errors, msg_prefix + "The formset '%s', form %d in context %d " "does not contain the non-field error '%s' (actual errors: %s)" % (formset, form_index, i, err, repr(non_field_errors)) ) else: non_form_errors = context[formset].non_form_errors() self.assertFalse( len(non_form_errors) == 0, msg_prefix + "The formset '%s' in context %d does not " "contain any non-form errors." % (formset, i) ) self.assertTrue( err in non_form_errors, msg_prefix + "The formset '%s' in context %d does not " "contain the non-form error '%s' (actual errors: %s)" % (formset, i, err, repr(non_form_errors)) ) if not found_formset: self.fail(msg_prefix + "The formset '%s' was not used to render the response" % formset) def _assert_template_used(self, response, template_name, msg_prefix): if response is None and template_name is None: raise TypeError('response and/or template_name argument must be provided') if msg_prefix: msg_prefix += ": " if template_name is not None and response is not None and not hasattr(response, 'templates'): raise ValueError( "assertTemplateUsed() and assertTemplateNotUsed() are only " "usable on responses fetched using the Django test Client." ) if not hasattr(response, 'templates') or (response is None and template_name): if response: template_name = response response = None # use this template with context manager return template_name, None, msg_prefix template_names = [t.name for t in response.templates if t.name is not None] return None, template_names, msg_prefix def assertTemplateUsed(self, response=None, template_name=None, msg_prefix='', count=None): """ Asserts that the template with the provided name was used in rendering the response. Also usable as context manager. """ context_mgr_template, template_names, msg_prefix = self._assert_template_used( response, template_name, msg_prefix) if context_mgr_template: # Use assertTemplateUsed as context manager. return _AssertTemplateUsedContext(self, context_mgr_template) if not template_names: self.fail(msg_prefix + "No templates used to render the response") self.assertTrue( template_name in template_names, msg_prefix + "Template '%s' was not a template used to render" " the response. Actual template(s) used: %s" % (template_name, ', '.join(template_names)) ) if count is not None: self.assertEqual( template_names.count(template_name), count, msg_prefix + "Template '%s' was expected to be rendered %d " "time(s) but was actually rendered %d time(s)." % (template_name, count, template_names.count(template_name)) ) def assertTemplateNotUsed(self, response=None, template_name=None, msg_prefix=''): """ Asserts that the template with the provided name was NOT used in rendering the response. Also usable as context manager. """ context_mgr_template, template_names, msg_prefix = self._assert_template_used( response, template_name, msg_prefix ) if context_mgr_template: # Use assertTemplateNotUsed as context manager. return _AssertTemplateNotUsedContext(self, context_mgr_template) self.assertFalse( template_name in template_names, msg_prefix + "Template '%s' was used unexpectedly in rendering the response" % template_name ) @contextmanager def _assert_raises_message_cm(self, expected_exception, expected_message): with self.assertRaises(expected_exception) as cm: yield cm self.assertIn(expected_message, str(cm.exception)) def assertRaisesMessage(self, expected_exception, expected_message, *args, **kwargs): """ Asserts that expected_message is found in the the message of a raised exception. Args: expected_exception: Exception class expected to be raised. expected_message: expected error message string value. args: Function to be called and extra positional args. kwargs: Extra kwargs. """ # callable_obj was a documented kwarg in Django 1.8 and older. callable_obj = kwargs.pop('callable_obj', None) if callable_obj: warnings.warn( 'The callable_obj kwarg is deprecated. Pass the callable ' 'as a positional argument instead.', RemovedInDjango20Warning ) elif len(args): callable_obj = args[0] args = args[1:] cm = self._assert_raises_message_cm(expected_exception, expected_message) # Assertion used in context manager fashion. if callable_obj is None: return cm # Assertion was passed a callable. with cm: callable_obj(*args, **kwargs) def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None, field_kwargs=None, empty_value=''): """ Asserts that a form field behaves correctly with various inputs. Args: fieldclass: the class of the field to be tested. valid: a dictionary mapping valid inputs to their expected cleaned values. invalid: a dictionary mapping invalid inputs to one or more raised error messages. field_args: the args passed to instantiate the field field_kwargs: the kwargs passed to instantiate the field empty_value: the expected clean output for inputs in empty_values """ if field_args is None: field_args = [] if field_kwargs is None: field_kwargs = {} required = fieldclass(*field_args, **field_kwargs) optional = fieldclass(*field_args, **dict(field_kwargs, required=False)) # test valid inputs for input, output in valid.items(): self.assertEqual(required.clean(input), output) self.assertEqual(optional.clean(input), output) # test invalid inputs for input, errors in invalid.items(): with self.assertRaises(ValidationError) as context_manager: required.clean(input) self.assertEqual(context_manager.exception.messages, errors) with self.assertRaises(ValidationError) as context_manager: optional.clean(input) self.assertEqual(context_manager.exception.messages, errors) # test required inputs error_required = [force_text(required.error_messages['required'])] for e in required.empty_values: with self.assertRaises(ValidationError) as context_manager: required.clean(e) self.assertEqual(context_manager.exception.messages, error_required) self.assertEqual(optional.clean(e), empty_value) # test that max_length and min_length are always accepted if issubclass(fieldclass, CharField): field_kwargs.update({'min_length': 2, 'max_length': 20}) self.assertIsInstance(fieldclass(*field_args, **field_kwargs), fieldclass) def assertHTMLEqual(self, html1, html2, msg=None): """ Asserts that two HTML snippets are semantically the same. Whitespace in most cases is ignored, and attribute ordering is not significant. The passed-in arguments must be valid HTML. """ dom1 = assert_and_parse_html(self, html1, msg, 'First argument is not valid HTML:') dom2 = assert_and_parse_html(self, html2, msg, 'Second argument is not valid HTML:') if dom1 != dom2: standardMsg = '%s != %s' % ( safe_repr(dom1, True), safe_repr(dom2, True)) diff = ('\n' + '\n'.join(difflib.ndiff( six.text_type(dom1).splitlines(), six.text_type(dom2).splitlines(), ))) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg)) def assertHTMLNotEqual(self, html1, html2, msg=None): """Asserts that two HTML snippets are not semantically equivalent.""" dom1 = assert_and_parse_html(self, html1, msg, 'First argument is not valid HTML:') dom2 = assert_and_parse_html(self, html2, msg, 'Second argument is not valid HTML:') if dom1 == dom2: standardMsg = '%s == %s' % ( safe_repr(dom1, True), safe_repr(dom2, True)) self.fail(self._formatMessage(msg, standardMsg)) def assertInHTML(self, needle, haystack, count=None, msg_prefix=''): needle = assert_and_parse_html(self, needle, None, 'First argument is not valid HTML:') haystack = assert_and_parse_html(self, haystack, None, 'Second argument is not valid HTML:') real_count = haystack.count(needle) if count is not None: self.assertEqual( real_count, count, msg_prefix + "Found %d instances of '%s' in response (expected %d)" % (real_count, needle, count) ) else: self.assertTrue(real_count != 0, msg_prefix + "Couldn't find '%s' in response" % needle) def assertJSONEqual(self, raw, expected_data, msg=None): """ Asserts that the JSON fragments raw and expected_data are equal. Usual JSON non-significant whitespace rules apply as the heavyweight is delegated to the json library. """ try: data = json.loads(raw) except ValueError: self.fail("First argument is not valid JSON: %r" % raw) if isinstance(expected_data, six.string_types): try: expected_data = json.loads(expected_data) except ValueError: self.fail("Second argument is not valid JSON: %r" % expected_data) self.assertEqual(data, expected_data, msg=msg) def assertJSONNotEqual(self, raw, expected_data, msg=None): """ Asserts that the JSON fragments raw and expected_data are not equal. Usual JSON non-significant whitespace rules apply as the heavyweight is delegated to the json library. """ try: data = json.loads(raw) except ValueError: self.fail("First argument is not valid JSON: %r" % raw) if isinstance(expected_data, six.string_types): try: expected_data = json.loads(expected_data) except ValueError: self.fail("Second argument is not valid JSON: %r" % expected_data) self.assertNotEqual(data, expected_data, msg=msg) def assertXMLEqual(self, xml1, xml2, msg=None): """ Asserts that two XML snippets are semantically the same. Whitespace in most cases is ignored, and attribute ordering is not significant. The passed-in arguments must be valid XML. """ try: result = compare_xml(xml1, xml2) except Exception as e: standardMsg = 'First or second argument is not valid XML\n%s' % e self.fail(self._formatMessage(msg, standardMsg)) else: if not result: standardMsg = '%s != %s' % (safe_repr(xml1, True), safe_repr(xml2, True)) diff = ('\n' + '\n'.join( difflib.ndiff( six.text_type(xml1).splitlines(), six.text_type(xml2).splitlines(), ) )) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg)) def assertXMLNotEqual(self, xml1, xml2, msg=None): """ Asserts that two XML snippets are not semantically equivalent. Whitespace in most cases is ignored, and attribute ordering is not significant. The passed-in arguments must be valid XML. """ try: result = compare_xml(xml1, xml2) except Exception as e: standardMsg = 'First or second argument is not valid XML\n%s' % e self.fail(self._formatMessage(msg, standardMsg)) else: if result: standardMsg = '%s == %s' % (safe_repr(xml1, True), safe_repr(xml2, True)) self.fail(self._formatMessage(msg, standardMsg)) class TransactionTestCase(SimpleTestCase): # Subclasses can ask for resetting of auto increment sequence before each # test case reset_sequences = False # Subclasses can enable only a subset of apps for faster tests available_apps = None # Subclasses can define fixtures which will be automatically installed. fixtures = None # If transactions aren't available, Django will serialize the database # contents into a fixture during setup and flush and reload them # during teardown (as flush does not restore data from migrations). # This can be slow; this flag allows enabling on a per-case basis. serialized_rollback = False # Since tests will be wrapped in a transaction, or serialized if they # are not available, we allow queries to be run. allow_database_queries = True def _pre_setup(self): """Performs any pre-test setup. This includes: * If the class has an 'available_apps' attribute, restricting the app registry to these applications, then firing post_migrate -- it must run with the correct set of applications for the test case. * If the class has a 'fixtures' attribute, installing these fixtures. """ super(TransactionTestCase, self)._pre_setup() if self.available_apps is not None: apps.set_available_apps(self.available_apps) setting_changed.send( sender=settings._wrapped.__class__, setting='INSTALLED_APPS', value=self.available_apps, enter=True, ) for db_name in self._databases_names(include_mirrors=False): emit_post_migrate_signal(verbosity=0, interactive=False, db=db_name) try: self._fixture_setup() except Exception: if self.available_apps is not None: apps.unset_available_apps() setting_changed.send( sender=settings._wrapped.__class__, setting='INSTALLED_APPS', value=settings.INSTALLED_APPS, enter=False, ) raise @classmethod def _databases_names(cls, include_mirrors=True): # If the test case has a multi_db=True flag, act on all databases, # including mirrors or not. Otherwise, just on the default DB. if getattr(cls, 'multi_db', False): return [ alias for alias in connections if include_mirrors or not connections[alias].settings_dict['TEST']['MIRROR'] ] else: return [DEFAULT_DB_ALIAS] def _reset_sequences(self, db_name): conn = connections[db_name] if conn.features.supports_sequence_reset: sql_list = conn.ops.sequence_reset_by_name_sql( no_style(), conn.introspection.sequence_list()) if sql_list: with transaction.atomic(using=db_name): cursor = conn.cursor() for sql in sql_list: cursor.execute(sql) def _fixture_setup(self): for db_name in self._databases_names(include_mirrors=False): # Reset sequences if self.reset_sequences: self._reset_sequences(db_name) # If we need to provide replica initial data from migrated apps, # then do so. if self.serialized_rollback and hasattr(connections[db_name], "_test_serialized_contents"): if self.available_apps is not None: apps.unset_available_apps() connections[db_name].creation.deserialize_db_from_string( connections[db_name]._test_serialized_contents ) if self.available_apps is not None: apps.set_available_apps(self.available_apps) if self.fixtures: # We have to use this slightly awkward syntax due to the fact # that we're using *args and **kwargs together. call_command('loaddata', *self.fixtures, **{'verbosity': 0, 'database': db_name}) def _should_reload_connections(self): return True def _post_teardown(self): """Performs any post-test things. This includes: * Flushing the contents of the database, to leave a clean slate. If the class has an 'available_apps' attribute, post_migrate isn't fired. * Force-closing the connection, so the next test gets a clean cursor. """ try: self._fixture_teardown() super(TransactionTestCase, self)._post_teardown() if self._should_reload_connections(): # Some DB cursors include SQL statements as part of cursor # creation. If you have a test that does a rollback, the effect # of these statements is lost, which can affect the operation of # tests (e.g., losing a timezone setting causing objects to be # created with the wrong time). To make sure this doesn't # happen, get a clean connection at the start of every test. for conn in connections.all(): conn.close() finally: if self.available_apps is not None: apps.unset_available_apps() setting_changed.send(sender=settings._wrapped.__class__, setting='INSTALLED_APPS', value=settings.INSTALLED_APPS, enter=False) def _fixture_teardown(self): # Allow TRUNCATE ... CASCADE and don't emit the post_migrate signal # when flushing only a subset of the apps for db_name in self._databases_names(include_mirrors=False): # Flush the database inhibit_post_migrate = ( self.available_apps is not None or ( # Inhibit the post_migrate signal when using serialized # rollback to avoid trying to recreate the serialized data. self.serialized_rollback and hasattr(connections[db_name], '_test_serialized_contents') ) ) call_command('flush', verbosity=0, interactive=False, database=db_name, reset_sequences=False, allow_cascade=self.available_apps is not None, inhibit_post_migrate=inhibit_post_migrate) def assertQuerysetEqual(self, qs, values, transform=repr, ordered=True, msg=None): items = six.moves.map(transform, qs) if not ordered: return self.assertEqual(Counter(items), Counter(values), msg=msg) values = list(values) # For example qs.iterator() could be passed as qs, but it does not # have 'ordered' attribute. if len(values) > 1 and hasattr(qs, 'ordered') and not qs.ordered: raise ValueError("Trying to compare non-ordered queryset " "against more than one ordered values") return self.assertEqual(list(items), values, msg=msg) def assertNumQueries(self, num, func=None, *args, **kwargs): using = kwargs.pop("using", DEFAULT_DB_ALIAS) conn = connections[using] context = _AssertNumQueriesContext(self, num, conn) if func is None: return context with context: func(*args, **kwargs) def connections_support_transactions(): """ Returns True if all connections support transactions. """ return all(conn.features.supports_transactions for conn in connections.all()) class TestCase(TransactionTestCase): """ Similar to TransactionTestCase, but uses `transaction.atomic()` to achieve test isolation. In most situations, TestCase should be preferred to TransactionTestCase as it allows faster execution. However, there are some situations where using TransactionTestCase might be necessary (e.g. testing some transactional behavior). On database backends with no transaction support, TestCase behaves as TransactionTestCase. """ @classmethod def _enter_atomics(cls): """Helper method to open atomic blocks for multiple databases""" atomics = {} for db_name in cls._databases_names(): atomics[db_name] = transaction.atomic(using=db_name) atomics[db_name].__enter__() return atomics @classmethod def _rollback_atomics(cls, atomics): """Rollback atomic blocks opened through the previous method""" for db_name in reversed(cls._databases_names()): transaction.set_rollback(True, using=db_name) atomics[db_name].__exit__(None, None, None) @classmethod def setUpClass(cls): super(TestCase, cls).setUpClass() if not connections_support_transactions(): return cls.cls_atomics = cls._enter_atomics() if cls.fixtures: for db_name in cls._databases_names(include_mirrors=False): try: call_command('loaddata', *cls.fixtures, **{ 'verbosity': 0, 'commit': False, 'database': db_name, }) except Exception: cls._rollback_atomics(cls.cls_atomics) raise try: cls.setUpTestData() except Exception: cls._rollback_atomics(cls.cls_atomics) raise @classmethod def tearDownClass(cls): if connections_support_transactions(): cls._rollback_atomics(cls.cls_atomics) for conn in connections.all(): conn.close() super(TestCase, cls).tearDownClass() @classmethod def setUpTestData(cls): """Load initial data for the TestCase""" pass def _should_reload_connections(self): if connections_support_transactions(): return False return super(TestCase, self)._should_reload_connections() def _fixture_setup(self): if not connections_support_transactions(): # If the backend does not support transactions, we should reload # class data before each test self.setUpTestData() return super(TestCase, self)._fixture_setup() assert not self.reset_sequences, 'reset_sequences cannot be used on TestCase instances' self.atomics = self._enter_atomics() def _fixture_teardown(self): if not connections_support_transactions(): return super(TestCase, self)._fixture_teardown() try: for db_name in reversed(self._databases_names()): if self._should_check_constraints(connections[db_name]): connections[db_name].check_constraints() finally: self._rollback_atomics(self.atomics) def _should_check_constraints(self, connection): return ( connection.features.can_defer_constraint_checks and not connection.needs_rollback and connection.is_usable() ) class CheckCondition(object): """Descriptor class for deferred condition checking""" def __init__(self, *conditions): self.conditions = conditions def add_condition(self, condition, reason): return self.__class__(*self.conditions + ((condition, reason),)) def __get__(self, instance, cls=None): # Trigger access for all bases. if any(getattr(base, '__unittest_skip__', False) for base in cls.__bases__): return True for condition, reason in self.conditions: if condition(): # Override this descriptor's value and set the skip reason. cls.__unittest_skip__ = True cls.__unittest_skip_why__ = reason return True return False def _deferredSkip(condition, reason): def decorator(test_func): if not (isinstance(test_func, type) and issubclass(test_func, unittest.TestCase)): @wraps(test_func) def skip_wrapper(*args, **kwargs): if condition(): raise unittest.SkipTest(reason) return test_func(*args, **kwargs) test_item = skip_wrapper else: # Assume a class is decorated test_item = test_func # Retrieve the possibly existing value from the class's dict to # avoid triggering the descriptor. skip = test_func.__dict__.get('__unittest_skip__') if isinstance(skip, CheckCondition): test_item.__unittest_skip__ = skip.add_condition(condition, reason) elif skip is not True: test_item.__unittest_skip__ = CheckCondition((condition, reason)) return test_item return decorator def skipIfDBFeature(*features): """ Skip a test if a database has at least one of the named features. """ return _deferredSkip( lambda: any(getattr(connection.features, feature, False) for feature in features), "Database has feature(s) %s" % ", ".join(features) ) def skipUnlessDBFeature(*features): """ Skip a test unless a database has all the named features. """ return _deferredSkip( lambda: not all(getattr(connection.features, feature, False) for feature in features), "Database doesn't support feature(s): %s" % ", ".join(features) ) def skipUnlessAnyDBFeature(*features): """ Skip a test unless a database has any of the named features. """ return _deferredSkip( lambda: not any(getattr(connection.features, feature, False) for feature in features), "Database doesn't support any of the feature(s): %s" % ", ".join(features) ) class QuietWSGIRequestHandler(WSGIRequestHandler): """ Just a regular WSGIRequestHandler except it doesn't log to the standard output any of the requests received, so as to not clutter the output for the tests' results. """ def log_message(*args): pass class FSFilesHandler(WSGIHandler): """ WSGI middleware that intercepts calls to a directory, as defined by one of the *_ROOT settings, and serves those files, publishing them under *_URL. """ def __init__(self, application): self.application = application self.base_url = urlparse(self.get_base_url()) super(FSFilesHandler, self).__init__() def _should_handle(self, path): """ Checks if the path should be handled. Ignores the path if: * the host is provided as part of the base_url * the request's path isn't under the media path (or equal) """ return path.startswith(self.base_url[2]) and not self.base_url[1] def file_path(self, url): """ Returns the relative path to the file on disk for the given URL. """ relative_url = url[len(self.base_url[2]):] return url2pathname(relative_url) def get_response(self, request): from django.http import Http404 if self._should_handle(request.path): try: return self.serve(request) except Http404: pass return super(FSFilesHandler, self).get_response(request) def serve(self, request): os_rel_path = self.file_path(request.path) os_rel_path = posixpath.normpath(unquote(os_rel_path)) # Emulate behavior of django.contrib.staticfiles.views.serve() when it # invokes staticfiles' finders functionality. # TODO: Modify if/when that internal API is refactored final_rel_path = os_rel_path.replace('\\', '/').lstrip('/') return serve(request, final_rel_path, document_root=self.get_base_dir()) def __call__(self, environ, start_response): if not self._should_handle(get_path_info(environ)): return self.application(environ, start_response) return super(FSFilesHandler, self).__call__(environ, start_response) class _StaticFilesHandler(FSFilesHandler): """ Handler for serving static files. A private class that is meant to be used solely as a convenience by LiveServerThread. """ def get_base_dir(self): return settings.STATIC_ROOT def get_base_url(self): return settings.STATIC_URL class _MediaFilesHandler(FSFilesHandler): """ Handler for serving the media files. A private class that is meant to be used solely as a convenience by LiveServerThread. """ def get_base_dir(self): return settings.MEDIA_ROOT def get_base_url(self): return settings.MEDIA_URL class LiveServerThread(threading.Thread): """ Thread for running a live http server while the tests are running. """ def __init__(self, host, static_handler, connections_override=None): self.host = host self.port = None self.is_ready = threading.Event() self.error = None self.static_handler = static_handler self.connections_override = connections_override super(LiveServerThread, self).__init__() def run(self): """ Sets up the live server and databases, and then loops over handling http requests. """ if self.connections_override: # Override this thread's database connections with the ones # provided by the main thread. for alias, conn in self.connections_override.items(): connections[alias] = conn try: # Create the handler for serving static and media files handler = self.static_handler(_MediaFilesHandler(WSGIHandler())) self.httpd = self._create_server(0) self.port = self.httpd.server_address[1] self.httpd.set_app(handler) self.is_ready.set() self.httpd.serve_forever() except Exception as e: self.error = e self.is_ready.set() finally: connections.close_all() def _create_server(self, port): return WSGIServer((self.host, port), QuietWSGIRequestHandler, allow_reuse_address=False) def terminate(self): if hasattr(self, 'httpd'): # Stop the WSGI server self.httpd.shutdown() self.httpd.server_close() self.join() class LiveServerTestCase(TransactionTestCase): """ Does basically the same as TransactionTestCase but also launches a live http server in a separate thread so that the tests may use another testing framework, such as Selenium for example, instead of the built-in dummy client. Note that it inherits from TransactionTestCase instead of TestCase because the threads do not share the same transactions (unless if using in-memory sqlite) and each thread needs to commit all their transactions so that the other thread can see the changes. """ host = 'localhost' server_thread_class = LiveServerThread static_handler = _StaticFilesHandler @classproperty def live_server_url(cls): return 'http://%s:%s' % (cls.host, cls.server_thread.port) @classmethod def setUpClass(cls): super(LiveServerTestCase, cls).setUpClass() connections_override = {} for conn in connections.all(): # If using in-memory sqlite databases, pass the connections to # the server thread. if conn.vendor == 'sqlite' and conn.is_in_memory_db(): # Explicitly enable thread-shareability for this connection conn.allow_thread_sharing = True connections_override[conn.alias] = conn cls._live_server_modified_settings = modify_settings( ALLOWED_HOSTS={'append': cls.host}, ) cls._live_server_modified_settings.enable() cls.server_thread = cls._create_server_thread(connections_override) cls.server_thread.daemon = True cls.server_thread.start() # Wait for the live server to be ready cls.server_thread.is_ready.wait() if cls.server_thread.error: # Clean up behind ourselves, since tearDownClass won't get called in # case of errors. cls._tearDownClassInternal() raise cls.server_thread.error @classmethod def _create_server_thread(cls, connections_override): return cls.server_thread_class( cls.host, cls.static_handler, connections_override=connections_override, ) @classmethod def _tearDownClassInternal(cls): # There may not be a 'server_thread' attribute if setUpClass() for some # reasons has raised an exception. if hasattr(cls, 'server_thread'): # Terminate the live server's thread cls.server_thread.terminate() # Restore sqlite in-memory database connections' non-shareability for conn in connections.all(): if conn.vendor == 'sqlite' and conn.is_in_memory_db(): conn.allow_thread_sharing = False @classmethod def tearDownClass(cls): cls._tearDownClassInternal() cls._live_server_modified_settings.disable() super(LiveServerTestCase, cls).tearDownClass() class SerializeMixin(object): """ Mixin to enforce serialization of TestCases that share a common resource. Define a common 'lockfile' for each set of TestCases to serialize. This file must exist on the filesystem. Place it early in the MRO in order to isolate setUpClass / tearDownClass. """ lockfile = None @classmethod def setUpClass(cls): if cls.lockfile is None: raise ValueError( "{}.lockfile isn't set. Set it to a unique value " "in the base class.".format(cls.__name__)) cls._lockfile = open(cls.lockfile) locks.lock(cls._lockfile, locks.LOCK_EX) super(SerializeMixin, cls).setUpClass() @classmethod def tearDownClass(cls): super(SerializeMixin, cls).tearDownClass() cls._lockfile.close()
eed26d70902baf64c3ffc293ffad289a76d72ea89028a7eff48ea67725865ba7
""" Comparing two html documents. """ from __future__ import unicode_literals import re from django.utils import six from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.html_parser import HTMLParseError, HTMLParser WHITESPACE = re.compile(r'\s+') def normalize_whitespace(string): return WHITESPACE.sub(' ', string) @python_2_unicode_compatible class Element(object): def __init__(self, name, attributes): self.name = name self.attributes = sorted(attributes) self.children = [] def append(self, element): if isinstance(element, six.string_types): element = force_text(element) element = normalize_whitespace(element) if self.children: if isinstance(self.children[-1], six.string_types): self.children[-1] += element self.children[-1] = normalize_whitespace(self.children[-1]) return elif self.children: # removing last children if it is only whitespace # this can result in incorrect dom representations since # whitespace between inline tags like <span> is significant if isinstance(self.children[-1], six.string_types): if self.children[-1].isspace(): self.children.pop() if element: self.children.append(element) def finalize(self): def rstrip_last_element(children): if children: if isinstance(children[-1], six.string_types): children[-1] = children[-1].rstrip() if not children[-1]: children.pop() children = rstrip_last_element(children) return children rstrip_last_element(self.children) for i, child in enumerate(self.children): if isinstance(child, six.string_types): self.children[i] = child.strip() elif hasattr(child, 'finalize'): child.finalize() def __eq__(self, element): if not hasattr(element, 'name'): return False if hasattr(element, 'name') and self.name != element.name: return False if len(self.attributes) != len(element.attributes): return False if self.attributes != element.attributes: # attributes without a value is same as attribute with value that # equals the attributes name: # <input checked> == <input checked="checked"> for i in range(len(self.attributes)): attr, value = self.attributes[i] other_attr, other_value = element.attributes[i] if value is None: value = attr if other_value is None: other_value = other_attr if attr != other_attr or value != other_value: return False if self.children != element.children: return False return True def __hash__(self): return hash((self.name,) + tuple(a for a in self.attributes)) def __ne__(self, element): return not self.__eq__(element) def _count(self, element, count=True): if not isinstance(element, six.string_types): if self == element: return 1 if isinstance(element, RootElement): if self.children == element.children: return 1 i = 0 for child in self.children: # child is text content and element is also text content, then # make a simple "text" in "text" if isinstance(child, six.string_types): if isinstance(element, six.string_types): if count: i += child.count(element) elif element in child: return 1 else: i += child._count(element, count=count) if not count and i: return i return i def __contains__(self, element): return self._count(element, count=False) > 0 def count(self, element): return self._count(element, count=True) def __getitem__(self, key): return self.children[key] def __str__(self): output = '<%s' % self.name for key, value in self.attributes: if value: output += ' %s="%s"' % (key, value) else: output += ' %s' % key if self.children: output += '>\n' output += ''.join(six.text_type(c) for c in self.children) output += '\n</%s>' % self.name else: output += ' />' return output def __repr__(self): return six.text_type(self) @python_2_unicode_compatible class RootElement(Element): def __init__(self): super(RootElement, self).__init__(None, ()) def __str__(self): return ''.join(six.text_type(c) for c in self.children) class Parser(HTMLParser): SELF_CLOSING_TAGS = ( 'br', 'hr', 'input', 'img', 'meta', 'spacer', 'link', 'frame', 'base', 'col', ) def __init__(self): HTMLParser.__init__(self) self.root = RootElement() self.open_tags = [] self.element_positions = {} def error(self, msg): raise HTMLParseError(msg, self.getpos()) def format_position(self, position=None, element=None): if not position and element: position = self.element_positions[element] if position is None: position = self.getpos() if hasattr(position, 'lineno'): position = position.lineno, position.offset return 'Line %d, Column %d' % position @property def current(self): if self.open_tags: return self.open_tags[-1] else: return self.root def handle_startendtag(self, tag, attrs): self.handle_starttag(tag, attrs) if tag not in self.SELF_CLOSING_TAGS: self.handle_endtag(tag) def handle_starttag(self, tag, attrs): # Special case handling of 'class' attribute, so that comparisons of DOM # instances are not sensitive to ordering of classes. attrs = [ (name, " ".join(sorted(value.split(" ")))) if name == "class" else (name, value) for name, value in attrs ] element = Element(tag, attrs) self.current.append(element) if tag not in self.SELF_CLOSING_TAGS: self.open_tags.append(element) self.element_positions[element] = self.getpos() def handle_endtag(self, tag): if not self.open_tags: self.error("Unexpected end tag `%s` (%s)" % ( tag, self.format_position())) element = self.open_tags.pop() while element.name != tag: if not self.open_tags: self.error("Unexpected end tag `%s` (%s)" % ( tag, self.format_position())) element = self.open_tags.pop() def handle_data(self, data): self.current.append(data) def handle_charref(self, name): self.current.append('&%s;' % name) def handle_entityref(self, name): self.current.append('&%s;' % name) def parse_html(html): """ Takes a string that contains *valid* HTML and turns it into a Python object structure that can be easily compared against other HTML on semantic equivalence. Syntactical differences like which quotation is used on arguments will be ignored. """ parser = Parser() parser.feed(html) parser.close() document = parser.root document.finalize() # Removing ROOT element if it's not necessary if len(document.children) == 1: if not isinstance(document.children[0], six.string_types): document = document.children[0] return document
0dc2e4609474c12a38ea140f5495e74726071298d1e34a6b1177b8bbc314bd81
import collections import logging import re import sys import time import warnings from contextlib import contextmanager from functools import wraps from unittest import TestCase, skipIf, skipUnless from xml.dom.minidom import Node, parseString from django.apps import apps from django.apps.registry import Apps from django.conf import UserSettingsHolder, settings from django.core import mail from django.core.exceptions import ImproperlyConfigured from django.core.signals import request_started from django.db import DEFAULT_DB_ALIAS, connections, reset_queries from django.db.models.options import Options from django.template import Template from django.test.signals import setting_changed, template_rendered from django.urls import get_script_prefix, set_script_prefix from django.utils import six from django.utils.decorators import available_attrs from django.utils.encoding import force_str from django.utils.translation import deactivate if six.PY3: from types import SimpleNamespace else: class SimpleNamespace(object): pass try: import jinja2 except ImportError: jinja2 = None __all__ = ( 'Approximate', 'ContextList', 'isolate_lru_cache', 'get_runner', 'modify_settings', 'override_settings', 'requires_tz_support', 'setup_test_environment', 'teardown_test_environment', ) TZ_SUPPORT = hasattr(time, 'tzset') class Approximate(object): def __init__(self, val, places=7): self.val = val self.places = places def __repr__(self): return repr(self.val) def __eq__(self, other): if self.val == other: return True return round(abs(self.val - other), self.places) == 0 class ContextList(list): """A wrapper that provides direct key access to context items contained in a list of context objects. """ def __getitem__(self, key): if isinstance(key, six.string_types): for subcontext in self: if key in subcontext: return subcontext[key] raise KeyError(key) else: return super(ContextList, self).__getitem__(key) def __contains__(self, key): try: self[key] except KeyError: return False return True def keys(self): """ Flattened keys of subcontexts. """ keys = set() for subcontext in self: for dict in subcontext: keys |= set(dict.keys()) return keys def instrumented_test_render(self, context): """ An instrumented Template render method, providing a signal that can be intercepted by the test system Client """ template_rendered.send(sender=self, template=self, context=context) return self.nodelist.render(context) class _TestState(object): pass def setup_test_environment(debug=None): """ Perform global pre-test setup, such as installing the instrumented template renderer and setting the email backend to the locmem email backend. """ if hasattr(_TestState, 'saved_data'): # Executing this function twice would overwrite the saved values. raise RuntimeError( "setup_test_environment() was already called and can't be called " "again without first calling teardown_test_environment()." ) if debug is None: debug = settings.DEBUG saved_data = SimpleNamespace() _TestState.saved_data = saved_data saved_data.allowed_hosts = settings.ALLOWED_HOSTS # Add the default host of the test client. settings.ALLOWED_HOSTS = settings.ALLOWED_HOSTS + ['testserver'] saved_data.debug = settings.DEBUG settings.DEBUG = debug saved_data.email_backend = settings.EMAIL_BACKEND settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' saved_data.template_render = Template._render Template._render = instrumented_test_render mail.outbox = [] deactivate() def teardown_test_environment(): """ Perform any global post-test teardown, such as restoring the original template renderer and restoring the email sending functions. """ saved_data = _TestState.saved_data settings.ALLOWED_HOSTS = saved_data.allowed_hosts settings.DEBUG = saved_data.debug settings.EMAIL_BACKEND = saved_data.email_backend Template._render = saved_data.template_render del _TestState.saved_data del mail.outbox def setup_databases(verbosity, interactive, keepdb=False, debug_sql=False, parallel=0, **kwargs): """ Create the test databases. """ test_databases, mirrored_aliases = get_unique_databases_and_mirrors() old_names = [] for signature, (db_name, aliases) in test_databases.items(): first_alias = None for alias in aliases: connection = connections[alias] old_names.append((connection, db_name, first_alias is None)) # Actually create the database for the first connection if first_alias is None: first_alias = alias connection.creation.create_test_db( verbosity=verbosity, autoclobber=not interactive, keepdb=keepdb, serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True), ) if parallel > 1: for index in range(parallel): connection.creation.clone_test_db( number=index + 1, verbosity=verbosity, keepdb=keepdb, ) # Configure all other connections as mirrors of the first one else: connections[alias].creation.set_as_test_mirror(connections[first_alias].settings_dict) # Configure the test mirrors. for alias, mirror_alias in mirrored_aliases.items(): connections[alias].creation.set_as_test_mirror( connections[mirror_alias].settings_dict) if debug_sql: for alias in connections: connections[alias].force_debug_cursor = True return old_names def dependency_ordered(test_databases, dependencies): """ Reorder test_databases into an order that honors the dependencies described in TEST[DEPENDENCIES]. """ ordered_test_databases = [] resolved_databases = set() # Maps db signature to dependencies of all its aliases dependencies_map = {} # Check that no database depends on its own alias for sig, (_, aliases) in test_databases: all_deps = set() for alias in aliases: all_deps.update(dependencies.get(alias, [])) if not all_deps.isdisjoint(aliases): raise ImproperlyConfigured( "Circular dependency: databases %r depend on each other, " "but are aliases." % aliases ) dependencies_map[sig] = all_deps while test_databases: changed = False deferred = [] # Try to find a DB that has all its dependencies met for signature, (db_name, aliases) in test_databases: if dependencies_map[signature].issubset(resolved_databases): resolved_databases.update(aliases) ordered_test_databases.append((signature, (db_name, aliases))) changed = True else: deferred.append((signature, (db_name, aliases))) if not changed: raise ImproperlyConfigured("Circular dependency in TEST[DEPENDENCIES]") test_databases = deferred return ordered_test_databases def get_unique_databases_and_mirrors(): """ Figure out which databases actually need to be created. Deduplicate entries in DATABASES that correspond the same database or are configured as test mirrors. Return two values: - test_databases: ordered mapping of signatures to (name, list of aliases) where all aliases share the same underlying database. - mirrored_aliases: mapping of mirror aliases to original aliases. """ mirrored_aliases = {} test_databases = {} dependencies = {} default_sig = connections[DEFAULT_DB_ALIAS].creation.test_db_signature() for alias in connections: connection = connections[alias] test_settings = connection.settings_dict['TEST'] if test_settings['MIRROR']: # If the database is marked as a test mirror, save the alias. mirrored_aliases[alias] = test_settings['MIRROR'] else: # Store a tuple with DB parameters that uniquely identify it. # If we have two aliases with the same values for that tuple, # we only need to create the test database once. item = test_databases.setdefault( connection.creation.test_db_signature(), (connection.settings_dict['NAME'], set()) ) item[1].add(alias) if 'DEPENDENCIES' in test_settings: dependencies[alias] = test_settings['DEPENDENCIES'] else: if alias != DEFAULT_DB_ALIAS and connection.creation.test_db_signature() != default_sig: dependencies[alias] = test_settings.get('DEPENDENCIES', [DEFAULT_DB_ALIAS]) test_databases = dependency_ordered(test_databases.items(), dependencies) test_databases = collections.OrderedDict(test_databases) return test_databases, mirrored_aliases def teardown_databases(old_config, verbosity, parallel=0, keepdb=False): """ Destroy all the non-mirror databases. """ for connection, old_name, destroy in old_config: if destroy: if parallel > 1: for index in range(parallel): connection.creation.destroy_test_db( number=index + 1, verbosity=verbosity, keepdb=keepdb, ) connection.creation.destroy_test_db(old_name, verbosity, keepdb) def get_runner(settings, test_runner_class=None): if not test_runner_class: test_runner_class = settings.TEST_RUNNER test_path = test_runner_class.split('.') # Allow for Python 2.5 relative paths if len(test_path) > 1: test_module_name = '.'.join(test_path[:-1]) else: test_module_name = '.' test_module = __import__(test_module_name, {}, {}, force_str(test_path[-1])) test_runner = getattr(test_module, test_path[-1]) return test_runner class TestContextDecorator(object): """ A base class that can either be used as a context manager during tests or as a test function or unittest.TestCase subclass decorator to perform temporary alterations. `attr_name`: attribute assigned the return value of enable() if used as a class decorator. `kwarg_name`: keyword argument passing the return value of enable() if used as a function decorator. """ def __init__(self, attr_name=None, kwarg_name=None): self.attr_name = attr_name self.kwarg_name = kwarg_name def enable(self): raise NotImplementedError def disable(self): raise NotImplementedError def __enter__(self): return self.enable() def __exit__(self, exc_type, exc_value, traceback): self.disable() def decorate_class(self, cls): if issubclass(cls, TestCase): decorated_setUp = cls.setUp decorated_tearDown = cls.tearDown def setUp(inner_self): context = self.enable() if self.attr_name: setattr(inner_self, self.attr_name, context) decorated_setUp(inner_self) def tearDown(inner_self): decorated_tearDown(inner_self) self.disable() cls.setUp = setUp cls.tearDown = tearDown return cls raise TypeError('Can only decorate subclasses of unittest.TestCase') def decorate_callable(self, func): @wraps(func, assigned=available_attrs(func)) def inner(*args, **kwargs): with self as context: if self.kwarg_name: kwargs[self.kwarg_name] = context return func(*args, **kwargs) return inner def __call__(self, decorated): if isinstance(decorated, type): return self.decorate_class(decorated) elif callable(decorated): return self.decorate_callable(decorated) raise TypeError('Cannot decorate object of type %s' % type(decorated)) class override_settings(TestContextDecorator): """ Acts as either a decorator or a context manager. If it's a decorator it takes a function and returns a wrapped function. If it's a contextmanager it's used with the ``with`` statement. In either event entering/exiting are called before and after, respectively, the function/block is executed. """ def __init__(self, **kwargs): self.options = kwargs super(override_settings, self).__init__() def enable(self): # Keep this code at the beginning to leave the settings unchanged # in case it raises an exception because INSTALLED_APPS is invalid. if 'INSTALLED_APPS' in self.options: try: apps.set_installed_apps(self.options['INSTALLED_APPS']) except Exception: apps.unset_installed_apps() raise override = UserSettingsHolder(settings._wrapped) for key, new_value in self.options.items(): setattr(override, key, new_value) self.wrapped = settings._wrapped settings._wrapped = override for key, new_value in self.options.items(): setting_changed.send(sender=settings._wrapped.__class__, setting=key, value=new_value, enter=True) def disable(self): if 'INSTALLED_APPS' in self.options: apps.unset_installed_apps() settings._wrapped = self.wrapped del self.wrapped for key in self.options: new_value = getattr(settings, key, None) setting_changed.send(sender=settings._wrapped.__class__, setting=key, value=new_value, enter=False) def save_options(self, test_func): if test_func._overridden_settings is None: test_func._overridden_settings = self.options else: # Duplicate dict to prevent subclasses from altering their parent. test_func._overridden_settings = dict( test_func._overridden_settings, **self.options) def decorate_class(self, cls): from django.test import SimpleTestCase if not issubclass(cls, SimpleTestCase): raise ValueError( "Only subclasses of Django SimpleTestCase can be decorated " "with override_settings") self.save_options(cls) return cls class modify_settings(override_settings): """ Like override_settings, but makes it possible to append, prepend or remove items instead of redefining the entire list. """ def __init__(self, *args, **kwargs): if args: # Hack used when instantiating from SimpleTestCase.setUpClass. assert not kwargs self.operations = args[0] else: assert not args self.operations = list(kwargs.items()) super(override_settings, self).__init__() def save_options(self, test_func): if test_func._modified_settings is None: test_func._modified_settings = self.operations else: # Duplicate list to prevent subclasses from altering their parent. test_func._modified_settings = list( test_func._modified_settings) + self.operations def enable(self): self.options = {} for name, operations in self.operations: try: # When called from SimpleTestCase.setUpClass, values may be # overridden several times; cumulate changes. value = self.options[name] except KeyError: value = list(getattr(settings, name, [])) for action, items in operations.items(): # items my be a single value or an iterable. if isinstance(items, six.string_types): items = [items] if action == 'append': value = value + [item for item in items if item not in value] elif action == 'prepend': value = [item for item in items if item not in value] + value elif action == 'remove': value = [item for item in value if item not in items] else: raise ValueError("Unsupported action: %s" % action) self.options[name] = value super(modify_settings, self).enable() class override_system_checks(TestContextDecorator): """ Acts as a decorator. Overrides list of registered system checks. Useful when you override `INSTALLED_APPS`, e.g. if you exclude `auth` app, you also need to exclude its system checks. """ def __init__(self, new_checks, deployment_checks=None): from django.core.checks.registry import registry self.registry = registry self.new_checks = new_checks self.deployment_checks = deployment_checks super(override_system_checks, self).__init__() def enable(self): self.old_checks = self.registry.registered_checks self.registry.registered_checks = self.new_checks self.old_deployment_checks = self.registry.deployment_checks if self.deployment_checks is not None: self.registry.deployment_checks = self.deployment_checks def disable(self): self.registry.registered_checks = self.old_checks self.registry.deployment_checks = self.old_deployment_checks def compare_xml(want, got): """Tries to do a 'xml-comparison' of want and got. Plain string comparison doesn't always work because, for example, attribute ordering should not be important. Comment nodes are not considered in the comparison. Leading and trailing whitespace is ignored on both chunks. Based on https://github.com/lxml/lxml/blob/master/src/lxml/doctestcompare.py """ _norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+') def norm_whitespace(v): return _norm_whitespace_re.sub(' ', v) def child_text(element): return ''.join(c.data for c in element.childNodes if c.nodeType == Node.TEXT_NODE) def children(element): return [c for c in element.childNodes if c.nodeType == Node.ELEMENT_NODE] def norm_child_text(element): return norm_whitespace(child_text(element)) def attrs_dict(element): return dict(element.attributes.items()) def check_element(want_element, got_element): if want_element.tagName != got_element.tagName: return False if norm_child_text(want_element) != norm_child_text(got_element): return False if attrs_dict(want_element) != attrs_dict(got_element): return False want_children = children(want_element) got_children = children(got_element) if len(want_children) != len(got_children): return False for want, got in zip(want_children, got_children): if not check_element(want, got): return False return True def first_node(document): for node in document.childNodes: if node.nodeType != Node.COMMENT_NODE: return node want, got = strip_quotes(want, got) want = want.strip().replace('\\n', '\n') got = got.strip().replace('\\n', '\n') # If the string is not a complete xml document, we may need to add a # root element. This allow us to compare fragments, like "<foo/><bar/>" if not want.startswith('<?xml'): wrapper = '<root>%s</root>' want = wrapper % want got = wrapper % got # Parse the want and got strings, and compare the parsings. want_root = first_node(parseString(want)) got_root = first_node(parseString(got)) return check_element(want_root, got_root) def strip_quotes(want, got): """ Strip quotes of doctests output values: >>> strip_quotes("'foo'") "foo" >>> strip_quotes('"foo"') "foo" """ def is_quoted_string(s): s = s.strip() return len(s) >= 2 and s[0] == s[-1] and s[0] in ('"', "'") def is_quoted_unicode(s): s = s.strip() return len(s) >= 3 and s[0] == 'u' and s[1] == s[-1] and s[1] in ('"', "'") if is_quoted_string(want) and is_quoted_string(got): want = want.strip()[1:-1] got = got.strip()[1:-1] elif is_quoted_unicode(want) and is_quoted_unicode(got): want = want.strip()[2:-1] got = got.strip()[2:-1] return want, got def str_prefix(s): return s % {'_': '' if six.PY3 else 'u'} class CaptureQueriesContext(object): """ Context manager that captures queries executed by the specified connection. """ def __init__(self, connection): self.connection = connection def __iter__(self): return iter(self.captured_queries) def __getitem__(self, index): return self.captured_queries[index] def __len__(self): return len(self.captured_queries) @property def captured_queries(self): return self.connection.queries[self.initial_queries:self.final_queries] def __enter__(self): self.force_debug_cursor = self.connection.force_debug_cursor self.connection.force_debug_cursor = True self.initial_queries = len(self.connection.queries_log) self.final_queries = None request_started.disconnect(reset_queries) return self def __exit__(self, exc_type, exc_value, traceback): self.connection.force_debug_cursor = self.force_debug_cursor request_started.connect(reset_queries) if exc_type is not None: return self.final_queries = len(self.connection.queries_log) class ignore_warnings(TestContextDecorator): def __init__(self, **kwargs): self.ignore_kwargs = kwargs if 'message' in self.ignore_kwargs or 'module' in self.ignore_kwargs: self.filter_func = warnings.filterwarnings else: self.filter_func = warnings.simplefilter super(ignore_warnings, self).__init__() def enable(self): self.catch_warnings = warnings.catch_warnings() self.catch_warnings.__enter__() self.filter_func('ignore', **self.ignore_kwargs) def disable(self): self.catch_warnings.__exit__(*sys.exc_info()) @contextmanager def patch_logger(logger_name, log_level, log_kwargs=False): """ Context manager that takes a named logger and the logging level and provides a simple mock-like list of messages received """ calls = [] def replacement(msg, *args, **kwargs): call = msg % args calls.append((call, kwargs) if log_kwargs else call) logger = logging.getLogger(logger_name) orig = getattr(logger, log_level) setattr(logger, log_level, replacement) try: yield calls finally: setattr(logger, log_level, orig) # On OSes that don't provide tzset (Windows), we can't set the timezone # in which the program runs. As a consequence, we must skip tests that # don't enforce a specific timezone (with timezone.override or equivalent), # or attempt to interpret naive datetimes in the default timezone. requires_tz_support = skipUnless( TZ_SUPPORT, "This test relies on the ability to run a program in an arbitrary " "time zone, but your operating system isn't able to do that." ) @contextmanager def extend_sys_path(*paths): """Context manager to temporarily add paths to sys.path.""" _orig_sys_path = sys.path[:] sys.path.extend(paths) try: yield finally: sys.path = _orig_sys_path @contextmanager def isolate_lru_cache(lru_cache_object): """Clear the cache of an LRU cache object on entering and exiting.""" lru_cache_object.cache_clear() try: yield finally: lru_cache_object.cache_clear() @contextmanager def captured_output(stream_name): """Return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO. Note: This function and the following ``captured_std*`` are copied from CPython's ``test.support`` module.""" orig_stdout = getattr(sys, stream_name) setattr(sys, stream_name, six.StringIO()) try: yield getattr(sys, stream_name) finally: setattr(sys, stream_name, orig_stdout) def captured_stdout(): """Capture the output of sys.stdout: with captured_stdout() as stdout: print("hello") self.assertEqual(stdout.getvalue(), "hello\n") """ return captured_output("stdout") def captured_stderr(): """Capture the output of sys.stderr: with captured_stderr() as stderr: print("hello", file=sys.stderr) self.assertEqual(stderr.getvalue(), "hello\n") """ return captured_output("stderr") def captured_stdin(): """Capture the input to sys.stdin: with captured_stdin() as stdin: stdin.write('hello\n') stdin.seek(0) # call test code that consumes from sys.stdin captured = input() self.assertEqual(captured, "hello") """ return captured_output("stdin") def reset_warning_registry(): """ Clear warning registry for all modules. This is required in some tests because of a bug in Python that prevents warnings.simplefilter("always") from always making warnings appear: http://bugs.python.org/issue4180 The bug was fixed in Python 3.4.2. """ key = "__warningregistry__" for mod in sys.modules.values(): if hasattr(mod, key): getattr(mod, key).clear() @contextmanager def freeze_time(t): """ Context manager to temporarily freeze time.time(). This temporarily modifies the time function of the time module. Modules which import the time function directly (e.g. `from time import time`) won't be affected This isn't meant as a public API, but helps reduce some repetitive code in Django's test suite. """ _real_time = time.time time.time = lambda: t try: yield finally: time.time = _real_time def require_jinja2(test_func): """ Decorator to enable a Jinja2 template engine in addition to the regular Django template engine for a test or skip it if Jinja2 isn't available. """ test_func = skipIf(jinja2 is None, "this test requires jinja2")(test_func) test_func = override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }, { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'APP_DIRS': True, 'OPTIONS': {'keep_trailing_newline': True}, }])(test_func) return test_func class override_script_prefix(TestContextDecorator): """ Decorator or context manager to temporary override the script prefix. """ def __init__(self, prefix): self.prefix = prefix super(override_script_prefix, self).__init__() def enable(self): self.old_prefix = get_script_prefix() set_script_prefix(self.prefix) def disable(self): set_script_prefix(self.old_prefix) class LoggingCaptureMixin(object): """ Capture the output from the 'django' logger and store it on the class's logger_output attribute. """ def setUp(self): self.logger = logging.getLogger('django') self.old_stream = self.logger.handlers[0].stream self.logger_output = six.StringIO() self.logger.handlers[0].stream = self.logger_output def tearDown(self): self.logger.handlers[0].stream = self.old_stream class isolate_apps(TestContextDecorator): """ Act as either a decorator or a context manager to register models defined in its wrapped context to an isolated registry. The list of installed apps the isolated registry should contain must be passed as arguments. Two optional keyword arguments can be specified: `attr_name`: attribute assigned the isolated registry if used as a class decorator. `kwarg_name`: keyword argument passing the isolated registry if used as a function decorator. """ def __init__(self, *installed_apps, **kwargs): self.installed_apps = installed_apps super(isolate_apps, self).__init__(**kwargs) def enable(self): self.old_apps = Options.default_apps apps = Apps(self.installed_apps) setattr(Options, 'default_apps', apps) return apps def disable(self): setattr(Options, 'default_apps', self.old_apps) def tag(*tags): """ Decorator to add tags to a test class or method. """ def decorator(obj): setattr(obj, 'tags', set(tags)) return obj return decorator
77292bee7eb83e7f51fe35a4b2d7df24f18178053de3fb3c8343667a058bb8b3
import os import threading import time import warnings from django.apps import apps from django.core.signals import setting_changed from django.db import connections, router from django.db.utils import ConnectionRouter from django.dispatch import Signal, receiver from django.utils import timezone from django.utils.functional import empty template_rendered = Signal(providing_args=["template", "context"]) # Most setting_changed receivers are supposed to be added below, # except for cases where the receiver is related to a contrib app. # Settings that may not work well when using 'override_settings' (#19031) COMPLEX_OVERRIDE_SETTINGS = {'DATABASES'} @receiver(setting_changed) def clear_cache_handlers(**kwargs): if kwargs['setting'] == 'CACHES': from django.core.cache import caches caches._caches = threading.local() @receiver(setting_changed) def update_installed_apps(**kwargs): if kwargs['setting'] == 'INSTALLED_APPS': # Rebuild any AppDirectoriesFinder instance. from django.contrib.staticfiles.finders import get_finder get_finder.cache_clear() # Rebuild management commands cache from django.core.management import get_commands get_commands.cache_clear() # Rebuild get_app_template_dirs cache. from django.template.utils import get_app_template_dirs get_app_template_dirs.cache_clear() # Rebuild translations cache. from django.utils.translation import trans_real trans_real._translations = {} @receiver(setting_changed) def update_connections_time_zone(**kwargs): if kwargs['setting'] == 'TIME_ZONE': # Reset process time zone if hasattr(time, 'tzset'): if kwargs['value']: os.environ['TZ'] = kwargs['value'] else: os.environ.pop('TZ', None) time.tzset() # Reset local time zone cache timezone.get_default_timezone.cache_clear() # Reset the database connections' time zone if kwargs['setting'] in {'TIME_ZONE', 'USE_TZ'}: for conn in connections.all(): try: del conn.timezone except AttributeError: pass try: del conn.timezone_name except AttributeError: pass conn.ensure_timezone() @receiver(setting_changed) def clear_routers_cache(**kwargs): if kwargs['setting'] == 'DATABASE_ROUTERS': router.routers = ConnectionRouter().routers @receiver(setting_changed) def reset_template_engines(**kwargs): if kwargs['setting'] in { 'TEMPLATES', 'DEBUG', 'FILE_CHARSET', 'INSTALLED_APPS', }: from django.template import engines try: del engines.templates except AttributeError: pass engines._templates = None engines._engines = {} from django.template.engine import Engine Engine.get_default.cache_clear() @receiver(setting_changed) def clear_serializers_cache(**kwargs): if kwargs['setting'] == 'SERIALIZATION_MODULES': from django.core import serializers serializers._serializers = {} @receiver(setting_changed) def language_changed(**kwargs): if kwargs['setting'] in {'LANGUAGES', 'LANGUAGE_CODE', 'LOCALE_PATHS'}: from django.utils.translation import trans_real trans_real._default = None trans_real._active = threading.local() if kwargs['setting'] in {'LANGUAGES', 'LOCALE_PATHS'}: from django.utils.translation import trans_real trans_real._translations = {} trans_real.check_for_language.cache_clear() @receiver(setting_changed) def file_storage_changed(**kwargs): if kwargs['setting'] == 'DEFAULT_FILE_STORAGE': from django.core.files.storage import default_storage default_storage._wrapped = empty @receiver(setting_changed) def complex_setting_changed(**kwargs): if kwargs['enter'] and kwargs['setting'] in COMPLEX_OVERRIDE_SETTINGS: # Considering the current implementation of the signals framework, # stacklevel=5 shows the line containing the override_settings call. warnings.warn("Overriding setting %s can lead to unexpected behavior." % kwargs['setting'], stacklevel=5) @receiver(setting_changed) def root_urlconf_changed(**kwargs): if kwargs['setting'] == 'ROOT_URLCONF': from django.urls import clear_url_caches, set_urlconf clear_url_caches() set_urlconf(None) @receiver(setting_changed) def static_storage_changed(**kwargs): if kwargs['setting'] in { 'STATICFILES_STORAGE', 'STATIC_ROOT', 'STATIC_URL', }: from django.contrib.staticfiles.storage import staticfiles_storage staticfiles_storage._wrapped = empty @receiver(setting_changed) def static_finders_changed(**kwargs): if kwargs['setting'] in { 'STATICFILES_DIRS', 'STATIC_ROOT', }: from django.contrib.staticfiles.finders import get_finder get_finder.cache_clear() @receiver(setting_changed) def auth_password_validators_changed(**kwargs): if kwargs['setting'] == 'AUTH_PASSWORD_VALIDATORS': from django.contrib.auth.password_validation import get_default_password_validators get_default_password_validators.cache_clear() @receiver(setting_changed) def user_model_swapped(**kwargs): if kwargs['setting'] == 'AUTH_USER_MODEL': apps.clear_cache()
0ab270e6b62382efd3023fb8a8986d4ce9d995163c686bff36b5b83227ab6c3a
import sys import threading import warnings from collections import Counter, OrderedDict, defaultdict from functools import partial from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured from django.utils import lru_cache from .config import AppConfig class Apps(object): """ A registry that stores the configuration of installed applications. It also keeps track of models eg. to provide reverse-relations. """ def __init__(self, installed_apps=()): # installed_apps is set to None when creating the master registry # because it cannot be populated at that point. Other registries must # provide a list of installed apps and are populated immediately. if installed_apps is None and hasattr(sys.modules[__name__], 'apps'): raise RuntimeError("You must supply an installed_apps argument.") # Mapping of app labels => model names => model classes. Every time a # model is imported, ModelBase.__new__ calls apps.register_model which # creates an entry in all_models. All imported models are registered, # regardless of whether they're defined in an installed application # and whether the registry has been populated. Since it isn't possible # to reimport a module safely (it could reexecute initialization code) # all_models is never overridden or reset. self.all_models = defaultdict(OrderedDict) # Mapping of labels to AppConfig instances for installed apps. self.app_configs = OrderedDict() # Stack of app_configs. Used to store the current state in # set_available_apps and set_installed_apps. self.stored_app_configs = [] # Whether the registry is populated. self.apps_ready = self.models_ready = self.ready = False # Lock for thread-safe population. self._lock = threading.Lock() # Maps ("app_label", "modelname") tuples to lists of functions to be # called when the corresponding model is ready. Used by this class's # `lazy_model_operation()` and `do_pending_operations()` methods. self._pending_operations = defaultdict(list) # Populate apps and models, unless it's the master registry. if installed_apps is not None: self.populate(installed_apps) def populate(self, installed_apps=None): """ Loads application configurations and models. This method imports each application module and then each model module. It is thread safe and idempotent, but not reentrant. """ if self.ready: return # populate() might be called by two threads in parallel on servers # that create threads before initializing the WSGI callable. with self._lock: if self.ready: return # app_config should be pristine, otherwise the code below won't # guarantee that the order matches the order in INSTALLED_APPS. if self.app_configs: raise RuntimeError("populate() isn't reentrant") # Phase 1: initialize app configs and import app modules. for entry in installed_apps: if isinstance(entry, AppConfig): app_config = entry else: app_config = AppConfig.create(entry) if app_config.label in self.app_configs: raise ImproperlyConfigured( "Application labels aren't unique, " "duplicates: %s" % app_config.label) self.app_configs[app_config.label] = app_config app_config.apps = self # Check for duplicate app names. counts = Counter( app_config.name for app_config in self.app_configs.values()) duplicates = [ name for name, count in counts.most_common() if count > 1] if duplicates: raise ImproperlyConfigured( "Application names aren't unique, " "duplicates: %s" % ", ".join(duplicates)) self.apps_ready = True # Phase 2: import models modules. for app_config in self.app_configs.values(): app_config.import_models() self.clear_cache() self.models_ready = True # Phase 3: run ready() methods of app configs. for app_config in self.get_app_configs(): app_config.ready() self.ready = True def check_apps_ready(self): """ Raises an exception if all apps haven't been imported yet. """ if not self.apps_ready: raise AppRegistryNotReady("Apps aren't loaded yet.") def check_models_ready(self): """ Raises an exception if all models haven't been imported yet. """ if not self.models_ready: raise AppRegistryNotReady("Models aren't loaded yet.") def get_app_configs(self): """ Imports applications and returns an iterable of app configs. """ self.check_apps_ready() return self.app_configs.values() def get_app_config(self, app_label): """ Imports applications and returns an app config for the given label. Raises LookupError if no application exists with this label. """ self.check_apps_ready() try: return self.app_configs[app_label] except KeyError: message = "No installed app with label '%s'." % app_label for app_config in self.get_app_configs(): if app_config.name == app_label: message += " Did you mean '%s'?" % app_config.label break raise LookupError(message) # This method is performance-critical at least for Django's test suite. @lru_cache.lru_cache(maxsize=None) def get_models(self, include_auto_created=False, include_swapped=False): """ Returns a list of all installed models. By default, the following models aren't included: - auto-created models for many-to-many relations without an explicit intermediate table, - models created to satisfy deferred attribute queries, - models that have been swapped out. Set the corresponding keyword argument to True to include such models. """ self.check_models_ready() result = [] for app_config in self.app_configs.values(): result.extend(list(app_config.get_models(include_auto_created, include_swapped))) return result def get_model(self, app_label, model_name=None, require_ready=True): """ Returns the model matching the given app_label and model_name. As a shortcut, this function also accepts a single argument in the form <app_label>.<model_name>. model_name is case-insensitive. Raises LookupError if no application exists with this label, or no model exists with this name in the application. Raises ValueError if called with a single argument that doesn't contain exactly one dot. """ if require_ready: self.check_models_ready() else: self.check_apps_ready() if model_name is None: app_label, model_name = app_label.split('.') app_config = self.get_app_config(app_label) if not require_ready and app_config.models is None: app_config.import_models() return app_config.get_model(model_name, require_ready=require_ready) def register_model(self, app_label, model): # Since this method is called when models are imported, it cannot # perform imports because of the risk of import loops. It mustn't # call get_app_config(). model_name = model._meta.model_name app_models = self.all_models[app_label] if model_name in app_models: if (model.__name__ == app_models[model_name].__name__ and model.__module__ == app_models[model_name].__module__): warnings.warn( "Model '%s.%s' was already registered. " "Reloading models is not advised as it can lead to inconsistencies, " "most notably with related models." % (app_label, model_name), RuntimeWarning, stacklevel=2) else: raise RuntimeError( "Conflicting '%s' models in application '%s': %s and %s." % (model_name, app_label, app_models[model_name], model)) app_models[model_name] = model self.do_pending_operations(model) self.clear_cache() def is_installed(self, app_name): """ Checks whether an application with this name exists in the registry. app_name is the full name of the app eg. 'django.contrib.admin'. """ self.check_apps_ready() return any(ac.name == app_name for ac in self.app_configs.values()) def get_containing_app_config(self, object_name): """ Look for an app config containing a given object. object_name is the dotted Python path to the object. Returns the app config for the inner application in case of nesting. Returns None if the object isn't in any registered app config. """ self.check_apps_ready() candidates = [] for app_config in self.app_configs.values(): if object_name.startswith(app_config.name): subpath = object_name[len(app_config.name):] if subpath == '' or subpath[0] == '.': candidates.append(app_config) if candidates: return sorted(candidates, key=lambda ac: -len(ac.name))[0] def get_registered_model(self, app_label, model_name): """ Similar to get_model(), but doesn't require that an app exists with the given app_label. It's safe to call this method at import time, even while the registry is being populated. """ model = self.all_models[app_label].get(model_name.lower()) if model is None: raise LookupError( "Model '%s.%s' not registered." % (app_label, model_name)) return model @lru_cache.lru_cache(maxsize=None) def get_swappable_settings_name(self, to_string): """ For a given model string (e.g. "auth.User"), return the name of the corresponding settings name if it refers to a swappable model. If the referred model is not swappable, return None. This method is decorated with lru_cache because it's performance critical when it comes to migrations. Since the swappable settings don't change after Django has loaded the settings, there is no reason to get the respective settings attribute over and over again. """ for model in self.get_models(include_swapped=True): swapped = model._meta.swapped # Is this model swapped out for the model given by to_string? if swapped and swapped == to_string: return model._meta.swappable # Is this model swappable and the one given by to_string? if model._meta.swappable and model._meta.label == to_string: return model._meta.swappable return None def set_available_apps(self, available): """ Restricts the set of installed apps used by get_app_config[s]. available must be an iterable of application names. set_available_apps() must be balanced with unset_available_apps(). Primarily used for performance optimization in TransactionTestCase. This method is safe is the sense that it doesn't trigger any imports. """ available = set(available) installed = set(app_config.name for app_config in self.get_app_configs()) if not available.issubset(installed): raise ValueError( "Available apps isn't a subset of installed apps, extra apps: %s" % ", ".join(available - installed) ) self.stored_app_configs.append(self.app_configs) self.app_configs = OrderedDict( (label, app_config) for label, app_config in self.app_configs.items() if app_config.name in available) self.clear_cache() def unset_available_apps(self): """ Cancels a previous call to set_available_apps(). """ self.app_configs = self.stored_app_configs.pop() self.clear_cache() def set_installed_apps(self, installed): """ Enables a different set of installed apps for get_app_config[s]. installed must be an iterable in the same format as INSTALLED_APPS. set_installed_apps() must be balanced with unset_installed_apps(), even if it exits with an exception. Primarily used as a receiver of the setting_changed signal in tests. This method may trigger new imports, which may add new models to the registry of all imported models. They will stay in the registry even after unset_installed_apps(). Since it isn't possible to replay imports safely (eg. that could lead to registering listeners twice), models are registered when they're imported and never removed. """ if not self.ready: raise AppRegistryNotReady("App registry isn't ready yet.") self.stored_app_configs.append(self.app_configs) self.app_configs = OrderedDict() self.apps_ready = self.models_ready = self.ready = False self.clear_cache() self.populate(installed) def unset_installed_apps(self): """ Cancels a previous call to set_installed_apps(). """ self.app_configs = self.stored_app_configs.pop() self.apps_ready = self.models_ready = self.ready = True self.clear_cache() def clear_cache(self): """ Clears all internal caches, for methods that alter the app registry. This is mostly used in tests. """ # Call expire cache on each model. This will purge # the relation tree and the fields cache. self.get_models.cache_clear() if self.ready: # Circumvent self.get_models() to prevent that the cache is refilled. # This particularly prevents that an empty value is cached while cloning. for app_config in self.app_configs.values(): for model in app_config.get_models(include_auto_created=True): model._meta._expire_cache() def lazy_model_operation(self, function, *model_keys): """ Take a function and a number of ("app_label", "modelname") tuples, and when all the corresponding models have been imported and registered, call the function with the model classes as its arguments. The function passed to this method must accept exactly n models as arguments, where n=len(model_keys). """ # Base case: no arguments, just execute the function. if not model_keys: function() # Recursive case: take the head of model_keys, wait for the # corresponding model class to be imported and registered, then apply # that argument to the supplied function. Pass the resulting partial # to lazy_model_operation() along with the remaining model args and # repeat until all models are loaded and all arguments are applied. else: next_model, more_models = model_keys[0], model_keys[1:] # This will be executed after the class corresponding to next_model # has been imported and registered. The `func` attribute provides # duck-type compatibility with partials. def apply_next_model(model): next_function = partial(apply_next_model.func, model) self.lazy_model_operation(next_function, *more_models) apply_next_model.func = function # If the model has already been imported and registered, partially # apply it to the function now. If not, add it to the list of # pending operations for the model, where it will be executed with # the model class as its sole argument once the model is ready. try: model_class = self.get_registered_model(*next_model) except LookupError: self._pending_operations[next_model].append(apply_next_model) else: apply_next_model(model_class) def do_pending_operations(self, model): """ Take a newly-prepared model and pass it to each function waiting for it. This is called at the very end of `Apps.register_model()`. """ key = model._meta.app_label, model._meta.model_name for function in self._pending_operations.pop(key, []): function(model) apps = Apps(installed_apps=None)
371888386d7e53d0b9b7c22f37bb4bce0783bfc59972415d491b7bdfdd6cdea6
import os from importlib import import_module from django.core.exceptions import ImproperlyConfigured from django.utils._os import upath from django.utils.module_loading import module_has_submodule MODELS_MODULE_NAME = 'models' class AppConfig(object): """ Class representing a Django application and its configuration. """ def __init__(self, app_name, app_module): # Full Python path to the application eg. 'django.contrib.admin'. self.name = app_name # Root module for the application eg. <module 'django.contrib.admin' # from 'django/contrib/admin/__init__.pyc'>. self.module = app_module # Reference to the Apps registry that holds this AppConfig. Set by the # registry when it registers the AppConfig instance. self.apps = None # The following attributes could be defined at the class level in a # subclass, hence the test-and-set pattern. # Last component of the Python path to the application eg. 'admin'. # This value must be unique across a Django project. if not hasattr(self, 'label'): self.label = app_name.rpartition(".")[2] # Human-readable name for the application eg. "Admin". if not hasattr(self, 'verbose_name'): self.verbose_name = self.label.title() # Filesystem path to the application directory eg. # u'/usr/lib/python2.7/dist-packages/django/contrib/admin'. Unicode on # Python 2 and a str on Python 3. if not hasattr(self, 'path'): self.path = self._path_from_module(app_module) # Module containing models eg. <module 'django.contrib.admin.models' # from 'django/contrib/admin/models.pyc'>. Set by import_models(). # None if the application doesn't have a models module. self.models_module = None # Mapping of lower case model names to model classes. Initially set to # None to prevent accidental access before import_models() runs. self.models = None def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self.label) def _path_from_module(self, module): """Attempt to determine app's filesystem path from its module.""" # See #21874 for extended discussion of the behavior of this method in # various cases. # Convert paths to list because Python 3's _NamespacePath does not # support indexing. paths = list(getattr(module, '__path__', [])) if len(paths) != 1: filename = getattr(module, '__file__', None) if filename is not None: paths = [os.path.dirname(filename)] else: # For unknown reasons, sometimes the list returned by __path__ # contains duplicates that must be removed (#25246). paths = list(set(paths)) if len(paths) > 1: raise ImproperlyConfigured( "The app module %r has multiple filesystem locations (%r); " "you must configure this app with an AppConfig subclass " "with a 'path' class attribute." % (module, paths)) elif not paths: raise ImproperlyConfigured( "The app module %r has no filesystem location, " "you must configure this app with an AppConfig subclass " "with a 'path' class attribute." % (module,)) return upath(paths[0]) @classmethod def create(cls, entry): """ Factory that creates an app config from an entry in INSTALLED_APPS. """ try: # If import_module succeeds, entry is a path to an app module, # which may specify an app config class with default_app_config. # Otherwise, entry is a path to an app config class or an error. module = import_module(entry) except ImportError: # Track that importing as an app module failed. If importing as an # app config class fails too, we'll trigger the ImportError again. module = None mod_path, _, cls_name = entry.rpartition('.') # Raise the original exception when entry cannot be a path to an # app config class. if not mod_path: raise else: try: # If this works, the app module specifies an app config class. entry = module.default_app_config except AttributeError: # Otherwise, it simply uses the default app config class. return cls(entry, module) else: mod_path, _, cls_name = entry.rpartition('.') # If we're reaching this point, we must attempt to load the app config # class located at <mod_path>.<cls_name> mod = import_module(mod_path) try: cls = getattr(mod, cls_name) except AttributeError: if module is None: # If importing as an app module failed, that error probably # contains the most informative traceback. Trigger it again. import_module(entry) else: raise # Check for obvious errors. (This check prevents duck typing, but # it could be removed if it became a problem in practice.) if not issubclass(cls, AppConfig): raise ImproperlyConfigured( "'%s' isn't a subclass of AppConfig." % entry) # Obtain app name here rather than in AppClass.__init__ to keep # all error checking for entries in INSTALLED_APPS in one place. try: app_name = cls.name except AttributeError: raise ImproperlyConfigured( "'%s' must supply a name attribute." % entry) # Ensure app_name points to a valid module. try: app_module = import_module(app_name) except ImportError: raise ImproperlyConfigured( "Cannot import '%s'. Check that '%s.%s.name' is correct." % ( app_name, mod_path, cls_name, ) ) # Entry is a path to an app config class. return cls(app_name, app_module) def get_model(self, model_name, require_ready=True): """ Returns the model with the given case-insensitive model_name. Raises LookupError if no model exists with this name. """ if require_ready: self.apps.check_models_ready() else: self.apps.check_apps_ready() try: return self.models[model_name.lower()] except KeyError: raise LookupError( "App '%s' doesn't have a '%s' model." % (self.label, model_name)) def get_models(self, include_auto_created=False, include_swapped=False): """ Returns an iterable of models. By default, the following models aren't included: - auto-created models for many-to-many relations without an explicit intermediate table, - models created to satisfy deferred attribute queries, - models that have been swapped out. Set the corresponding keyword argument to True to include such models. Keyword arguments aren't documented; they're a private API. """ self.apps.check_models_ready() for model in self.models.values(): if model._meta.auto_created and not include_auto_created: continue if model._meta.swapped and not include_swapped: continue yield model def import_models(self): # Dictionary of models for this app, primarily maintained in the # 'all_models' attribute of the Apps this AppConfig is attached to. self.models = self.apps.all_models[self.label] if module_has_submodule(self.module, MODELS_MODULE_NAME): models_module_name = '%s.%s' % (self.name, MODELS_MODULE_NAME) self.models_module = import_module(models_module_name) def ready(self): """ Override this method in subclasses to run code when Django starts. """
3e9311380b9a3d63e71dcd31e648360df1f9b74714cb8a4fbf3db3ffff15ee0c
""" Views and functions for serving static files. These are only to be used during development, and SHOULD NOT be used in a production setting. """ from __future__ import unicode_literals import mimetypes import os import posixpath import re import stat from django.http import ( FileResponse, Http404, HttpResponse, HttpResponseNotModified, HttpResponseRedirect, ) from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils.http import http_date, parse_http_date from django.utils.six.moves.urllib.parse import unquote from django.utils.translation import ugettext as _, ugettext_lazy def serve(request, path, document_root=None, show_indexes=False): """ Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: from django.views.static import serve url(r'^(?P<path>.*)$', serve, {'document_root': '/path/to/my/files/'}) in your URLconf. You must provide the ``document_root`` param. You may also set ``show_indexes`` to ``True`` if you'd like to serve a basic index of the directory. This index view will use the template hardcoded below, but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(unquote(path)) path = path.lstrip('/') newpath = '' for part in path.split('/'): if not part: # Strip empty path components. continue drive, part = os.path.splitdrive(part) head, part = os.path.split(part) if part in (os.curdir, os.pardir): # Strip '.' and '..' in path. continue newpath = os.path.join(newpath, part).replace('\\', '/') if newpath and path != newpath: return HttpResponseRedirect(newpath) fullpath = os.path.join(document_root, newpath) if os.path.isdir(fullpath): if show_indexes: return directory_index(newpath, fullpath) raise Http404(_("Directory indexes are not allowed here.")) if not os.path.exists(fullpath): raise Http404(_('"%(path)s" does not exist') % {'path': fullpath}) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj.st_mtime, statobj.st_size): return HttpResponseNotModified() content_type, encoding = mimetypes.guess_type(fullpath) content_type = content_type or 'application/octet-stream' response = FileResponse(open(fullpath, 'rb'), content_type=content_type) response["Last-Modified"] = http_date(statobj.st_mtime) if stat.S_ISREG(statobj.st_mode): response["Content-Length"] = statobj.st_size if encoding: response["Content-Encoding"] = encoding return response DEFAULT_DIRECTORY_INDEX_TEMPLATE = """ {% load i18n %} <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Language" content="en-us" /> <meta name="robots" content="NONE,NOARCHIVE" /> <title>{% blocktrans %}Index of {{ directory }}{% endblocktrans %}</title> </head> <body> <h1>{% blocktrans %}Index of {{ directory }}{% endblocktrans %}</h1> <ul> {% if directory != "/" %} <li><a href="../">../</a></li> {% endif %} {% for f in file_list %} <li><a href="{{ f|urlencode }}">{{ f }}</a></li> {% endfor %} </ul> </body> </html> """ template_translatable = ugettext_lazy("Index of %(directory)s") def directory_index(path, fullpath): try: t = loader.select_template([ 'static/directory_index.html', 'static/directory_index', ]) except TemplateDoesNotExist: t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE) files = [] for f in os.listdir(fullpath): if not f.startswith('.'): if os.path.isdir(os.path.join(fullpath, f)): f += '/' files.append(f) c = Context({ 'directory': path + '/', 'file_list': files, }) return HttpResponse(t.render(c)) def was_modified_since(header=None, mtime=0, size=0): """ Was something modified since the user last downloaded it? header This is the value of the If-Modified-Since header. If this is None, I'll just return True. mtime This is the modification time of the item we're talking about. size This is the size of the item we're talking about. """ try: if header is None: raise ValueError matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header, re.IGNORECASE) header_mtime = parse_http_date(matches.group(1)) header_len = matches.group(3) if header_len and int(header_len) != size: raise ValueError if int(mtime) > header_mtime: raise ValueError except (AttributeError, ValueError, OverflowError): return True return False
9bcfa516dbf669bd8ac517d62b1ed282b88010fa964be2bf68394e53067a3640
import importlib import itertools import json import os import warnings from django import http from django.apps import apps from django.conf import settings from django.template import Context, Engine from django.urls import translate_url from django.utils import six from django.utils._os import upath from django.utils.deprecation import RemovedInDjango20Warning from django.utils.encoding import force_text from django.utils.formats import get_format from django.utils.http import is_safe_url, urlunquote from django.utils.translation import ( LANGUAGE_SESSION_KEY, check_for_language, get_language, to_locale, ) from django.utils.translation.trans_real import DjangoTranslation from django.views.generic import View DEFAULT_PACKAGES = ['django.conf'] LANGUAGE_QUERY_PARAMETER = 'language' def set_language(request): """ Redirect to a given url while setting the chosen language in the session or cookie. The url and the language code need to be specified in the request parameters. Since this view changes how the user will see the rest of the site, it must only be accessed as a POST request. If called as a GET request, it will redirect to the page in the request (the 'next' parameter) without changing any state. """ next = request.POST.get('next', request.GET.get('next')) if ((next or not request.is_ajax()) and not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure())): next = request.META.get('HTTP_REFERER') if next: next = urlunquote(next) # HTTP_REFERER may be encoded. if not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure()): next = '/' response = http.HttpResponseRedirect(next) if next else http.HttpResponse(status=204) if request.method == 'POST': lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER) if lang_code and check_for_language(lang_code): if next: next_trans = translate_url(next, lang_code) if next_trans != next: response = http.HttpResponseRedirect(next_trans) if hasattr(request, 'session'): request.session[LANGUAGE_SESSION_KEY] = lang_code else: response.set_cookie( settings.LANGUAGE_COOKIE_NAME, lang_code, max_age=settings.LANGUAGE_COOKIE_AGE, path=settings.LANGUAGE_COOKIE_PATH, domain=settings.LANGUAGE_COOKIE_DOMAIN, ) return response def get_formats(): """ Returns all formats strings required for i18n to work """ FORMAT_SETTINGS = ( 'DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT', 'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT', 'SHORT_DATE_FORMAT', 'SHORT_DATETIME_FORMAT', 'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR', 'THOUSAND_SEPARATOR', 'NUMBER_GROUPING', 'DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS', 'DATETIME_INPUT_FORMATS' ) result = {} for attr in FORMAT_SETTINGS: result[attr] = get_format(attr) formats = {} for k, v in result.items(): if isinstance(v, (six.string_types, int)): formats[k] = force_text(v) elif isinstance(v, (tuple, list)): formats[k] = [force_text(value) for value in v] return formats js_catalog_template = r""" {% autoescape off %} (function(globals) { var django = globals.django || (globals.django = {}); {% if plural %} django.pluralidx = function(n) { var v={{ plural }}; if (typeof(v) == 'boolean') { return v ? 1 : 0; } else { return v; } }; {% else %} django.pluralidx = function(count) { return (count == 1) ? 0 : 1; }; {% endif %} /* gettext library */ django.catalog = django.catalog || {}; {% if catalog_str %} var newcatalog = {{ catalog_str }}; for (var key in newcatalog) { django.catalog[key] = newcatalog[key]; } {% endif %} if (!django.jsi18n_initialized) { django.gettext = function(msgid) { var value = django.catalog[msgid]; if (typeof(value) == 'undefined') { return msgid; } else { return (typeof(value) == 'string') ? value : value[0]; } }; django.ngettext = function(singular, plural, count) { var value = django.catalog[singular]; if (typeof(value) == 'undefined') { return (count == 1) ? singular : plural; } else { return value[django.pluralidx(count)]; } }; django.gettext_noop = function(msgid) { return msgid; }; django.pgettext = function(context, msgid) { var value = django.gettext(context + '\x04' + msgid); if (value.indexOf('\x04') != -1) { value = msgid; } return value; }; django.npgettext = function(context, singular, plural, count) { var value = django.ngettext(context + '\x04' + singular, context + '\x04' + plural, count); if (value.indexOf('\x04') != -1) { value = django.ngettext(singular, plural, count); } return value; }; django.interpolate = function(fmt, obj, named) { if (named) { return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])}); } else { return fmt.replace(/%s/g, function(match){return String(obj.shift())}); } }; /* formatting library */ django.formats = {{ formats_str }}; django.get_format = function(format_type) { var value = django.formats[format_type]; if (typeof(value) == 'undefined') { return format_type; } else { return value; } }; /* add to global namespace */ globals.pluralidx = django.pluralidx; globals.gettext = django.gettext; globals.ngettext = django.ngettext; globals.gettext_noop = django.gettext_noop; globals.pgettext = django.pgettext; globals.npgettext = django.npgettext; globals.interpolate = django.interpolate; globals.get_format = django.get_format; django.jsi18n_initialized = true; } }(this)); {% endautoescape %} """ def render_javascript_catalog(catalog=None, plural=None): template = Engine().from_string(js_catalog_template) def indent(s): return s.replace('\n', '\n ') context = Context({ 'catalog_str': indent(json.dumps( catalog, sort_keys=True, indent=2)) if catalog else None, 'formats_str': indent(json.dumps( get_formats(), sort_keys=True, indent=2)), 'plural': plural, }) return http.HttpResponse(template.render(context), 'text/javascript') def get_javascript_catalog(locale, domain, packages): app_configs = apps.get_app_configs() allowable_packages = set(app_config.name for app_config in app_configs) allowable_packages.update(DEFAULT_PACKAGES) packages = [p for p in packages if p in allowable_packages] paths = [] # paths of requested packages for package in packages: p = importlib.import_module(package) path = os.path.join(os.path.dirname(upath(p.__file__)), 'locale') paths.append(path) trans = DjangoTranslation(locale, domain=domain, localedirs=paths) trans_cat = trans._catalog plural = None if '' in trans_cat: for line in trans_cat[''].split('\n'): if line.startswith('Plural-Forms:'): plural = line.split(':', 1)[1].strip() if plural is not None: # this should actually be a compiled function of a typical plural-form: # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : # n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2; plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=', 1)[1] pdict = {} maxcnts = {} catalog = {} trans_fallback_cat = trans._fallback._catalog if trans._fallback else {} for key, value in itertools.chain(six.iteritems(trans_cat), six.iteritems(trans_fallback_cat)): if key == '' or key in catalog: continue if isinstance(key, six.string_types): catalog[key] = value elif isinstance(key, tuple): msgid = key[0] cnt = key[1] maxcnts[msgid] = max(cnt, maxcnts.get(msgid, 0)) pdict.setdefault(msgid, {})[cnt] = value else: raise TypeError(key) for k, v in pdict.items(): catalog[k] = [v.get(i, '') for i in range(maxcnts[msgid] + 1)] return catalog, plural def _get_locale(request): language = request.GET.get(LANGUAGE_QUERY_PARAMETER) if not (language and check_for_language(language)): language = get_language() return to_locale(language) def _parse_packages(packages): if packages is None: packages = list(DEFAULT_PACKAGES) elif isinstance(packages, six.string_types): packages = packages.split('+') return packages def null_javascript_catalog(request, domain=None, packages=None): """ Returns "identity" versions of the JavaScript i18n functions -- i.e., versions that don't actually do anything. """ return render_javascript_catalog() def javascript_catalog(request, domain='djangojs', packages=None): """ Returns the selected language catalog as a javascript library. Receives the list of packages to check for translations in the packages parameter either from an infodict or as a +-delimited string from the request. Default is 'django.conf'. Additionally you can override the gettext domain for this view, but usually you don't want to do that, as JavaScript messages go to the djangojs domain. But this might be needed if you deliver your JavaScript source from Django templates. """ warnings.warn( "The javascript_catalog() view is deprecated in favor of the " "JavaScriptCatalog view.", RemovedInDjango20Warning, stacklevel=2 ) locale = _get_locale(request) packages = _parse_packages(packages) catalog, plural = get_javascript_catalog(locale, domain, packages) return render_javascript_catalog(catalog, plural) def json_catalog(request, domain='djangojs', packages=None): """ Return the selected language catalog as a JSON object. Receives the same parameters as javascript_catalog(), but returns a response with a JSON object of the following format: { "catalog": { # Translations catalog }, "formats": { # Language formats for date, time, etc. }, "plural": '...' # Expression for plural forms, or null. } """ warnings.warn( "The json_catalog() view is deprecated in favor of the " "JSONCatalog view.", RemovedInDjango20Warning, stacklevel=2 ) locale = _get_locale(request) packages = _parse_packages(packages) catalog, plural = get_javascript_catalog(locale, domain, packages) data = { 'catalog': catalog, 'formats': get_formats(), 'plural': plural, } return http.JsonResponse(data) class JavaScriptCatalog(View): """ Return the selected language catalog as a JavaScript library. Receives the list of packages to check for translations in the `packages` kwarg either from the extra dictionary passed to the url() function or as a plus-sign delimited string from the request. Default is 'django.conf'. You can override the gettext domain for this view, but usually you don't want to do that as JavaScript messages go to the djangojs domain. This might be needed if you deliver your JavaScript source from Django templates. """ domain = 'djangojs' packages = None def get(self, request, *args, **kwargs): locale = get_language() domain = kwargs.get('domain', self.domain) # If packages are not provided, default to all installed packages, as # DjangoTranslation without localedirs harvests them all. packages = kwargs.get('packages', '') packages = packages.split('+') if packages else self.packages paths = self.get_paths(packages) if packages else None self.translation = DjangoTranslation(locale, domain=domain, localedirs=paths) context = self.get_context_data(**kwargs) return self.render_to_response(context) def get_paths(self, packages): allowable_packages = dict((app_config.name, app_config) for app_config in apps.get_app_configs()) app_configs = [allowable_packages[p] for p in packages if p in allowable_packages] # paths of requested packages return [os.path.join(app.path, 'locale') for app in app_configs] def get_plural(self): plural = None if '' in self.translation._catalog: for line in self.translation._catalog[''].split('\n'): if line.startswith('Plural-Forms:'): plural = line.split(':', 1)[1].strip() if plural is not None: # This should be a compiled function of a typical plural-form: # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : # n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2; plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=', 1)[1] return plural def get_catalog(self): pdict = {} maxcnts = {} catalog = {} trans_cat = self.translation._catalog trans_fallback_cat = self.translation._fallback._catalog if self.translation._fallback else {} for key, value in itertools.chain(six.iteritems(trans_cat), six.iteritems(trans_fallback_cat)): if key == '' or key in catalog: continue if isinstance(key, six.string_types): catalog[key] = value elif isinstance(key, tuple): msgid = key[0] cnt = key[1] maxcnts[msgid] = max(cnt, maxcnts.get(msgid, 0)) pdict.setdefault(msgid, {})[cnt] = value else: raise TypeError(key) for k, v in pdict.items(): catalog[k] = [v.get(i, '') for i in range(maxcnts[msgid] + 1)] return catalog def get_context_data(self, **kwargs): return { 'catalog': self.get_catalog(), 'formats': get_formats(), 'plural': self.get_plural(), } def render_to_response(self, context, **response_kwargs): def indent(s): return s.replace('\n', '\n ') template = Engine().from_string(js_catalog_template) context['catalog_str'] = indent( json.dumps(context['catalog'], sort_keys=True, indent=2) ) if context['catalog'] else None context['formats_str'] = indent(json.dumps(context['formats'], sort_keys=True, indent=2)) return http.HttpResponse(template.render(Context(context)), 'text/javascript') class JSONCatalog(JavaScriptCatalog): """ Return the selected language catalog as a JSON object. Receives the same parameters as JavaScriptCatalog and returns a response with a JSON object of the following format: { "catalog": { # Translations catalog }, "formats": { # Language formats for date, time, etc. }, "plural": '...' # Expression for plural forms, or null. } """ def render_to_response(self, context, **response_kwargs): return http.JsonResponse(context)
bb5e75b158cda9f69cef75b6c88a4e2e5aba7510964e7384ac5dbc2e27454b0d
from django import http from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils import six from django.utils.encoding import force_text from django.views.decorators.csrf import requires_csrf_token ERROR_404_TEMPLATE_NAME = '404.html' ERROR_403_TEMPLATE_NAME = '403.html' ERROR_400_TEMPLATE_NAME = '400.html' ERROR_500_TEMPLATE_NAME = '500.html' # This can be called when CsrfViewMiddleware.process_view has not run, # therefore need @requires_csrf_token in case the template needs # {% csrf_token %}. @requires_csrf_token def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): """ Default 404 handler. Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') exception The message from the exception which triggered the 404 (if one was supplied), or the exception class name """ exception_repr = exception.__class__.__name__ # Try to get an "interesting" exception message, if any (and not the ugly # Resolver404 dictionary) try: message = exception.args[0] except (AttributeError, IndexError): pass else: if isinstance(message, six.text_type): exception_repr = message context = { 'request_path': request.path, 'exception': exception_repr, } try: template = loader.get_template(template_name) body = template.render(context, request) content_type = None # Django will use DEFAULT_CONTENT_TYPE except TemplateDoesNotExist: if template_name != ERROR_404_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) content_type = 'text/html' return http.HttpResponseNotFound(body, content_type=content_type) @requires_csrf_token def server_error(request, template_name=ERROR_500_TEMPLATE_NAME): """ 500 error handler. Templates: :template:`500.html` Context: None """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: if template_name != ERROR_500_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html') return http.HttpResponseServerError(template.render()) @requires_csrf_token def bad_request(request, exception, template_name=ERROR_400_TEMPLATE_NAME): """ 400 error handler. Templates: :template:`400.html` Context: None """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: if template_name != ERROR_400_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html') # No exception content is passed to the template, to not disclose any sensitive information. return http.HttpResponseBadRequest(template.render()) # This can be called when CsrfViewMiddleware.process_view has not run, # therefore need @requires_csrf_token in case the template needs # {% csrf_token %}. @requires_csrf_token def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME): """ Permission denied (403) handler. Templates: :template:`403.html` Context: None If the template does not exist, an Http403 response containing the text "403 Forbidden" (as per RFC 7231) will be returned. """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: if template_name != ERROR_403_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html') return http.HttpResponseForbidden( template.render(request=request, context={'exception': force_text(exception)}) )
23a35683724837e7086efaf35367d917b2275d8a8ec57ccfedbbb787fd05f472
from __future__ import unicode_literals import re import sys import types from django.conf import settings from django.http import HttpResponse, HttpResponseNotFound from django.template import Context, Engine, TemplateDoesNotExist from django.template.defaultfilters import force_escape, pprint from django.urls import Resolver404, resolve from django.utils import lru_cache, six, timezone from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_bytes, force_text from django.utils.module_loading import import_string from django.utils.translation import ugettext as _ # Minimal Django templates engine to render the error templates # regardless of the project's TEMPLATES setting. DEBUG_ENGINE = Engine(debug=True) HIDDEN_SETTINGS = re.compile('API|TOKEN|KEY|SECRET|PASS|SIGNATURE', flags=re.IGNORECASE) CLEANSED_SUBSTITUTE = '********************' class CallableSettingWrapper(object): """ Object to wrap callable appearing in settings * Not to call in the debug page (#21345). * Not to break the debug page if the callable forbidding to set attributes (#23070). """ def __init__(self, callable_setting): self._wrapped = callable_setting def __repr__(self): return repr(self._wrapped) def cleanse_setting(key, value): """Cleanse an individual setting key/value of sensitive content. If the value is a dictionary, recursively cleanse the keys in that dictionary. """ try: if HIDDEN_SETTINGS.search(key): cleansed = CLEANSED_SUBSTITUTE else: if isinstance(value, dict): cleansed = {k: cleanse_setting(k, v) for k, v in value.items()} else: cleansed = value except TypeError: # If the key isn't regex-able, just return as-is. cleansed = value if callable(cleansed): # For fixing #21345 and #23070 cleansed = CallableSettingWrapper(cleansed) return cleansed def get_safe_settings(): "Returns a dictionary of the settings module, with sensitive settings blurred out." settings_dict = {} for k in dir(settings): if k.isupper(): settings_dict[k] = cleanse_setting(k, getattr(settings, k)) return settings_dict def technical_500_response(request, exc_type, exc_value, tb, status_code=500): """ Create a technical server error response. The last three arguments are the values returned from sys.exc_info() and friends. """ reporter = ExceptionReporter(request, exc_type, exc_value, tb) if request.is_ajax(): text = reporter.get_traceback_text() return HttpResponse(text, status=status_code, content_type='text/plain') else: html = reporter.get_traceback_html() return HttpResponse(html, status=status_code, content_type='text/html') @lru_cache.lru_cache() def get_default_exception_reporter_filter(): # Instantiate the default filter for the first time and cache it. return import_string(settings.DEFAULT_EXCEPTION_REPORTER_FILTER)() def get_exception_reporter_filter(request): default_filter = get_default_exception_reporter_filter() return getattr(request, 'exception_reporter_filter', default_filter) class ExceptionReporterFilter(object): """ Base for all exception reporter filter classes. All overridable hooks contain lenient default behaviors. """ def get_post_parameters(self, request): if request is None: return {} else: return request.POST def get_traceback_frame_variables(self, request, tb_frame): return list(tb_frame.f_locals.items()) class SafeExceptionReporterFilter(ExceptionReporterFilter): """ Use annotations made by the sensitive_post_parameters and sensitive_variables decorators to filter out sensitive information. """ def is_active(self, request): """ This filter is to add safety in production environments (i.e. DEBUG is False). If DEBUG is True then your site is not safe anyway. This hook is provided as a convenience to easily activate or deactivate the filter on a per request basis. """ return settings.DEBUG is False def get_cleansed_multivaluedict(self, request, multivaluedict): """ Replaces the keys in a MultiValueDict marked as sensitive with stars. This mitigates leaking sensitive POST parameters if something like request.POST['nonexistent_key'] throws an exception (#21098). """ sensitive_post_parameters = getattr(request, 'sensitive_post_parameters', []) if self.is_active(request) and sensitive_post_parameters: multivaluedict = multivaluedict.copy() for param in sensitive_post_parameters: if param in multivaluedict: multivaluedict[param] = CLEANSED_SUBSTITUTE return multivaluedict def get_post_parameters(self, request): """ Replaces the values of POST parameters marked as sensitive with stars (*********). """ if request is None: return {} else: sensitive_post_parameters = getattr(request, 'sensitive_post_parameters', []) if self.is_active(request) and sensitive_post_parameters: cleansed = request.POST.copy() if sensitive_post_parameters == '__ALL__': # Cleanse all parameters. for k, v in cleansed.items(): cleansed[k] = CLEANSED_SUBSTITUTE return cleansed else: # Cleanse only the specified parameters. for param in sensitive_post_parameters: if param in cleansed: cleansed[param] = CLEANSED_SUBSTITUTE return cleansed else: return request.POST def cleanse_special_types(self, request, value): try: # If value is lazy or a complex object of another kind, this check # might raise an exception. isinstance checks that lazy # MultiValueDicts will have a return value. is_multivalue_dict = isinstance(value, MultiValueDict) except Exception as e: return '{!r} while evaluating {!r}'.format(e, value) if is_multivalue_dict: # Cleanse MultiValueDicts (request.POST is the one we usually care about) value = self.get_cleansed_multivaluedict(request, value) return value def get_traceback_frame_variables(self, request, tb_frame): """ Replaces the values of variables marked as sensitive with stars (*********). """ # Loop through the frame's callers to see if the sensitive_variables # decorator was used. current_frame = tb_frame.f_back sensitive_variables = None while current_frame is not None: if (current_frame.f_code.co_name == 'sensitive_variables_wrapper' and 'sensitive_variables_wrapper' in current_frame.f_locals): # The sensitive_variables decorator was used, so we take note # of the sensitive variables' names. wrapper = current_frame.f_locals['sensitive_variables_wrapper'] sensitive_variables = getattr(wrapper, 'sensitive_variables', None) break current_frame = current_frame.f_back cleansed = {} if self.is_active(request) and sensitive_variables: if sensitive_variables == '__ALL__': # Cleanse all variables for name, value in tb_frame.f_locals.items(): cleansed[name] = CLEANSED_SUBSTITUTE else: # Cleanse specified variables for name, value in tb_frame.f_locals.items(): if name in sensitive_variables: value = CLEANSED_SUBSTITUTE else: value = self.cleanse_special_types(request, value) cleansed[name] = value else: # Potentially cleanse the request and any MultiValueDicts if they # are one of the frame variables. for name, value in tb_frame.f_locals.items(): cleansed[name] = self.cleanse_special_types(request, value) if (tb_frame.f_code.co_name == 'sensitive_variables_wrapper' and 'sensitive_variables_wrapper' in tb_frame.f_locals): # For good measure, obfuscate the decorated function's arguments in # the sensitive_variables decorator's frame, in case the variables # associated with those arguments were meant to be obfuscated from # the decorated function's frame. cleansed['func_args'] = CLEANSED_SUBSTITUTE cleansed['func_kwargs'] = CLEANSED_SUBSTITUTE return cleansed.items() class ExceptionReporter(object): """ A class to organize and coordinate reporting on exceptions. """ def __init__(self, request, exc_type, exc_value, tb, is_email=False): self.request = request self.filter = get_exception_reporter_filter(self.request) self.exc_type = exc_type self.exc_value = exc_value self.tb = tb self.is_email = is_email self.template_info = getattr(self.exc_value, 'template_debug', None) self.template_does_not_exist = False self.postmortem = None # Handle deprecated string exceptions if isinstance(self.exc_type, six.string_types): self.exc_value = Exception('Deprecated String Exception: %r' % self.exc_type) self.exc_type = type(self.exc_value) def get_traceback_data(self): """Return a dictionary containing traceback information.""" if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist): self.template_does_not_exist = True self.postmortem = self.exc_value.chain or [self.exc_value] frames = self.get_traceback_frames() for i, frame in enumerate(frames): if 'vars' in frame: frame_vars = [] for k, v in frame['vars']: v = pprint(v) # The force_escape filter assume unicode, make sure that works if isinstance(v, six.binary_type): v = v.decode('utf-8', 'replace') # don't choke on non-utf-8 input # Trim large blobs of data if len(v) > 4096: v = '%s... <trimmed %d bytes string>' % (v[0:4096], len(v)) frame_vars.append((k, force_escape(v))) frame['vars'] = frame_vars frames[i] = frame unicode_hint = '' if self.exc_type and issubclass(self.exc_type, UnicodeError): start = getattr(self.exc_value, 'start', None) end = getattr(self.exc_value, 'end', None) if start is not None and end is not None: unicode_str = self.exc_value.args[1] unicode_hint = force_text( unicode_str[max(start - 5, 0):min(end + 5, len(unicode_str))], 'ascii', errors='replace' ) from django import get_version c = { 'is_email': self.is_email, 'unicode_hint': unicode_hint, 'frames': frames, 'request': self.request, 'filtered_POST_items': self.filter.get_post_parameters(self.request).items(), 'settings': get_safe_settings(), 'sys_executable': sys.executable, 'sys_version_info': '%d.%d.%d' % sys.version_info[0:3], 'server_time': timezone.now(), 'django_version_info': get_version(), 'sys_path': sys.path, 'template_info': self.template_info, 'template_does_not_exist': self.template_does_not_exist, 'postmortem': self.postmortem, } if self.request is not None: c['request_GET_items'] = self.request.GET.items() c['request_FILES_items'] = self.request.FILES.items() c['request_COOKIES_items'] = self.request.COOKIES.items() # Check whether exception info is available if self.exc_type: c['exception_type'] = self.exc_type.__name__ if self.exc_value: c['exception_value'] = force_text(self.exc_value, errors='replace') if frames: c['lastframe'] = frames[-1] return c def get_traceback_html(self): "Return HTML version of debug 500 HTTP error page." t = DEBUG_ENGINE.from_string(TECHNICAL_500_TEMPLATE) c = Context(self.get_traceback_data(), use_l10n=False) return t.render(c) def get_traceback_text(self): "Return plain text version of debug 500 HTTP error page." t = DEBUG_ENGINE.from_string(TECHNICAL_500_TEXT_TEMPLATE) c = Context(self.get_traceback_data(), autoescape=False, use_l10n=False) return t.render(c) def _get_lines_from_file(self, filename, lineno, context_lines, loader=None, module_name=None): """ Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context). """ source = None if loader is not None and hasattr(loader, "get_source"): try: source = loader.get_source(module_name) except ImportError: pass if source is not None: source = source.splitlines() if source is None: try: with open(filename, 'rb') as fp: source = fp.read().splitlines() except (OSError, IOError): pass if source is None: return None, [], None, [] # If we just read the source from a file, or if the loader did not # apply tokenize.detect_encoding to decode the source into a Unicode # string, then we should do that ourselves. if isinstance(source[0], six.binary_type): encoding = 'ascii' for line in source[:2]: # File coding may be specified. Match pattern from PEP-263 # (http://www.python.org/dev/peps/pep-0263/) match = re.search(br'coding[:=]\s*([-\w.]+)', line) if match: encoding = match.group(1).decode('ascii') break source = [six.text_type(sline, encoding, 'replace') for sline in source] lower_bound = max(0, lineno - context_lines) upper_bound = lineno + context_lines pre_context = source[lower_bound:lineno] context_line = source[lineno] post_context = source[lineno + 1:upper_bound] return lower_bound, pre_context, context_line, post_context def get_traceback_frames(self): def explicit_or_implicit_cause(exc_value): explicit = getattr(exc_value, '__cause__', None) implicit = getattr(exc_value, '__context__', None) return explicit or implicit # Get the exception and all its causes exceptions = [] exc_value = self.exc_value while exc_value: exceptions.append(exc_value) exc_value = explicit_or_implicit_cause(exc_value) frames = [] # No exceptions were supplied to ExceptionReporter if not exceptions: return frames # In case there's just one exception (always in Python 2, # sometimes in Python 3), take the traceback from self.tb (Python 2 # doesn't have a __traceback__ attribute on Exception) exc_value = exceptions.pop() tb = self.tb if six.PY2 or not exceptions else exc_value.__traceback__ while tb is not None: # Support for __traceback_hide__ which is used by a few libraries # to hide internal frames. if tb.tb_frame.f_locals.get('__traceback_hide__'): tb = tb.tb_next continue filename = tb.tb_frame.f_code.co_filename function = tb.tb_frame.f_code.co_name lineno = tb.tb_lineno - 1 loader = tb.tb_frame.f_globals.get('__loader__') module_name = tb.tb_frame.f_globals.get('__name__') or '' pre_context_lineno, pre_context, context_line, post_context = self._get_lines_from_file( filename, lineno, 7, loader, module_name, ) if pre_context_lineno is not None: frames.append({ 'exc_cause': explicit_or_implicit_cause(exc_value), 'exc_cause_explicit': getattr(exc_value, '__cause__', True), 'tb': tb, 'type': 'django' if module_name.startswith('django.') else 'user', 'filename': filename, 'function': function, 'lineno': lineno + 1, 'vars': self.filter.get_traceback_frame_variables(self.request, tb.tb_frame), 'id': id(tb), 'pre_context': pre_context, 'context_line': context_line, 'post_context': post_context, 'pre_context_lineno': pre_context_lineno + 1, }) # If the traceback for current exception is consumed, try the # other exception. if six.PY2: tb = tb.tb_next elif not tb.tb_next and exceptions: exc_value = exceptions.pop() tb = exc_value.__traceback__ else: tb = tb.tb_next return frames def format_exception(self): """ Return the same data as from traceback.format_exception. """ import traceback frames = self.get_traceback_frames() tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames] list = ['Traceback (most recent call last):\n'] list += traceback.format_list(tb) list += traceback.format_exception_only(self.exc_type, self.exc_value) return list def technical_404_response(request, exception): "Create a technical 404 error response. The exception should be the Http404." try: error_url = exception.args[0]['path'] except (IndexError, TypeError, KeyError): error_url = request.path_info[1:] # Trim leading slash try: tried = exception.args[0]['tried'] except (IndexError, TypeError, KeyError): tried = [] else: if (not tried or ( # empty URLconf request.path == '/' and len(tried) == 1 and # default URLconf len(tried[0]) == 1 and getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin' )): return default_urlconf(request) urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF) if isinstance(urlconf, types.ModuleType): urlconf = urlconf.__name__ caller = '' try: resolver_match = resolve(request.path) except Resolver404: pass else: obj = resolver_match.func if hasattr(obj, '__name__'): caller = obj.__name__ elif hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'): caller = obj.__class__.__name__ if hasattr(obj, '__module__'): module = obj.__module__ caller = '%s.%s' % (module, caller) t = DEBUG_ENGINE.from_string(TECHNICAL_404_TEMPLATE) c = Context({ 'urlconf': urlconf, 'root_urlconf': settings.ROOT_URLCONF, 'request_path': error_url, 'urlpatterns': tried, 'reason': force_bytes(exception, errors='replace'), 'request': request, 'settings': get_safe_settings(), 'raising_view_name': caller, }) return HttpResponseNotFound(t.render(c), content_type='text/html') def default_urlconf(request): "Create an empty URLconf 404 error response." t = DEBUG_ENGINE.from_string(DEFAULT_URLCONF_TEMPLATE) c = Context({ "title": _("Welcome to Django"), "heading": _("It worked!"), "subheading": _("Congratulations on your first Django-powered page."), "instructions": _( "Of course, you haven't actually done any work yet. " "Next, start your first app by running <code>python manage.py startapp [app_label]</code>." ), "explanation": _( "You're seeing this message because you have <code>DEBUG = True</code> in your " "Django settings file and you haven't configured any URLs. Get to work!" ), }) return HttpResponse(t.render(c), content_type='text/html') # # Templates are embedded in the file so that we know the error handler will # always work even if the template loader is broken. # TECHNICAL_500_TEMPLATE = (""" <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>{% if exception_type %}{{ exception_type }}{% else %}Report{% endif %}""" r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; } h2 { margin-bottom:.8em; } h2 span { font-size:80%; color:#666; font-weight:normal; } h3 { margin:1em 0 .5em 0; } h4 { margin:0 0 .5em 0; font-weight: normal; } code, pre { font-size: 100%; white-space: pre-wrap; } table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; } tbody td, tbody th { vertical-align:top; padding:2px 3px; } thead th { padding:1px 6px 1px 3px; background:#fefefe; text-align:left; font-weight:normal; font-size:11px; border:1px solid #ddd; } tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; } table.vars { margin:5px 0 2px 40px; } table.vars td, table.req td { font-family:monospace; } table td.code { width:100%; } table td.code pre { overflow:hidden; } table.source th { color:#666; } table.source td { font-family:monospace; white-space:pre; border-bottom:1px solid #eee; } ul.traceback { list-style-type:none; color: #222; } ul.traceback li.frame { padding-bottom:1em; color:#666; } ul.traceback li.user { background-color:#e0e0e0; color:#000 } div.context { padding:10px 0; overflow:hidden; } div.context ol { padding-left:30px; margin:0 10px; list-style-position: inside; } div.context ol li { font-family:monospace; white-space:pre; color:#777; cursor:pointer; padding-left: 2px; } div.context ol li pre { display:inline; } div.context ol.context-line li { color:#505050; background-color:#dfdfdf; padding: 3px 2px; } div.context ol.context-line li span { position:absolute; right:32px; } .user div.context ol.context-line li { background-color:#bbb; color:#000; } .user div.context ol li { color:#666; } div.commands { margin-left: 40px; } div.commands a { color:#555; text-decoration:none; } .user div.commands a { color: black; } #summary { background: #ffc; } #summary h2 { font-weight: normal; color: #666; } #explanation { background:#eee; } #template, #template-not-exist { background:#f6f6f6; } #template-not-exist ul { margin: 0 0 10px 20px; } #template-not-exist .postmortem-section { margin-bottom: 3px; } #unicode-hint { background:#eee; } #traceback { background:#eee; } #requestinfo { background:#f6f6f6; padding-left:120px; } #summary table { border:none; background:transparent; } #requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; } #requestinfo h3 { margin-bottom:-1em; } .error { background: #ffc; } .specific { color:#cc3300; font-weight:bold; } h2 span.commands { font-size:.7em;} span.commands a:link {color:#5E5694;} pre.exception_value { font-family: sans-serif; color: #666; font-size: 1.5em; margin: 10px 0 10px 0; } .append-bottom { margin-bottom: 10px; } </style> {% if not is_email %} <script type="text/javascript"> //<!-- function getElementsByClassName(oElm, strTagName, strClassName){ // Written by Jonathan Snook, http://www.snook.ca/jon; Add-ons by Robert Nyman, http://www.robertnyman.com var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName); var arrReturnElements = new Array(); strClassName = strClassName.replace(/\-/g, "\\-"); var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)"); var oElement; for(var i=0; i<arrElements.length; i++){ oElement = arrElements[i]; if(oRegExp.test(oElement.className)){ arrReturnElements.push(oElement); } } return (arrReturnElements) } function hideAll(elems) { for (var e = 0; e < elems.length; e++) { elems[e].style.display = 'none'; } } window.onload = function() { hideAll(getElementsByClassName(document, 'table', 'vars')); hideAll(getElementsByClassName(document, 'ol', 'pre-context')); hideAll(getElementsByClassName(document, 'ol', 'post-context')); hideAll(getElementsByClassName(document, 'div', 'pastebin')); } function toggle() { for (var i = 0; i < arguments.length; i++) { var e = document.getElementById(arguments[i]); if (e) { e.style.display = e.style.display == 'none' ? 'block': 'none'; } } return false; } function varToggle(link, id) { toggle('v' + id); var s = link.getElementsByTagName('span')[0]; var uarr = String.fromCharCode(0x25b6); var darr = String.fromCharCode(0x25bc); s.textContent = s.textContent == uarr ? darr : uarr; return false; } function switchPastebinFriendly(link) { s1 = "Switch to copy-and-paste view"; s2 = "Switch back to interactive view"; link.textContent = link.textContent.trim() == s1 ? s2: s1; toggle('browserTraceback', 'pastebinTraceback'); return false; } //--> </script> {% endif %} </head> <body> <div id="summary"> <h1>{% if exception_type %}{{ exception_type }}{% else %}Report{% endif %}""" """{% if request %} at {{ request.path_info|escape }}{% endif %}</h1> <pre class="exception_value">""" """{% if exception_value %}{{ exception_value|force_escape }}{% else %}No exception message supplied{% endif %}""" """</pre> <table class="meta"> {% if request %} <tr> <th>Request Method:</th> <td>{{ request.META.REQUEST_METHOD }}</td> </tr> <tr> <th>Request URL:</th> <td>{{ request.get_raw_uri|escape }}</td> </tr> {% endif %} <tr> <th>Django Version:</th> <td>{{ django_version_info }}</td> </tr> {% if exception_type %} <tr> <th>Exception Type:</th> <td>{{ exception_type }}</td> </tr> {% endif %} {% if exception_type and exception_value %} <tr> <th>Exception Value:</th> <td><pre>{{ exception_value|force_escape }}</pre></td> </tr> {% endif %} {% if lastframe %} <tr> <th>Exception Location:</th> <td>{{ lastframe.filename|escape }} in {{ lastframe.function|escape }}, line {{ lastframe.lineno }}</td> </tr> {% endif %} <tr> <th>Python Executable:</th> <td>{{ sys_executable|escape }}</td> </tr> <tr> <th>Python Version:</th> <td>{{ sys_version_info }}</td> </tr> <tr> <th>Python Path:</th> <td><pre>{{ sys_path|pprint }}</pre></td> </tr> <tr> <th>Server time:</th> <td>{{server_time|date:"r"}}</td> </tr> </table> </div> {% if unicode_hint %} <div id="unicode-hint"> <h2>Unicode error hint</h2> <p>The string that could not be encoded/decoded was: <strong>{{ unicode_hint|force_escape }}</strong></p> </div> {% endif %} {% if template_does_not_exist %} <div id="template-not-exist"> <h2>Template-loader postmortem</h2> {% if postmortem %} <p class="append-bottom">Django tried loading these templates, in this order:</p> {% for entry in postmortem %} <p class="postmortem-section">Using engine <code>{{ entry.backend.name }}</code>:</p> <ul> {% if entry.tried %} {% for attempt in entry.tried %} <li><code>{{ attempt.0.loader_name }}</code>: {{ attempt.0.name }} ({{ attempt.1 }})</li> {% endfor %} {% else %} <li>This engine did not provide a list of tried templates.</li> {% endif %} </ul> {% endfor %} {% else %} <p>No templates were found because your 'TEMPLATES' setting is not configured.</p> {% endif %} </div> {% endif %} {% if template_info %} <div id="template"> <h2>Error during template rendering</h2> <p>In template <code>{{ template_info.name }}</code>, error at line <strong>{{ template_info.line }}</strong></p> <h3>{{ template_info.message }}</h3> <table class="source{% if template_info.top %} cut-top{% endif %} {% if template_info.bottom != template_info.total %} cut-bottom{% endif %}"> {% for source_line in template_info.source_lines %} {% if source_line.0 == template_info.line %} <tr class="error"><th>{{ source_line.0 }}</th> <td>{{ template_info.before }}""" """<span class="specific">{{ template_info.during }}</span>""" """{{ template_info.after }}</td> </tr> {% else %} <tr><th>{{ source_line.0 }}</th> <td>{{ source_line.1 }}</td></tr> {% endif %} {% endfor %} </table> </div> {% endif %} {% if frames %} <div id="traceback"> <h2>Traceback <span class="commands">{% if not is_email %}<a href="#" onclick="return switchPastebinFriendly(this);"> Switch to copy-and-paste view</a></span>{% endif %} </h2> {% autoescape off %} <div id="browserTraceback"> <ul class="traceback"> {% for frame in frames %} {% ifchanged frame.exc_cause %}{% if frame.exc_cause %} <li><h3> {% if frame.exc_cause_explicit %} The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception: {% else %} During handling of the above exception ({{ frame.exc_cause }}), another exception occurred: {% endif %} </h3></li> {% endif %}{% endifchanged %} <li class="frame {{ frame.type }}"> <code>{{ frame.filename|escape }}</code> in <code>{{ frame.function|escape }}</code> {% if frame.context_line %} <div class="context" id="c{{ frame.id }}"> {% if frame.pre_context and not is_email %} <ol start="{{ frame.pre_context_lineno }}" class="pre-context" id="pre{{ frame.id }}"> {% for line in frame.pre_context %} <li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')"><pre>{{ line|escape }}</pre></li> {% endfor %} </ol> {% endif %} <ol start="{{ frame.lineno }}" class="context-line"> <li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')"><pre> """ """{{ frame.context_line|escape }}</pre>{% if not is_email %} <span>...</span>{% endif %}</li></ol> {% if frame.post_context and not is_email %} <ol start='{{ frame.lineno|add:"1" }}' class="post-context" id="post{{ frame.id }}"> {% for line in frame.post_context %} <li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')"><pre>{{ line|escape }}</pre></li> {% endfor %} </ol> {% endif %} </div> {% endif %} {% if frame.vars %} <div class="commands"> {% if is_email %} <h2>Local Vars</h2> {% else %} <a href="#" onclick="return varToggle(this, '{{ frame.id }}')"><span>&#x25b6;</span> Local vars</a> {% endif %} </div> <table class="vars" id="v{{ frame.id }}"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in frame.vars|dictsort:0 %} <tr> <td>{{ var.0|force_escape }}</td> <td class="code"><pre>{{ var.1 }}</pre></td> </tr> {% endfor %} </tbody> </table> {% endif %} </li> {% endfor %} </ul> </div> {% endautoescape %} <form action="http://dpaste.com/" name="pasteform" id="pasteform" method="post"> {% if not is_email %} <div id="pastebinTraceback" class="pastebin"> <input type="hidden" name="language" value="PythonConsole"> <input type="hidden" name="title" value="{{ exception_type|escape }}{% if request %} at {{ request.path_info|escape }}{% endif %}"> <input type="hidden" name="source" value="Django Dpaste Agent"> <input type="hidden" name="poster" value="Django"> <textarea name="content" id="traceback_area" cols="140" rows="25"> Environment: {% if request %} Request Method: {{ request.META.REQUEST_METHOD }} Request URL: {{ request.get_raw_uri|escape }} {% endif %} Django Version: {{ django_version_info }} Python Version: {{ sys_version_info }} Installed Applications: {{ settings.INSTALLED_APPS|pprint }} Installed Middleware: {% if settings.MIDDLEWARE is not None %}{{ settings.MIDDLEWARE|pprint }}""" """{% else %}{{ settings.MIDDLEWARE_CLASSES|pprint }}{% endif %} {% if template_does_not_exist %}Template loader postmortem {% 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 }}) {% 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 %} Template error: In template {{ template_info.name }}, error at line {{ template_info.line }} {{ template_info.message }}""" "{% for source_line in template_info.source_lines %}" "{% if source_line.0 == template_info.line %}" " {{ source_line.0 }} : {{ template_info.before }} {{ template_info.during }} {{ template_info.after }}" "{% else %}" " {{ source_line.0 }} : {{ source_line.1 }}" """{% endif %}{% endfor %}{% endif %} Traceback:{% for frame in frames %} {% ifchanged frame.exc_cause %}{% if frame.exc_cause %}{% if frame.exc_cause_explicit %} The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception: {% else %} During handling of the above exception ({{ frame.exc_cause }}), another exception occurred: {% endif %}{% endif %}{% endifchanged %} File "{{ frame.filename|escape }}" in {{ frame.function|escape }} {% if frame.context_line %} {{ frame.lineno }}. {{ frame.context_line|escape }}{% endif %}{% endfor %} Exception Type: {{ exception_type|escape }}{% if request %} at {{ request.path_info|escape }}{% endif %} Exception Value: {{ exception_value|force_escape }} </textarea> <br><br> <input type="submit" value="Share this traceback on a public website"> </div> </form> </div> {% endif %} {% endif %} <div id="requestinfo"> <h2>Request information</h2> {% if request %} {% if request.user %} <h3 id="user-info">USER</h3> <p>{{ request.user }}</p> {% endif %} <h3 id="get-info">GET</h3> {% if request.GET %} <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for k, v in request_GET_items %} <tr> <td>{{ k }}</td> <td class="code"><pre>{{ v|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>No GET data</p> {% endif %} <h3 id="post-info">POST</h3> {% if filtered_POST_items %} <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for k, v in filtered_POST_items %} <tr> <td>{{ k }}</td> <td class="code"><pre>{{ v|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>No POST data</p> {% endif %} <h3 id="files-info">FILES</h3> {% if request.FILES %} <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for k, v in request_FILES_items %} <tr> <td>{{ k }}</td> <td class="code"><pre>{{ v|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>No FILES data</p> {% endif %} <h3 id="cookie-info">COOKIES</h3> {% if request.COOKIES %} <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for k, v in request_COOKIES_items %} <tr> <td>{{ k }}</td> <td class="code"><pre>{{ v|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>No cookie data</p> {% endif %} <h3 id="meta-info">META</h3> <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in request.META.items|dictsort:0 %} <tr> <td>{{ var.0 }}</td> <td class="code"><pre>{{ var.1|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>Request data not supplied</p> {% endif %} <h3 id="settings-info">Settings</h3> <h4>Using settings module <code>{{ settings.SETTINGS_MODULE }}</code></h4> <table class="req"> <thead> <tr> <th>Setting</th> <th>Value</th> </tr> </thead> <tbody> {% for var in settings.items|dictsort:0 %} <tr> <td>{{ var.0 }}</td> <td class="code"><pre>{{ var.1|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> </div> {% if not is_email %} <div id="explanation"> <p> You're seeing this error because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and Django will display a standard page generated by the handler for this status code. </p> </div> {% endif %} </body> </html> """) # NOQA 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 }} Request URL: {{ request.get_raw_uri }}{% endif %} Django Version: {{ django_version_info }} Python Executable: {{ sys_executable }} Python Version: {{ sys_version_info }} Python Path: {{ sys_path }} Server time: {{server_time|date:"r"}} Installed Applications: {{ settings.INSTALLED_APPS|pprint }} Installed Middleware: {% if settings.MIDDLEWARE is not None %}{{ settings.MIDDLEWARE|pprint }}""" """{% else %}{{ settings.MIDDLEWARE_CLASSES|pprint }}{% endif %} {% if template_does_not_exist %}Template loader postmortem {% 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 }}) {% 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 %} Template error: In template {{ template_info.name }}, error at line {{ template_info.line }} {{ template_info.message }} {% for source_line in template_info.source_lines %}""" "{% if source_line.0 == template_info.line %}" " {{ source_line.0 }} : {{ template_info.before }} {{ template_info.during }} {{ template_info.after }}" "{% else %}" " {{ source_line.0 }} : {{ source_line.1 }}" """{% endif %}{% endfor %}{% endif %}{% if frames %} Traceback:""" "{% for frame in frames %}" "{% ifchanged frame.exc_cause %}" " {% if frame.exc_cause %}" """ {% if frame.exc_cause_explicit %} The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception: {% else %} During handling of the above exception ({{ frame.exc_cause }}), another exception occurred: {% endif %} {% endif %} {% endifchanged %} File "{{ frame.filename }}" in {{ frame.function }} {% if frame.context_line %} {{ frame.lineno }}. {{ frame.context_line }}{% endif %} {% endfor %} {% if exception_type %}Exception Type: {{ exception_type }}{% if request %} at {{ request.path_info }}{% endif %} {% if exception_value %}Exception Value: {{ exception_value }}{% endif %}{% endif %}{% endif %} {% if request %}Request information: {% if request.user %}USER: {{ request.user }}{% endif %} GET:{% for k, v in request_GET_items %} {{ k }} = {{ v|stringformat:"r" }}{% empty %} No GET data{% endfor %} POST:{% for k, v in filtered_POST_items %} {{ k }} = {{ v|stringformat:"r" }}{% empty %} No POST data{% endfor %} FILES:{% for k, v in request_FILES_items %} {{ k }} = {{ v|stringformat:"r" }}{% empty %} No FILES data{% endfor %} COOKIES:{% for k, v in request_COOKIES_items %} {{ k }} = {{ v|stringformat:"r" }}{% empty %} No cookie data{% endfor %} META:{% for k, v in request.META.items|dictsort:0 %} {{ k }} = {{ v|stringformat:"r" }}{% endfor %} {% else %}Request data not supplied {% endif %} Settings: Using settings module {{ settings.SETTINGS_MODULE }}{% for k, v in settings.items|dictsort:0 %} {{ k }} = {{ v|stringformat:"r" }}{% endfor %} {% if not is_email %} You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard page generated by the handler for this status code. {% endif %} """) # NOQA TECHNICAL_404_TEMPLATE = """ <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Page not found at {{ request.path_info|escape }}</title> <meta name="robots" content="NONE,NOARCHIVE"> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; } table { border:none; border-collapse: collapse; width:100%; } td, th { vertical-align:top; padding:2px 3px; } th { width:12em; text-align:right; color:#666; padding-right:.5em; } #info { background:#f6f6f6; } #info ol { margin: 0.5em 4em; } #info ol li { font-family: monospace; } #summary { background: #ffc; } #explanation { background:#eee; border-bottom: 0px none; } </style> </head> <body> <div id="summary"> <h1>Page not found <span>(404)</span></h1> <table class="meta"> <tr> <th>Request Method:</th> <td>{{ request.META.REQUEST_METHOD }}</td> </tr> <tr> <th>Request URL:</th> <td>{{ request.build_absolute_uri|escape }}</td> </tr> {% if raising_view_name %} <tr> <th>Raised by:</th> <td>{{ raising_view_name }}</td> </tr> {% endif %} </table> </div> <div id="info"> {% if urlpatterns %} <p> Using the URLconf defined in <code>{{ urlconf }}</code>, Django tried these URL patterns, in this order: </p> <ol> {% for pattern in urlpatterns %} <li> {% for pat in pattern %} {{ pat.regex.pattern }} {% if forloop.last and pat.name %}[name='{{ pat.name }}']{% endif %} {% endfor %} </li> {% endfor %} </ol> <p> {% if request_path %} The current path, <code>{{ request_path|escape }}</code>,{% else %} The empty path{% endif %} didn't match any of these. </p> {% else %} <p>{{ reason }}</p> {% endif %} </div> <div id="explanation"> <p> You're seeing this error because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and Django will display a standard 404 page. </p> </div> </body> </html> """ DEFAULT_URLCONF_TEMPLATE = """ <!DOCTYPE html> <html lang="en"><head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"><title>{{ title }}</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; } h2 { margin-bottom:.8em; } h2 span { font-size:80%; color:#666; font-weight:normal; } h3 { margin:1em 0 .5em 0; } h4 { margin:0 0 .5em 0; font-weight: normal; } table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; } tbody td, tbody th { vertical-align:top; padding:2px 3px; } thead th { padding:1px 6px 1px 3px; background:#fefefe; text-align:left; font-weight:normal; font-size:11px; border:1px solid #ddd; } tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; } #summary { background: #e0ebff; } #summary h2 { font-weight: normal; color: #666; } #explanation { background:#eee; } #instructions { background:#f6f6f6; } #summary table { border:none; background:transparent; } </style> </head> <body> <div id="summary"> <h1>{{ heading }}</h1> <h2>{{ subheading }}</h2> </div> <div id="instructions"> <p> {{ instructions|safe }} </p> </div> <div id="explanation"> <p> {{ explanation|safe }} </p> </div> </body></html> """
d1fc234ee884c19d7a17382a73619e713fb36c162f608a2de615854494af6af8
from django.conf import settings from django.http import HttpResponseForbidden from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils.translation import ugettext as _ from django.utils.version import get_docs_version # We include the template inline since we need to be able to reliably display # this error message, especially for the sake of developers, and there isn't any # other way of making it available independent of what is in the settings file. # Only the text appearing with DEBUG=False is translated. Normal translation # tags cannot be used with this inline templates as makemessages would not be # able to discover the strings. CSRF_FAILURE_TEMPLATE = """ <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>403 Forbidden</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; } #info { background:#f6f6f6; } #info ul { margin: 0.5em 4em; } #info p, #summary p { padding-top:10px; } #summary { background: #ffc; } #explanation { background:#eee; border-bottom: 0px none; } </style> </head> <body> <div id="summary"> <h1>{{ title }} <span>(403)</span></h1> <p>{{ main }}</p> {% if no_referer %} <p>{{ no_referer1 }}</p> <p>{{ no_referer2 }}</p> {% endif %} {% if no_cookie %} <p>{{ no_cookie1 }}</p> <p>{{ no_cookie2 }}</p> {% endif %} </div> {% if DEBUG %} <div id="info"> <h2>Help</h2> {% if reason %} <p>Reason given for failure:</p> <pre> {{ reason }} </pre> {% endif %} <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when <a href="https://docs.djangoproject.com/en/{{ docs_version }}/ref/csrf/">Django's CSRF mechanism</a> has not been used correctly. For POST forms, you need to ensure:</p> <ul> <li>Your browser is accepting cookies.</li> <li>The view function passes a <code>request</code> to the template's <a href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a> method.</li> <li>In the template, there is a <code>{% templatetag openblock %} csrf_token {% templatetag closeblock %}</code> template tag inside each POST form that targets an internal URL.</li> <li>If you are not using <code>CsrfViewMiddleware</code>, then you must use <code>csrf_protect</code> on any views that use the <code>csrf_token</code> template tag, as well as those that accept the POST data.</li> <li>The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.</li> </ul> <p>You're seeing the help section of this page because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and only the initial error message will be displayed. </p> <p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p> </div> {% else %} <div id="explanation"> <p><small>{{ more }}</small></p> </div> {% endif %} </body> </html> """ CSRF_FAILURE_TEMPLATE_NAME = "403_csrf.html" def csrf_failure(request, reason="", template_name=CSRF_FAILURE_TEMPLATE_NAME): """ Default view used when request fails CSRF protection """ from django.middleware.csrf import REASON_NO_REFERER, REASON_NO_CSRF_COOKIE c = Context({ 'title': _("Forbidden"), 'main': _("CSRF verification failed. Request aborted."), 'reason': reason, 'no_referer': reason == REASON_NO_REFERER, 'no_referer1': _( "You are seeing this message because this HTTPS site requires a " "'Referer header' to be sent by your Web browser, but none was " "sent. This header is required for security reasons, to ensure " "that your browser is not being hijacked by third parties."), 'no_referer2': _( "If you have configured your browser to disable 'Referer' headers, " "please re-enable them, at least for this site, or for HTTPS " "connections, or for 'same-origin' requests."), 'no_cookie': reason == REASON_NO_CSRF_COOKIE, 'no_cookie1': _( "You are seeing this message because this site requires a CSRF " "cookie when submitting forms. This cookie is required for " "security reasons, to ensure that your browser is not being " "hijacked by third parties."), 'no_cookie2': _( "If you have configured your browser to disable cookies, please " "re-enable them, at least for this site, or for 'same-origin' " "requests."), 'DEBUG': settings.DEBUG, 'docs_version': get_docs_version(), 'more': _("More information is available with DEBUG=True."), }) try: t = loader.get_template(template_name) except TemplateDoesNotExist: if template_name == CSRF_FAILURE_TEMPLATE_NAME: # If the default template doesn't exist, use the string template. t = Engine().from_string(CSRF_FAILURE_TEMPLATE) else: # Raise if a developer-specified template doesn't exist. raise return HttpResponseForbidden(t.render(c), content_type='text/html')
7bf979cddf27fc01eaad38199bb65c68148bb414774ec23cc4cb16ef40cd7bc4
""" Settings and configuration for Django. Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment variable, and then from django.conf.global_settings; see the global settings file for a list of all possible variables. """ import importlib import os import time from django.conf import global_settings from django.core.exceptions import ImproperlyConfigured from django.utils.functional import LazyObject, empty ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE" class LazySettings(LazyObject): """ A lazy proxy for either global Django settings or a custom settings object. The user can manually configure settings prior to using them. Otherwise, Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE. """ def _setup(self, name=None): """ Load the settings module pointed to by the environment variable. This is used the first time we need any settings at all, if the user has not previously configured the settings manually. """ settings_module = os.environ.get(ENVIRONMENT_VARIABLE) if not settings_module: desc = ("setting %s" % name) if name else "settings" raise ImproperlyConfigured( "Requested %s, but settings are not configured. " "You must either define the environment variable %s " "or call settings.configure() before accessing settings." % (desc, ENVIRONMENT_VARIABLE)) self._wrapped = Settings(settings_module) def __repr__(self): # Hardcode the class name as otherwise it yields 'Settings'. if self._wrapped is empty: return '<LazySettings [Unevaluated]>' return '<LazySettings "%(settings_module)s">' % { 'settings_module': self._wrapped.SETTINGS_MODULE, } def __getattr__(self, name): if self._wrapped is empty: self._setup(name) return getattr(self._wrapped, name) def configure(self, default_settings=global_settings, **options): """ Called to manually configure the settings. The 'default_settings' parameter sets where to retrieve any unspecified values from (its argument must support attribute access (__getattr__)). """ if self._wrapped is not empty: raise RuntimeError('Settings already configured.') holder = UserSettingsHolder(default_settings) for name, value in options.items(): setattr(holder, name, value) self._wrapped = holder @property def configured(self): """ Returns True if the settings have already been configured. """ return self._wrapped is not empty class BaseSettings(object): """ Common logic for settings whether set by a module or by the user. """ def __setattr__(self, name, value): if name in ("MEDIA_URL", "STATIC_URL") and value and not value.endswith('/'): raise ImproperlyConfigured("If set, %s must end with a slash" % name) object.__setattr__(self, name, value) class Settings(BaseSettings): def __init__(self, settings_module): # update this dict from global settings (but only for ALL_CAPS settings) for setting in dir(global_settings): if setting.isupper(): setattr(self, setting, getattr(global_settings, setting)) # store the settings module in case someone later cares self.SETTINGS_MODULE = settings_module mod = importlib.import_module(self.SETTINGS_MODULE) tuple_settings = ( "INSTALLED_APPS", "TEMPLATE_DIRS", "LOCALE_PATHS", ) self._explicit_settings = set() for setting in dir(mod): if setting.isupper(): setting_value = getattr(mod, setting) if (setting in tuple_settings and not isinstance(setting_value, (list, tuple))): raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting) setattr(self, setting, setting_value) self._explicit_settings.add(setting) if not self.SECRET_KEY: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") if hasattr(time, 'tzset') and self.TIME_ZONE: # When we can, attempt to validate the timezone. If we can't find # this file, no check happens and it's harmless. zoneinfo_root = '/usr/share/zoneinfo' if (os.path.exists(zoneinfo_root) and not os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))): raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE) # Move the time zone info into os.environ. See ticket #2315 for why # we don't do this unconditionally (breaks Windows). os.environ['TZ'] = self.TIME_ZONE time.tzset() def is_overridden(self, setting): return setting in self._explicit_settings def __repr__(self): return '<%(cls)s "%(settings_module)s">' % { 'cls': self.__class__.__name__, 'settings_module': self.SETTINGS_MODULE, } class UserSettingsHolder(BaseSettings): """ Holder for user configured settings. """ # SETTINGS_MODULE doesn't make much sense in the manually configured # (standalone) case. SETTINGS_MODULE = None def __init__(self, default_settings): """ Requests for configuration variables not in this class are satisfied from the module specified in default_settings (if possible). """ self.__dict__['_deleted'] = set() self.default_settings = default_settings def __getattr__(self, name): if name in self._deleted: raise AttributeError return getattr(self.default_settings, name) def __setattr__(self, name, value): self._deleted.discard(name) super(UserSettingsHolder, self).__setattr__(name, value) def __delattr__(self, name): self._deleted.add(name) if hasattr(self, name): super(UserSettingsHolder, self).__delattr__(name) def __dir__(self): return sorted( s for s in list(self.__dict__) + dir(self.default_settings) if s not in self._deleted ) def is_overridden(self, setting): deleted = (setting in self._deleted) set_locally = (setting in self.__dict__) set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting) return (deleted or set_locally or set_on_default) def __repr__(self): return '<%(cls)s>' % { 'cls': self.__class__.__name__, } settings = LazySettings()
2e49afbd831815e0be20fe3719d804b56050cd33d3d0eb9abbf6abce996c0bf5
# -*- coding: utf-8 -*- """ Default Django settings. Override these with settings in the module pointed to by the DJANGO_SETTINGS_MODULE environment variable. """ from __future__ import unicode_literals # This is defined here as a do-nothing function because we can't import # django.utils.translation -- that module depends on the settings. def gettext_noop(s): return s #################### # CORE # #################### DEBUG = False # Whether the framework should propagate raw exceptions rather than catching # them. This is useful under some testing situations and should never be used # on a live site. DEBUG_PROPAGATE_EXCEPTIONS = False # Whether to use the "ETag" header. This saves bandwidth but slows down performance. # Deprecated (RemovedInDjango21Warning) in favor of ConditionalGetMiddleware # which sets the ETag regardless of this setting. USE_ETAGS = False # People who get code error notifications. # In the format [('Full Name', '[email protected]'), ('Full Name', '[email protected]')] ADMINS = [] # List of IP addresses, as strings, that: # * See debug comments, when DEBUG is true # * Receive x-headers INTERNAL_IPS = [] # Hosts/domain names that are valid for this site. # "*" matches anything, ".example.com" matches example.com and all subdomains ALLOWED_HOSTS = [] # Local time zone for this installation. All choices can be found here: # https://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all # systems may support all possibilities). When USE_TZ is True, this is # interpreted as the default user time zone. TIME_ZONE = 'America/Chicago' # If you set this to True, Django will use timezone-aware datetimes. USE_TZ = False # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' # Languages we provide translations for, out of the box. LANGUAGES = [ ('af', gettext_noop('Afrikaans')), ('ar', gettext_noop('Arabic')), ('ast', gettext_noop('Asturian')), ('az', gettext_noop('Azerbaijani')), ('bg', gettext_noop('Bulgarian')), ('be', gettext_noop('Belarusian')), ('bn', gettext_noop('Bengali')), ('br', gettext_noop('Breton')), ('bs', gettext_noop('Bosnian')), ('ca', gettext_noop('Catalan')), ('cs', gettext_noop('Czech')), ('cy', gettext_noop('Welsh')), ('da', gettext_noop('Danish')), ('de', gettext_noop('German')), ('dsb', gettext_noop('Lower Sorbian')), ('el', gettext_noop('Greek')), ('en', gettext_noop('English')), ('en-au', gettext_noop('Australian English')), ('en-gb', gettext_noop('British English')), ('eo', gettext_noop('Esperanto')), ('es', gettext_noop('Spanish')), ('es-ar', gettext_noop('Argentinian Spanish')), ('es-co', gettext_noop('Colombian Spanish')), ('es-mx', gettext_noop('Mexican Spanish')), ('es-ni', gettext_noop('Nicaraguan Spanish')), ('es-ve', gettext_noop('Venezuelan Spanish')), ('et', gettext_noop('Estonian')), ('eu', gettext_noop('Basque')), ('fa', gettext_noop('Persian')), ('fi', gettext_noop('Finnish')), ('fr', gettext_noop('French')), ('fy', gettext_noop('Frisian')), ('ga', gettext_noop('Irish')), ('gd', gettext_noop('Scottish Gaelic')), ('gl', gettext_noop('Galician')), ('he', gettext_noop('Hebrew')), ('hi', gettext_noop('Hindi')), ('hr', gettext_noop('Croatian')), ('hsb', gettext_noop('Upper Sorbian')), ('hu', gettext_noop('Hungarian')), ('ia', gettext_noop('Interlingua')), ('id', gettext_noop('Indonesian')), ('io', gettext_noop('Ido')), ('is', gettext_noop('Icelandic')), ('it', gettext_noop('Italian')), ('ja', gettext_noop('Japanese')), ('ka', gettext_noop('Georgian')), ('kk', gettext_noop('Kazakh')), ('km', gettext_noop('Khmer')), ('kn', gettext_noop('Kannada')), ('ko', gettext_noop('Korean')), ('lb', gettext_noop('Luxembourgish')), ('lt', gettext_noop('Lithuanian')), ('lv', gettext_noop('Latvian')), ('mk', gettext_noop('Macedonian')), ('ml', gettext_noop('Malayalam')), ('mn', gettext_noop('Mongolian')), ('mr', gettext_noop('Marathi')), ('my', gettext_noop('Burmese')), ('nb', gettext_noop('Norwegian Bokmål')), ('ne', gettext_noop('Nepali')), ('nl', gettext_noop('Dutch')), ('nn', gettext_noop('Norwegian Nynorsk')), ('os', gettext_noop('Ossetic')), ('pa', gettext_noop('Punjabi')), ('pl', gettext_noop('Polish')), ('pt', gettext_noop('Portuguese')), ('pt-br', gettext_noop('Brazilian Portuguese')), ('ro', gettext_noop('Romanian')), ('ru', gettext_noop('Russian')), ('sk', gettext_noop('Slovak')), ('sl', gettext_noop('Slovenian')), ('sq', gettext_noop('Albanian')), ('sr', gettext_noop('Serbian')), ('sr-latn', gettext_noop('Serbian Latin')), ('sv', gettext_noop('Swedish')), ('sw', gettext_noop('Swahili')), ('ta', gettext_noop('Tamil')), ('te', gettext_noop('Telugu')), ('th', gettext_noop('Thai')), ('tr', gettext_noop('Turkish')), ('tt', gettext_noop('Tatar')), ('udm', gettext_noop('Udmurt')), ('uk', gettext_noop('Ukrainian')), ('ur', gettext_noop('Urdu')), ('vi', gettext_noop('Vietnamese')), ('zh-hans', gettext_noop('Simplified Chinese')), ('zh-hant', gettext_noop('Traditional Chinese')), ] # Languages using BiDi (right-to-left) layout LANGUAGES_BIDI = ["he", "ar", "fa", "ur"] # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True LOCALE_PATHS = [] # Settings for language cookie LANGUAGE_COOKIE_NAME = 'django_language' LANGUAGE_COOKIE_AGE = None LANGUAGE_COOKIE_DOMAIN = None LANGUAGE_COOKIE_PATH = '/' # If you set this to True, Django will format dates, numbers and calendars # according to user current locale. USE_L10N = False # Not-necessarily-technical managers of the site. They get broken link # notifications and other various emails. MANAGERS = ADMINS # Default content type and charset to use for all HttpResponse objects, if a # MIME type isn't manually specified. These are used to construct the # Content-Type header. DEFAULT_CONTENT_TYPE = 'text/html' DEFAULT_CHARSET = 'utf-8' # Encoding of files read from disk (template and initial SQL files). FILE_CHARSET = 'utf-8' # Email address that error messages come from. SERVER_EMAIL = 'root@localhost' # Database connection info. If left empty, will default to the dummy backend. DATABASES = {} # Classes used to implement DB routing behavior. DATABASE_ROUTERS = [] # The email backend to use. For possible shortcuts see django.core.mail. # The default is to use the SMTP backend. # Third-party backends can be specified by providing a Python path # to a module that defines an EmailBackend class. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Host for sending email. EMAIL_HOST = 'localhost' # Port for sending email. EMAIL_PORT = 25 # Whether to send SMTP 'Date' header in the local time zone or in UTC. EMAIL_USE_LOCALTIME = False # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False EMAIL_USE_SSL = False EMAIL_SSL_CERTFILE = None EMAIL_SSL_KEYFILE = None EMAIL_TIMEOUT = None # List of strings representing installed apps. INSTALLED_APPS = [] TEMPLATES = [] # Default email address to use for various automated correspondence from # the site managers. DEFAULT_FROM_EMAIL = 'webmaster@localhost' # Subject-line prefix for email messages send with django.core.mail.mail_admins # or ...mail_managers. Make sure to include the trailing space. EMAIL_SUBJECT_PREFIX = '[Django] ' # Whether to append trailing slashes to URLs. APPEND_SLASH = True # Whether to prepend the "www." subdomain to URLs that don't have it. PREPEND_WWW = False # Override the server-derived value of SCRIPT_NAME FORCE_SCRIPT_NAME = None # List of compiled regular expression objects representing User-Agent strings # that are not allowed to visit any page, systemwide. Use this for bad # robots/crawlers. Here are a few examples: # import re # DISALLOWED_USER_AGENTS = [ # re.compile(r'^NaverBot.*'), # re.compile(r'^EmailSiphon.*'), # re.compile(r'^SiteSucker.*'), # re.compile(r'^sohu-search') # ] DISALLOWED_USER_AGENTS = [] ABSOLUTE_URL_OVERRIDES = {} # List of compiled regular expression objects representing URLs that need not # be reported by BrokenLinkEmailsMiddleware. Here are a few examples: # import re # IGNORABLE_404_URLS = [ # re.compile(r'^/apple-touch-icon.*\.png$'), # re.compile(r'^/favicon.ico$), # re.compile(r'^/robots.txt$), # re.compile(r'^/phpmyadmin/), # re.compile(r'\.(cgi|php|pl)$'), # ] IGNORABLE_404_URLS = [] # A secret key for this particular Django installation. Used in secret-key # hashing algorithms. Set this in your settings, or Django will complain # loudly. SECRET_KEY = '' # Default file storage mechanism that holds media. DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/var/www/example.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. # Examples: "http://example.com/media/", "http://media.example.com/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Example: "/var/www/example.com/static/" STATIC_ROOT = None # URL that handles the static files served from STATIC_ROOT. # Example: "http://example.com/static/", "http://static.example.com/" STATIC_URL = None # List of upload handler classes to be applied in order. FILE_UPLOAD_HANDLERS = [ 'django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler', ] # Maximum size, in bytes, of a request before it will be streamed to the # file system instead of into memory. FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB # Maximum size in bytes of request data (excluding file uploads) that will be # read before a SuspiciousOperation (RequestDataTooBig) is raised. DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB # Maximum number of GET/POST parameters that will be read before a # SuspiciousOperation (TooManyFieldsSent) is raised. DATA_UPLOAD_MAX_NUMBER_FIELDS = 1000 # Directory in which upload streamed files will be temporarily saved. A value of # `None` will make Django use the operating system's default temporary directory # (i.e. "/tmp" on *nix systems). FILE_UPLOAD_TEMP_DIR = None # The numeric mode to set newly-uploaded files to. The value should be a mode # you'd pass directly to os.chmod; see https://docs.python.org/3/library/os.html#files-and-directories. FILE_UPLOAD_PERMISSIONS = None # The numeric mode to assign to newly-created directories, when uploading files. # The value should be a mode as you'd pass to os.chmod; # see https://docs.python.org/3/library/os.html#files-and-directories. FILE_UPLOAD_DIRECTORY_PERMISSIONS = None # Python module path where user will place custom format definition. # The directory where this setting is pointing should contain subdirectories # named as the locales, containing a formats.py file # (i.e. "myproject.locale" for myproject/locale/en/formats.py etc. use) FORMAT_MODULE_PATH = None # Default formatting for date objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'N j, Y' # Default formatting for datetime objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATETIME_FORMAT = 'N j, Y, P' # Default formatting for time objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date TIME_FORMAT = 'P' # Default formatting for date objects when only the year and month are relevant. # See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date YEAR_MONTH_FORMAT = 'F Y' # Default formatting for date objects when only the month and day are relevant. # See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date MONTH_DAY_FORMAT = 'F j' # Default short formatting for date objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date SHORT_DATE_FORMAT = 'm/d/Y' # Default short formatting for datetime objects. # See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date SHORT_DATETIME_FORMAT = 'm/d/Y P' # Default formats to be used when parsing dates from input boxes, in order # See all available format string here: # http://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATE_INPUT_FORMATS = [ '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ] # Default formats to be used when parsing times from input boxes, in order # See all available format string here: # http://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates TIME_INPUT_FORMATS = [ '%H:%M:%S', # '14:30:59' '%H:%M:%S.%f', # '14:30:59.000200' '%H:%M', # '14:30' ] # Default formats to be used when parsing dates and times from input boxes, # in order # See all available format string here: # http://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M:%S.%f', # '10/25/2006 14:30:59.000200' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M:%S.%f', # '10/25/06 14:30:59.000200' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ] # First day of week, to be used on calendars # 0 means Sunday, 1 means Monday... FIRST_DAY_OF_WEEK = 0 # Decimal separator symbol DECIMAL_SEPARATOR = '.' # Boolean that sets whether to add thousand separator when formatting numbers USE_THOUSAND_SEPARATOR = False # Number of digits that will be together, when splitting them by # THOUSAND_SEPARATOR. 0 means no grouping, 3 means splitting by thousands... NUMBER_GROUPING = 0 # Thousand separator symbol THOUSAND_SEPARATOR = ',' # The tablespaces to use for each model when not specified otherwise. DEFAULT_TABLESPACE = '' DEFAULT_INDEX_TABLESPACE = '' # Default X-Frame-Options header value X_FRAME_OPTIONS = 'SAMEORIGIN' USE_X_FORWARDED_HOST = False USE_X_FORWARDED_PORT = False # The Python dotted path to the WSGI application that Django's internal server # (runserver) will use. If `None`, the return value of # 'django.core.wsgi.get_wsgi_application' is used, thus preserving the same # behavior as previous versions of Django. Otherwise this should point to an # actual WSGI application object. WSGI_APPLICATION = None # If your Django app is behind a proxy that sets a header to specify secure # connections, AND that proxy ensures that user-submitted headers with the # same name are ignored (so that people can't spoof it), set this value to # a tuple of (header_name, header_value). For any requests that come in with # that header/value, request.is_secure() will return True. # WARNING! Only set this if you fully understand what you're doing. Otherwise, # you may be opening yourself up to a security risk. SECURE_PROXY_SSL_HEADER = None ############## # MIDDLEWARE # ############## # List of middleware to use. Order is important; in the request phase, these # middleware will be applied in the order given, and in the response # phase the middleware will be applied in reverse order. MIDDLEWARE_CLASSES = [ 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ] MIDDLEWARE = None ############ # SESSIONS # ############ # Cache to store session data if using the cache session backend. SESSION_CACHE_ALIAS = 'default' # Cookie name. This can be whatever you want. SESSION_COOKIE_NAME = 'sessionid' # Age of cookie, in seconds (default: 2 weeks). SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 # A string like ".example.com", or None for standard domain cookie. SESSION_COOKIE_DOMAIN = None # Whether the session cookie should be secure (https:// only). SESSION_COOKIE_SECURE = False # The path of the session cookie. SESSION_COOKIE_PATH = '/' # Whether to use the non-RFC standard httpOnly flag (IE, FF3+, others) SESSION_COOKIE_HTTPONLY = True # Whether to save the session data on every request. SESSION_SAVE_EVERY_REQUEST = False # Whether a user's session cookie expires when the Web browser is closed. SESSION_EXPIRE_AT_BROWSER_CLOSE = False # The module to store session data SESSION_ENGINE = 'django.contrib.sessions.backends.db' # Directory to store session files if using the file session module. If None, # the backend will use a sensible default. SESSION_FILE_PATH = None # class to serialize session data SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer' ######### # CACHE # ######### # The cache backends to use. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } CACHE_MIDDLEWARE_KEY_PREFIX = '' CACHE_MIDDLEWARE_SECONDS = 600 CACHE_MIDDLEWARE_ALIAS = 'default' ################## # AUTHENTICATION # ################## AUTH_USER_MODEL = 'auth.User' AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend'] LOGIN_URL = '/accounts/login/' LOGIN_REDIRECT_URL = '/accounts/profile/' LOGOUT_REDIRECT_URL = None # The number of days a password reset link is valid for PASSWORD_RESET_TIMEOUT_DAYS = 3 # the first hasher in this list is the preferred algorithm. any # password using different algorithms will be converted automatically # upon login PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', ] AUTH_PASSWORD_VALIDATORS = [] ########### # SIGNING # ########### SIGNING_BACKEND = 'django.core.signing.TimestampSigner' ######## # CSRF # ######## # Dotted path to callable to be used as view when a request is # rejected by the CSRF middleware. CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure' # Settings for CSRF cookie. CSRF_COOKIE_NAME = 'csrftoken' CSRF_COOKIE_AGE = 60 * 60 * 24 * 7 * 52 CSRF_COOKIE_DOMAIN = None CSRF_COOKIE_PATH = '/' CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN' CSRF_TRUSTED_ORIGINS = [] ############ # MESSAGES # ############ # Class to use as messages backend MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage' # Default values of MESSAGE_LEVEL and MESSAGE_TAGS are defined within # django.contrib.messages to avoid imports in this settings file. ########### # LOGGING # ########### # The callable to use to configure logging LOGGING_CONFIG = 'logging.config.dictConfig' # Custom logging configuration. LOGGING = {} # Default exception reporter filter class used in case none has been # specifically assigned to the HttpRequest instance. DEFAULT_EXCEPTION_REPORTER_FILTER = 'django.views.debug.SafeExceptionReporterFilter' ########### # TESTING # ########### # The name of the class to use to run the test suite TEST_RUNNER = 'django.test.runner.DiscoverRunner' # Apps that don't need to be serialized at test database creation time # (only apps with migrations are to start with) TEST_NON_SERIALIZED_APPS = [] ############ # FIXTURES # ############ # The list of directories to search for fixtures FIXTURE_DIRS = [] ############### # STATICFILES # ############### # A list of locations of additional static files STATICFILES_DIRS = [] # The default file storage backend used during the build process STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ] ############## # MIGRATIONS # ############## # Migration module overrides for apps, by app label. MIGRATION_MODULES = {} ################# # SYSTEM CHECKS # ################# # List of all issues generated by system checks that should be silenced. Light # issues like warnings, infos or debugs will not generate a message. Silencing # serious issues like errors and criticals does not result in hiding the # message, but Django will not stop you from e.g. running server. SILENCED_SYSTEM_CHECKS = [] ####################### # SECURITY MIDDLEWARE # ####################### SECURE_BROWSER_XSS_FILTER = False SECURE_CONTENT_TYPE_NOSNIFF = False SECURE_HSTS_INCLUDE_SUBDOMAINS = False SECURE_HSTS_PRELOAD = False SECURE_HSTS_SECONDS = 0 SECURE_REDIRECT_EXEMPT = [] SECURE_SSL_HOST = None SECURE_SSL_REDIRECT = False
1dc102996477771cc611290db9cd34ea4bebff95785defeaa16330b4be8a31af
"Functions that help with dynamically creating decorators for views." try: from contextlib import ContextDecorator except ImportError: ContextDecorator = None from functools import WRAPPER_ASSIGNMENTS, update_wrapper, wraps from django.utils import six class classonlymethod(classmethod): def __get__(self, instance, cls=None): if instance is not None: raise AttributeError("This method is available only on the class, not on instances.") return super(classonlymethod, self).__get__(instance, cls) def method_decorator(decorator, name=''): """ Converts a function decorator into a method decorator """ # 'obj' can be a class or a function. If 'obj' is a function at the time it # is passed to _dec, it will eventually be a method of the class it is # defined on. If 'obj' is a class, the 'name' is required to be the name # of the method that will be decorated. def _dec(obj): is_class = isinstance(obj, type) if is_class: if name and hasattr(obj, name): func = getattr(obj, name) if not callable(func): raise TypeError( "Cannot decorate '{0}' as it isn't a callable " "attribute of {1} ({2})".format(name, obj, func) ) else: raise ValueError( "The keyword argument `name` must be the name of a method " "of the decorated class: {0}. Got '{1}' instead".format( obj, name, ) ) else: func = obj def decorate(function): """ Apply a list/tuple of decorators if decorator is one. Decorator functions are applied so that the call order is the same as the order in which they appear in the iterable. """ if hasattr(decorator, '__iter__'): for dec in decorator[::-1]: function = dec(function) return function return decorator(function) def _wrapper(self, *args, **kwargs): @decorate def bound_func(*args2, **kwargs2): return func.__get__(self, type(self))(*args2, **kwargs2) # bound_func has the signature that 'decorator' expects i.e. no # 'self' argument, but it is a closure over self so it can call # 'func' correctly. return bound_func(*args, **kwargs) # In case 'decorator' adds attributes to the function it decorates, we # want to copy those. We don't have access to bound_func in this scope, # but we can cheat by using it on a dummy function. @decorate def dummy(*args, **kwargs): pass update_wrapper(_wrapper, dummy) # Need to preserve any existing attributes of 'func', including the name. update_wrapper(_wrapper, func) if is_class: setattr(obj, name, _wrapper) return obj return _wrapper # Don't worry about making _dec look similar to a list/tuple as it's rather # meaningless. if not hasattr(decorator, '__iter__'): update_wrapper(_dec, decorator, assigned=available_attrs(decorator)) # Change the name to aid debugging. if hasattr(decorator, '__name__'): _dec.__name__ = 'method_decorator(%s)' % decorator.__name__ else: _dec.__name__ = 'method_decorator(%s)' % decorator.__class__.__name__ return _dec def decorator_from_middleware_with_args(middleware_class): """ Like decorator_from_middleware, but returns a function that accepts the arguments to be passed to the middleware_class. Use like:: cache_page = decorator_from_middleware_with_args(CacheMiddleware) # ... @cache_page(3600) def my_view(request): # ... """ return make_middleware_decorator(middleware_class) def decorator_from_middleware(middleware_class): """ Given a middleware class (not an instance), returns a view decorator. This lets you use middleware functionality on a per-view basis. The middleware is created with no params passed. """ return make_middleware_decorator(middleware_class)() def available_attrs(fn): """ Return the list of functools-wrappable attributes on a callable. This is required as a workaround for http://bugs.python.org/issue3445 under Python 2. """ if six.PY3: return WRAPPER_ASSIGNMENTS else: return tuple(a for a in WRAPPER_ASSIGNMENTS if hasattr(fn, a)) def make_middleware_decorator(middleware_class): def _make_decorator(*m_args, **m_kwargs): middleware = middleware_class(*m_args, **m_kwargs) def _decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if hasattr(middleware, 'process_request'): result = middleware.process_request(request) if result is not None: return result if hasattr(middleware, 'process_view'): result = middleware.process_view(request, view_func, args, kwargs) if result is not None: return result try: response = view_func(request, *args, **kwargs) except Exception as e: if hasattr(middleware, 'process_exception'): result = middleware.process_exception(request, e) if result is not None: return result raise if hasattr(response, 'render') and callable(response.render): if hasattr(middleware, 'process_template_response'): response = middleware.process_template_response(request, response) # Defer running of process_response until after the template # has been rendered: if hasattr(middleware, 'process_response'): def callback(response): return middleware.process_response(request, response) response.add_post_render_callback(callback) else: if hasattr(middleware, 'process_response'): return middleware.process_response(request, response) return response return _wrapped_view return _decorator return _make_decorator if ContextDecorator is None: # ContextDecorator was introduced in Python 3.2 # See https://docs.python.org/3/library/contextlib.html#contextlib.ContextDecorator class ContextDecorator(object): """ A base class that enables a context manager to also be used as a decorator. """ def __call__(self, func): @wraps(func, assigned=available_attrs(func)) def inner(*args, **kwargs): with self: return func(*args, **kwargs) return inner class classproperty(object): def __init__(self, method=None): self.fget = method def __get__(self, instance, cls=None): return self.fget(cls) def getter(self, method): self.fget = method return self
8e68b3214f3c6d0405d7bb9952a4354090c6bc644bbf9c4ad4d685a76aaa6800
# Python's datetime strftime doesn't handle dates before 1900. # These classes override date and datetime to support the formatting of a date # through its full "proleptic Gregorian" date range. # # Based on code submitted to comp.lang.python by Andrew Dalke # # >>> datetime_safe.date(1850, 8, 2).strftime("%Y/%m/%d was a %A") # '1850/08/02 was a Friday' import re import time as ttime from datetime import ( date as real_date, datetime as real_datetime, time as real_time, ) class date(real_date): def strftime(self, fmt): return strftime(self, fmt) class datetime(real_datetime): def strftime(self, fmt): return strftime(self, fmt) @classmethod def combine(cls, date, time): return cls(date.year, date.month, date.day, time.hour, time.minute, time.second, time.microsecond, time.tzinfo) def date(self): return date(self.year, self.month, self.day) class time(real_time): pass def new_date(d): "Generate a safe date from a datetime.date object." return date(d.year, d.month, d.day) def new_datetime(d): """ Generate a safe datetime from a datetime.date or datetime.datetime object. """ kw = [d.year, d.month, d.day] if isinstance(d, real_datetime): kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo]) return datetime(*kw) # This library does not support strftime's "%s" or "%y" format strings. # Allowed if there's an even number of "%"s because they are escaped. _illegal_formatting = re.compile(r"((^|[^%])(%%)*%[sy])") def _findall(text, substr): # Also finds overlaps sites = [] i = 0 while 1: j = text.find(substr, i) if j == -1: break sites.append(j) i = j + 1 return sites def strftime(dt, fmt): if dt.year >= 1900: return super(type(dt), dt).strftime(fmt) illegal_formatting = _illegal_formatting.search(fmt) if illegal_formatting: raise TypeError("strftime of dates before 1900 does not handle" + illegal_formatting.group(0)) year = dt.year # For every non-leap year century, advance by # 6 years to get into the 28-year repeat cycle delta = 2000 - year off = 6 * (delta // 100 + delta // 400) year = year + off # Move to around the year 2000 year = year + ((2000 - year) // 28) * 28 timetuple = dt.timetuple() s1 = ttime.strftime(fmt, (year,) + timetuple[1:]) sites1 = _findall(s1, str(year)) s2 = ttime.strftime(fmt, (year + 28,) + timetuple[1:]) sites2 = _findall(s2, str(year + 28)) sites = [] for site in sites1: if site in sites2: sites.append(site) s = s1 syear = "%04d" % (dt.year,) for site in sites: s = s[:site] + syear + s[site + 4:] return s
abfadb711fd0368e3332161db74a0a701f226e782278898c7b04e9483be4f06e
# Autoreloading launcher. # Borrowed from Peter Hunt and the CherryPy project (http://www.cherrypy.org). # Some taken from Ian Bicking's Paste (http://pythonpaste.org/). # # Portions copyright (c) 2004, CherryPy Team ([email protected]) # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the CherryPy Team nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import signal import sys import time import traceback from django.apps import apps from django.conf import settings from django.core.signals import request_finished from django.utils import six from django.utils._os import npath from django.utils.six.moves import _thread as thread # This import does nothing, but it's necessary to avoid some race conditions # in the threading module. See http://code.djangoproject.com/ticket/2330 . try: import threading # NOQA except ImportError: pass try: import termios except ImportError: termios = None USE_INOTIFY = False try: # Test whether inotify is enabled and likely to work import pyinotify fd = pyinotify.INotifyWrapper.create().inotify_init() if fd >= 0: USE_INOTIFY = True os.close(fd) except ImportError: pass RUN_RELOADER = True FILE_MODIFIED = 1 I18N_MODIFIED = 2 _mtimes = {} _win = (sys.platform == "win32") _exception = None _error_files = [] _cached_modules = set() _cached_filenames = [] def gen_filenames(only_new=False): """ Returns a list of filenames referenced in sys.modules and translation files. """ # N.B. ``list(...)`` is needed, because this runs in parallel with # application code which might be mutating ``sys.modules``, and this will # fail with RuntimeError: cannot mutate dictionary while iterating global _cached_modules, _cached_filenames module_values = set(sys.modules.values()) _cached_filenames = clean_files(_cached_filenames) if _cached_modules == module_values: # No changes in module list, short-circuit the function if only_new: return [] else: return _cached_filenames + clean_files(_error_files) new_modules = module_values - _cached_modules new_filenames = clean_files( [filename.__file__ for filename in new_modules if hasattr(filename, '__file__')]) if not _cached_filenames and settings.USE_I18N: # Add the names of the .mo files that can be generated # by compilemessages management command to the list of files watched. basedirs = [os.path.join(os.path.dirname(os.path.dirname(__file__)), 'conf', 'locale'), 'locale'] for app_config in reversed(list(apps.get_app_configs())): basedirs.append(os.path.join(npath(app_config.path), 'locale')) basedirs.extend(settings.LOCALE_PATHS) basedirs = [os.path.abspath(basedir) for basedir in basedirs if os.path.isdir(basedir)] for basedir in basedirs: for dirpath, dirnames, locale_filenames in os.walk(basedir): for filename in locale_filenames: if filename.endswith('.mo'): new_filenames.append(os.path.join(dirpath, filename)) _cached_modules = _cached_modules.union(new_modules) _cached_filenames += new_filenames if only_new: return new_filenames + clean_files(_error_files) else: return _cached_filenames + clean_files(_error_files) def clean_files(filelist): filenames = [] for filename in filelist: if not filename: continue if filename.endswith(".pyc") or filename.endswith(".pyo"): filename = filename[:-1] if filename.endswith("$py.class"): filename = filename[:-9] + ".py" if os.path.exists(filename): filenames.append(filename) return filenames def reset_translations(): import gettext from django.utils.translation import trans_real gettext._translations = {} trans_real._translations = {} trans_real._default = None trans_real._active = threading.local() def inotify_code_changed(): """ Checks for changed code using inotify. After being called it blocks until a change event has been fired. """ class EventHandler(pyinotify.ProcessEvent): modified_code = None def process_default(self, event): if event.path.endswith('.mo'): EventHandler.modified_code = I18N_MODIFIED else: EventHandler.modified_code = FILE_MODIFIED wm = pyinotify.WatchManager() notifier = pyinotify.Notifier(wm, EventHandler()) def update_watch(sender=None, **kwargs): if sender and getattr(sender, 'handles_files', False): # No need to update watches when request serves files. # (sender is supposed to be a django.core.handlers.BaseHandler subclass) return mask = ( pyinotify.IN_MODIFY | pyinotify.IN_DELETE | pyinotify.IN_ATTRIB | pyinotify.IN_MOVED_FROM | pyinotify.IN_MOVED_TO | pyinotify.IN_CREATE | pyinotify.IN_DELETE_SELF | pyinotify.IN_MOVE_SELF ) for path in gen_filenames(only_new=True): wm.add_watch(path, mask) # New modules may get imported when a request is processed. request_finished.connect(update_watch) # Block until an event happens. update_watch() notifier.check_events(timeout=None) notifier.read_events() notifier.process_events() notifier.stop() # If we are here the code must have changed. return EventHandler.modified_code def code_changed(): global _mtimes, _win for filename in gen_filenames(): stat = os.stat(filename) mtime = stat.st_mtime if _win: mtime -= stat.st_ctime if filename not in _mtimes: _mtimes[filename] = mtime continue if mtime != _mtimes[filename]: _mtimes = {} try: del _error_files[_error_files.index(filename)] except ValueError: pass return I18N_MODIFIED if filename.endswith('.mo') else FILE_MODIFIED return False def check_errors(fn): def wrapper(*args, **kwargs): global _exception try: fn(*args, **kwargs) except Exception: _exception = sys.exc_info() et, ev, tb = _exception if getattr(ev, 'filename', None) is None: # get the filename from the last item in the stack filename = traceback.extract_tb(tb)[-1][0] else: filename = ev.filename if filename not in _error_files: _error_files.append(filename) raise return wrapper def raise_last_exception(): global _exception if _exception is not None: six.reraise(*_exception) def ensure_echo_on(): if termios: fd = sys.stdin if fd.isatty(): attr_list = termios.tcgetattr(fd) if not attr_list[3] & termios.ECHO: attr_list[3] |= termios.ECHO if hasattr(signal, 'SIGTTOU'): old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN) else: old_handler = None termios.tcsetattr(fd, termios.TCSANOW, attr_list) if old_handler is not None: signal.signal(signal.SIGTTOU, old_handler) def reloader_thread(): ensure_echo_on() if USE_INOTIFY: fn = inotify_code_changed else: fn = code_changed while RUN_RELOADER: change = fn() if change == FILE_MODIFIED: sys.exit(3) # force reload elif change == I18N_MODIFIED: reset_translations() time.sleep(1) def restart_with_reloader(): while True: args = [sys.executable] + ['-W%s' % o for o in sys.warnoptions] + sys.argv if sys.platform == "win32": args = ['"%s"' % arg for arg in args] new_environ = os.environ.copy() new_environ["RUN_MAIN"] = 'true' exit_code = os.spawnve(os.P_WAIT, sys.executable, args, new_environ) if exit_code != 3: return exit_code def python_reloader(main_func, args, kwargs): if os.environ.get("RUN_MAIN") == "true": thread.start_new_thread(main_func, args, kwargs) try: reloader_thread() except KeyboardInterrupt: pass else: try: exit_code = restart_with_reloader() if exit_code < 0: os.kill(os.getpid(), -exit_code) else: sys.exit(exit_code) except KeyboardInterrupt: pass def jython_reloader(main_func, args, kwargs): from _systemrestart import SystemRestart thread.start_new_thread(main_func, args) while True: if code_changed(): raise SystemRestart time.sleep(1) def main(main_func, args=None, kwargs=None): if args is None: args = () if kwargs is None: kwargs = {} if sys.platform.startswith('java'): reloader = jython_reloader else: reloader = python_reloader wrapped_main_func = check_errors(main_func) reloader(wrapped_main_func, args, kwargs)
dc32a22287548e78df97b812291e9196beb79d796d59c0aa9d3e95aba522db16
from __future__ import unicode_literals import re import unicodedata from gzip import GzipFile from io import BytesIO from django.utils import six from django.utils.encoding import force_text from django.utils.functional import ( SimpleLazyObject, keep_lazy, keep_lazy_text, lazy, ) from django.utils.safestring import SafeText, mark_safe from django.utils.six.moves import html_entities from django.utils.translation import pgettext, ugettext as _, ugettext_lazy if six.PY2: # Import force_unicode even though this module doesn't use it, because some # people rely on it being here. from django.utils.encoding import force_unicode # NOQA # Capitalizes the first letter of a string. def capfirst(x): return x and force_text(x)[0].upper() + force_text(x)[1:] capfirst = keep_lazy_text(capfirst) # Set up regular expressions re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.U | re.S) re_chars = re.compile(r'<.*?>|(.)', re.U | re.S) re_tag = re.compile(r'<(/)?([^ ]+?)(?:(\s*/)| .*?)?>', re.S) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))') @keep_lazy_text def wrap(text, width): """ A word-wrap function that preserves existing line breaks. Expects that existing line breaks are posix newlines. All white space is preserved except added line breaks consume the space on which they break the line. Long words are not wrapped, so the output text may have lines longer than ``width``. """ text = force_text(text) def _generator(): for line in text.splitlines(True): # True keeps trailing linebreaks max_width = min((line.endswith('\n') and width + 1 or width), width) while len(line) > max_width: space = line[:max_width + 1].rfind(' ') + 1 if space == 0: space = line.find(' ') + 1 if space == 0: yield line line = '' break yield '%s\n' % line[:space - 1] line = line[space:] max_width = min((line.endswith('\n') and width + 1 or width), width) if line: yield line return ''.join(_generator()) class Truncator(SimpleLazyObject): """ An object used to truncate text, either by characters or words. """ def __init__(self, text): super(Truncator, self).__init__(lambda: force_text(text)) def add_truncation_text(self, text, truncate=None): if truncate is None: truncate = pgettext( 'String to return when truncating text', '%(truncated_text)s...') truncate = force_text(truncate) if '%(truncated_text)s' in truncate: return truncate % {'truncated_text': text} # The truncation text didn't contain the %(truncated_text)s string # replacement argument so just append it to the text. if text.endswith(truncate): # But don't append the truncation text if the current text already # ends in this. return text return '%s%s' % (text, truncate) def chars(self, num, truncate=None, html=False): """ Returns the text truncated to be no longer than the specified number of characters. Takes an optional argument of what should be used to notify that the string has been truncated, defaulting to a translatable string of an ellipsis (...). """ self._setup() length = int(num) text = unicodedata.normalize('NFC', self._wrapped) # Calculate the length to truncate to (max length - end_text length) truncate_len = length for char in self.add_truncation_text('', truncate): if not unicodedata.combining(char): truncate_len -= 1 if truncate_len == 0: break if html: return self._truncate_html(length, truncate, text, truncate_len, False) return self._text_chars(length, truncate, text, truncate_len) def _text_chars(self, length, truncate, text, truncate_len): """ Truncates a string after a certain number of chars. """ s_len = 0 end_index = None for i, char in enumerate(text): if unicodedata.combining(char): # Don't consider combining characters # as adding to the string length continue s_len += 1 if end_index is None and s_len > truncate_len: end_index = i if s_len > length: # Return the truncated string return self.add_truncation_text(text[:end_index or 0], truncate) # Return the original string since no truncation was necessary return text def words(self, num, truncate=None, html=False): """ Truncates a string after a certain number of words. Takes an optional argument of what should be used to notify that the string has been truncated, defaulting to ellipsis (...). """ self._setup() length = int(num) if html: return self._truncate_html(length, truncate, self._wrapped, length, True) return self._text_words(length, truncate) def _text_words(self, length, truncate): """ Truncates a string after a certain number of words. Newlines in the string will be stripped. """ words = self._wrapped.split() if len(words) > length: words = words[:length] return self.add_truncation_text(' '.join(words), truncate) return ' '.join(words) def _truncate_html(self, length, truncate, text, truncate_len, words): """ Truncates HTML to a certain number of chars (not counting tags and comments), or, if words is True, then to a certain number of words. Closes opened tags if they were correctly closed in the given HTML. Newlines in the HTML are preserved. """ if words and length <= 0: return '' html4_singlets = ( 'br', 'col', 'link', 'base', 'img', 'param', 'area', 'hr', 'input' ) # Count non-HTML chars/words and keep note of open tags pos = 0 end_text_pos = 0 current_len = 0 open_tags = [] regex = re_words if words else re_chars while current_len <= length: m = regex.search(text, pos) if not m: # Checked through whole string break pos = m.end(0) if m.group(1): # It's an actual non-HTML word or char current_len += 1 if current_len == truncate_len: end_text_pos = pos continue # Check for tag tag = re_tag.match(m.group(0)) if not tag or current_len >= truncate_len: # Don't worry about non tags or tags after our truncate point continue closing_tag, tagname, self_closing = tag.groups() # Element names are always case-insensitive tagname = tagname.lower() if self_closing or tagname in html4_singlets: pass elif closing_tag: # Check for match in open tags list try: i = open_tags.index(tagname) except ValueError: pass else: # SGML: An end tag closes, back to the matching start tag, # all unclosed intervening start tags with omitted end tags open_tags = open_tags[i + 1:] else: # Add it to the start of the open tags list open_tags.insert(0, tagname) if current_len <= length: return text out = text[:end_text_pos] truncate_text = self.add_truncation_text('', truncate) if truncate_text: out += truncate_text # Close any tags still open for tag in open_tags: out += '</%s>' % tag # Return string return out @keep_lazy_text def get_valid_filename(s): """ Returns the given string converted to a string that can be used for a clean filename. Specifically, leading and trailing spaces are removed; other spaces are converted to underscores; and anything that is not a unicode alphanumeric, dash, underscore, or dot, is removed. >>> get_valid_filename("john's portrait in 2004.jpg") 'johns_portrait_in_2004.jpg' """ s = force_text(s).strip().replace(' ', '_') return re.sub(r'(?u)[^-\w.]', '', s) @keep_lazy_text def get_text_list(list_, last_word=ugettext_lazy('or')): """ >>> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c or d' >>> get_text_list(['a', 'b', 'c'], 'and') 'a, b and c' >>> get_text_list(['a', 'b'], 'and') 'a and b' >>> get_text_list(['a']) 'a' >>> get_text_list([]) '' """ if len(list_) == 0: return '' if len(list_) == 1: return force_text(list_[0]) return '%s %s %s' % ( # Translators: This string is used as a separator between list elements _(', ').join(force_text(i) for i in list_[:-1]), force_text(last_word), force_text(list_[-1])) @keep_lazy_text def normalize_newlines(text): """Normalizes CRLF and CR newlines to just LF.""" text = force_text(text) return re_newlines.sub('\n', text) @keep_lazy_text def phone2numeric(phone): """Converts a phone number with letters into its numeric equivalent.""" char2number = { 'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3', 'g': '4', 'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6', 'n': '6', 'o': '6', 'p': '7', 'q': '7', 'r': '7', 's': '7', 't': '8', 'u': '8', 'v': '8', 'w': '9', 'x': '9', 'y': '9', 'z': '9', } return ''.join(char2number.get(c, c) for c in phone.lower()) # From http://www.xhaus.com/alan/python/httpcomp.html#gzip # Used with permission. def compress_string(s): zbuf = BytesIO() with GzipFile(mode='wb', compresslevel=6, fileobj=zbuf, mtime=0) as zfile: zfile.write(s) return zbuf.getvalue() class StreamingBuffer(object): def __init__(self): self.vals = [] def write(self, val): self.vals.append(val) def read(self): if not self.vals: return b'' ret = b''.join(self.vals) self.vals = [] return ret def flush(self): return def close(self): return # Like compress_string, but for iterators of strings. def compress_sequence(sequence): buf = StreamingBuffer() with GzipFile(mode='wb', compresslevel=6, fileobj=buf, mtime=0) as zfile: # Output headers... yield buf.read() for item in sequence: zfile.write(item) data = buf.read() if data: yield data yield buf.read() # Expression to match some_token and some_token="with spaces" (and similarly # for single-quoted strings). smart_split_re = re.compile(r""" ((?: [^\s'"]* (?: (?:"(?:[^"\\]|\\.)*" | '(?:[^'\\]|\\.)*') [^\s'"]* )+ ) | \S+) """, re.VERBOSE) def smart_split(text): r""" Generator that splits a string by spaces, leaving quoted phrases together. Supports both single and double quotes, and supports escaping quotes with backslashes. In the output, strings will keep their initial and trailing quote marks and escaped quotes will remain escaped (the results can then be further processed with unescape_string_literal()). >>> list(smart_split(r'This is "a person\'s" test.')) ['This', 'is', '"a person\\\'s"', 'test.'] >>> list(smart_split(r"Another 'person\'s' test.")) ['Another', "'person\\'s'", 'test.'] >>> list(smart_split(r'A "\"funky\" style" test.')) ['A', '"\\"funky\\" style"', 'test.'] """ text = force_text(text) for bit in smart_split_re.finditer(text): yield bit.group(0) def _replace_entity(match): text = match.group(1) if text[0] == '#': text = text[1:] try: if text[0] in 'xX': c = int(text[1:], 16) else: c = int(text) return six.unichr(c) except ValueError: return match.group(0) else: try: return six.unichr(html_entities.name2codepoint[text]) except (ValueError, KeyError): return match.group(0) _entity_re = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));") @keep_lazy_text def unescape_entities(text): return _entity_re.sub(_replace_entity, force_text(text)) @keep_lazy_text def unescape_string_literal(s): r""" Convert quoted string literals to unquoted strings with escaped quotes and backslashes unquoted:: >>> unescape_string_literal('"abc"') 'abc' >>> unescape_string_literal("'abc'") 'abc' >>> unescape_string_literal('"a \"bc\""') 'a "bc"' >>> unescape_string_literal("'\'ab\' c'") "'ab' c" """ if s[0] not in "\"'" or s[-1] != s[0]: raise ValueError("Not a string literal: %r" % s) quote = s[0] return s[1:-1].replace(r'\%s' % quote, quote).replace(r'\\', '\\') @keep_lazy(six.text_type, SafeText) def slugify(value, allow_unicode=False): """ Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace. """ value = force_text(value) if allow_unicode: value = unicodedata.normalize('NFKC', value) value = re.sub(r'[^\w\s-]', '', value, flags=re.U).strip().lower() return mark_safe(re.sub(r'[-\s]+', '-', value, flags=re.U)) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii') value = re.sub(r'[^\w\s-]', '', value).strip().lower() return mark_safe(re.sub(r'[-\s]+', '-', value)) def camel_case_to_spaces(value): """ Splits CamelCase and converts to lower case. Also strips leading and trailing whitespace. """ return re_camel_case.sub(r' \1', value).strip().lower() def _format_lazy(format_string, *args, **kwargs): """ Apply str.format() on 'format_string' where format_string, args, and/or kwargs might be lazy. """ return format_string.format(*args, **kwargs) format_lazy = lazy(_format_lazy, six.text_type)
9ee470e30a45b8820ef25bc949ab0ed860b0be957ca728401d387b1955929e74
"""Functions to parse datetime objects.""" # We're using regular expressions rather than time.strptime because: # - They provide both validation and parsing. # - They're more flexible for datetimes. # - The date/datetime/time constructors produce friendlier error messages. import datetime import re from django.utils import six from django.utils.timezone import get_fixed_timezone, utc date_re = re.compile( r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$' ) time_re = re.compile( r'(?P<hour>\d{1,2}):(?P<minute>\d{1,2})' r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?' ) datetime_re = re.compile( r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})' r'[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})' r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?' r'(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$' ) standard_duration_re = re.compile( r'^' r'(?:(?P<days>-?\d+) (days?, )?)?' r'((?:(?P<hours>\d+):)(?=\d+:\d+))?' r'(?:(?P<minutes>\d+):)?' r'(?P<seconds>\d+)' r'(?:\.(?P<microseconds>\d{1,6})\d{0,6})?' r'$' ) # Support the sections of ISO 8601 date representation that are accepted by # timedelta iso8601_duration_re = re.compile( r'^(?P<sign>[-+]?)' r'P' r'(?:(?P<days>\d+(.\d+)?)D)?' r'(?:T' r'(?:(?P<hours>\d+(.\d+)?)H)?' r'(?:(?P<minutes>\d+(.\d+)?)M)?' r'(?:(?P<seconds>\d+(.\d+)?)S)?' r')?' r'$' ) def parse_date(value): """Parses a string and return a datetime.date. Raises ValueError if the input is well formatted but not a valid date. Returns None if the input isn't well formatted. """ match = date_re.match(value) if match: kw = {k: int(v) for k, v in six.iteritems(match.groupdict())} return datetime.date(**kw) def parse_time(value): """Parses a string and return a datetime.time. This function doesn't support time zone offsets. Raises ValueError if the input is well formatted but not a valid time. Returns None if the input isn't well formatted, in particular if it contains an offset. """ match = time_re.match(value) if match: kw = match.groupdict() if kw['microsecond']: kw['microsecond'] = kw['microsecond'].ljust(6, '0') kw = {k: int(v) for k, v in six.iteritems(kw) if v is not None} return datetime.time(**kw) def parse_datetime(value): """Parses a string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raises ValueError if the input is well formatted but not a valid datetime. Returns None if the input isn't well formatted. """ match = datetime_re.match(value) if match: kw = match.groupdict() if kw['microsecond']: kw['microsecond'] = kw['microsecond'].ljust(6, '0') tzinfo = kw.pop('tzinfo') if tzinfo == 'Z': tzinfo = utc elif tzinfo is not None: offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0 offset = 60 * int(tzinfo[1:3]) + offset_mins if tzinfo[0] == '-': offset = -offset tzinfo = get_fixed_timezone(offset) kw = {k: int(v) for k, v in six.iteritems(kw) if v is not None} kw['tzinfo'] = tzinfo return datetime.datetime(**kw) def parse_duration(value): """Parses a duration string and returns a datetime.timedelta. The preferred format for durations in Django is '%d %H:%M:%S.%f'. Also supports ISO 8601 representation. """ match = standard_duration_re.match(value) if not match: match = iso8601_duration_re.match(value) if match: kw = match.groupdict() sign = -1 if kw.pop('sign', '+') == '-' else 1 if kw.get('microseconds'): kw['microseconds'] = kw['microseconds'].ljust(6, '0') kw = {k: float(v) for k, v in six.iteritems(kw) if v is not None} return sign * datetime.timedelta(**kw)
e80f74685cb9f967d83da339fecc6a3eb0d0d14809102609a32b5f21c5ce7c5f
""" Utilities for XML generation/parsing. """ import re from xml.sax.saxutils import XMLGenerator class UnserializableContentError(ValueError): pass class SimplerXMLGenerator(XMLGenerator): def addQuickElement(self, name, contents=None, attrs=None): "Convenience method for adding an element with no children" if attrs is None: attrs = {} self.startElement(name, attrs) if contents is not None: self.characters(contents) self.endElement(name) def characters(self, content): if content and re.search(r'[\x00-\x08\x0B-\x0C\x0E-\x1F]', content): # Fail loudly when content has control chars (unsupported in XML 1.0) # See http://www.w3.org/International/questions/qa-controls raise UnserializableContentError("Control characters are not supported in XML 1.0") XMLGenerator.characters(self, content)
88d2d7ab89f045d820f3d1b7a2f6a574ac59cead0dad30337f7e9b91f3191617
from __future__ import unicode_literals from decimal import Decimal from django.conf import settings from django.utils import six from django.utils.safestring import mark_safe def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', force_grouping=False): """ Gets a number (as a number or string), and returns it as a string, using formats defined as arguments: * decimal_sep: Decimal separator symbol (for example ".") * decimal_pos: Number of decimal positions * grouping: Number of digits in every group limited by thousand separator. For non-uniform digit grouping, it can be a sequence with the number of digit group sizes following the format used by the Python locale module in locale.localeconv() LC_NUMERIC grouping (e.g. (3, 2, 0)). * thousand_sep: Thousand separator symbol (for example ",") """ use_grouping = settings.USE_L10N and settings.USE_THOUSAND_SEPARATOR use_grouping = use_grouping or force_grouping use_grouping = use_grouping and grouping != 0 # Make the common case fast if isinstance(number, int) and not use_grouping and not decimal_pos: return mark_safe(six.text_type(number)) # sign sign = '' if isinstance(number, Decimal): str_number = '{:f}'.format(number) else: str_number = six.text_type(number) if str_number[0] == '-': sign = '-' str_number = str_number[1:] # decimal part if '.' in str_number: int_part, dec_part = str_number.split('.') if decimal_pos is not None: dec_part = dec_part[:decimal_pos] else: int_part, dec_part = str_number, '' if decimal_pos is not None: dec_part = dec_part + ('0' * (decimal_pos - len(dec_part))) if dec_part: dec_part = decimal_sep + dec_part # grouping if use_grouping: try: # if grouping is a sequence intervals = list(grouping) except TypeError: # grouping is a single value intervals = [grouping, 0] active_interval = intervals.pop(0) int_part_gd = '' cnt = 0 for digit in int_part[::-1]: if cnt and cnt == active_interval: if intervals: active_interval = intervals.pop(0) or active_interval int_part_gd += thousand_sep[::-1] cnt = 0 int_part_gd += digit cnt += 1 int_part = int_part_gd[::-1] return sign + int_part + dec_part
fef875fd4d0a366df11f76e3acbe8621298ca3bede27ab44cc4fe1a1d11abe02
from __future__ import unicode_literals import datetime import os import subprocess from django.utils.lru_cache import lru_cache def get_version(version=None): "Returns a PEP 440-compliant version number from VERSION." version = get_complete_version(version) # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|rc}N - for alpha, beta, and rc releases main = get_main_version(version) sub = '' if version[3] == 'alpha' and version[4] == 0: git_changeset = get_git_changeset() if git_changeset: sub = '.dev%s' % git_changeset elif version[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'rc'} sub = mapping[version[3]] + str(version[4]) return str(main + sub) def get_main_version(version=None): "Returns main version (X.Y[.Z]) from VERSION." version = get_complete_version(version) parts = 2 if version[2] == 0 else 3 return '.'.join(str(x) for x in version[:parts]) def get_complete_version(version=None): """Returns a tuple of the django version. If version argument is non-empty, then checks for correctness of the tuple provided. """ if version is None: from django import VERSION as version else: assert len(version) == 5 assert version[3] in ('alpha', 'beta', 'rc', 'final') return version def get_docs_version(version=None): version = get_complete_version(version) if version[3] != 'final': return 'dev' else: return '%d.%d' % version[:2] @lru_cache() def get_git_changeset(): """Returns a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the development version numbers. """ repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) git_log = subprocess.Popen( 'git log --pretty=format:%ct --quiet -1 HEAD', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=repo_dir, universal_newlines=True, ) timestamp = git_log.communicate()[0] try: timestamp = datetime.datetime.utcfromtimestamp(int(timestamp)) except ValueError: return None return timestamp.strftime('%Y%m%d%H%M%S')
e635d91a94468a56974862b36b1819bd989d0e670096dc50a69e1189b0b16d54
""" Timezone-related classes and functions. """ from datetime import datetime, timedelta, tzinfo from threading import local import pytz from django.conf import settings from django.utils import lru_cache, six from django.utils.decorators import ContextDecorator __all__ = [ 'utc', 'get_fixed_timezone', 'get_default_timezone', 'get_default_timezone_name', 'get_current_timezone', 'get_current_timezone_name', 'activate', 'deactivate', 'override', 'localtime', 'now', 'is_aware', 'is_naive', 'make_aware', 'make_naive', ] # UTC and local time zones ZERO = timedelta(0) class FixedOffset(tzinfo): """ Fixed offset in minutes east from UTC. Taken from Python's docs. Kept as close as possible to the reference version. __init__ was changed to make its arguments optional, according to Python's requirement that tzinfo subclasses can be instantiated without arguments. """ def __init__(self, offset=None, name=None): if offset is not None: self.__offset = timedelta(minutes=offset) if name is not None: self.__name = name def utcoffset(self, dt): return self.__offset def tzname(self, dt): return self.__name def dst(self, dt): return ZERO utc = pytz.utc """UTC time zone as a tzinfo instance.""" def get_fixed_timezone(offset): """ Returns a tzinfo instance with a fixed offset from UTC. """ if isinstance(offset, timedelta): offset = offset.seconds // 60 sign = '-' if offset < 0 else '+' hhmm = '%02d%02d' % divmod(abs(offset), 60) name = sign + hhmm return FixedOffset(offset, name) # In order to avoid accessing settings at compile time, # wrap the logic in a function and cache the result. @lru_cache.lru_cache() def get_default_timezone(): """ Returns the default time zone as a tzinfo instance. This is the time zone defined by settings.TIME_ZONE. """ return pytz.timezone(settings.TIME_ZONE) # This function exists for consistency with get_current_timezone_name def get_default_timezone_name(): """ Returns the name of the default time zone. """ return _get_timezone_name(get_default_timezone()) _active = local() def get_current_timezone(): """ Returns the currently active time zone as a tzinfo instance. """ return getattr(_active, "value", get_default_timezone()) def get_current_timezone_name(): """ Returns the name of the currently active time zone. """ return _get_timezone_name(get_current_timezone()) def _get_timezone_name(timezone): """ Returns the name of ``timezone``. """ try: # for pytz timezones return timezone.zone except AttributeError: # for regular tzinfo objects return timezone.tzname(None) # Timezone selection functions. # These functions don't change os.environ['TZ'] and call time.tzset() # because it isn't thread safe. def activate(timezone): """ Sets the time zone for the current thread. The ``timezone`` argument must be an instance of a tzinfo subclass or a time zone name. """ if isinstance(timezone, tzinfo): _active.value = timezone elif isinstance(timezone, six.string_types): _active.value = pytz.timezone(timezone) else: raise ValueError("Invalid timezone: %r" % timezone) def deactivate(): """ Unsets the time zone for the current thread. Django will then use the time zone defined by settings.TIME_ZONE. """ if hasattr(_active, "value"): del _active.value class override(ContextDecorator): """ Temporarily set the time zone for the current thread. This is a context manager that uses ``~django.utils.timezone.activate()`` to set the timezone on entry, and restores the previously active timezone on exit. The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a time zone name, or ``None``. If it is ``None``, Django enables the default time zone. """ def __init__(self, timezone): self.timezone = timezone def __enter__(self): self.old_timezone = getattr(_active, 'value', None) if self.timezone is None: deactivate() else: activate(self.timezone) def __exit__(self, exc_type, exc_value, traceback): if self.old_timezone is None: deactivate() else: _active.value = self.old_timezone # Templates def template_localtime(value, use_tz=None): """ Checks if value is a datetime and converts it to local time if necessary. If use_tz is provided and is not None, that will force the value to be converted (or not), overriding the value of settings.USE_TZ. This function is designed for use by the template engine. """ should_convert = ( isinstance(value, datetime) and (settings.USE_TZ if use_tz is None else use_tz) and not is_naive(value) and getattr(value, 'convert_to_local_time', True) ) return localtime(value) if should_convert else value # Utilities def localtime(value=None, timezone=None): """ Converts an aware datetime.datetime to local time. Only aware datetimes are allowed. When value is omitted, it defaults to now(). Local time is defined by the current time zone, unless another time zone is specified. """ if value is None: value = now() if timezone is None: timezone = get_current_timezone() # Emulate the behavior of astimezone() on Python < 3.6. if is_naive(value): raise ValueError("localtime() cannot be applied to a naive datetime") value = value.astimezone(timezone) if hasattr(timezone, 'normalize'): # This method is available for pytz time zones. value = timezone.normalize(value) return value def localdate(value=None, timezone=None): """ Convert an aware datetime to local time and return the value's date. Only aware datetimes are allowed. When value is omitted, it defaults to now(). Local time is defined by the current time zone, unless another time zone is specified. """ return localtime(value, timezone).date() def now(): """ Returns an aware or naive datetime.datetime, depending on settings.USE_TZ. """ if settings.USE_TZ: # timeit shows that datetime.now(tz=utc) is 24% slower return datetime.utcnow().replace(tzinfo=utc) else: return datetime.now() # By design, these four functions don't perform any checks on their arguments. # The caller should ensure that they don't receive an invalid value like None. def is_aware(value): """ Determines if a given datetime.datetime is aware. The concept is defined in Python's docs: http://docs.python.org/library/datetime.html#datetime.tzinfo Assuming value.tzinfo is either None or a proper datetime.tzinfo, value.utcoffset() implements the appropriate logic. """ return value.utcoffset() is not None def is_naive(value): """ Determines if a given datetime.datetime is naive. The concept is defined in Python's docs: http://docs.python.org/library/datetime.html#datetime.tzinfo Assuming value.tzinfo is either None or a proper datetime.tzinfo, value.utcoffset() implements the appropriate logic. """ return value.utcoffset() is None def make_aware(value, timezone=None, is_dst=None): """ Makes a naive datetime.datetime in a given time zone aware. """ if timezone is None: timezone = get_current_timezone() if hasattr(timezone, 'localize'): # This method is available for pytz time zones. return timezone.localize(value, is_dst=is_dst) else: # Check that we won't overwrite the timezone of an aware datetime. if is_aware(value): raise ValueError( "make_aware expects a naive datetime, got %s" % value) # This may be wrong around DST changes! return value.replace(tzinfo=timezone) def make_naive(value, timezone=None): """ Makes an aware datetime.datetime naive in a given time zone. """ if timezone is None: timezone = get_current_timezone() # Emulate the behavior of astimezone() on Python < 3.6. if is_naive(value): raise ValueError("make_naive() cannot be applied to a naive datetime") value = value.astimezone(timezone) if hasattr(timezone, 'normalize'): # This method is available for pytz time zones. value = timezone.normalize(value) return value.replace(tzinfo=None)
f353bb71cda28ba926a59e1a27d297e4379c77b033c18b997fa9558112dccaca
""" A class for storing a tree graph. Primarily used for filter constructs in the ORM. """ import copy from django.utils.encoding import force_str, force_text class Node(object): """ A single internal node in the tree graph. A Node should be viewed as a connection (the root) with the children being either leaf nodes or other Node instances. """ # Standard connector type. Clients usually won't use this at all and # subclasses will usually override the value. default = 'DEFAULT' def __init__(self, children=None, connector=None, negated=False): """ Constructs a new Node. If no connector is given, the default will be used. """ self.children = children[:] if children else [] self.connector = connector or self.default self.negated = negated # We need this because of django.db.models.query_utils.Q. Q. __init__() is # problematic, but it is a natural Node subclass in all other respects. @classmethod def _new_instance(cls, children=None, connector=None, negated=False): """ This is called to create a new instance of this class when we need new Nodes (or subclasses) in the internal code in this class. Normally, it just shadows __init__(). However, subclasses with an __init__ signature that is not an extension of Node.__init__ might need to implement this method to allow a Node to create a new instance of them (if they have any extra setting up to do). """ obj = Node(children, connector, negated) obj.__class__ = cls return obj def __str__(self): template = '(NOT (%s: %s))' if self.negated else '(%s: %s)' return force_str(template % (self.connector, ', '.join(force_text(c) for c in self.children))) def __repr__(self): return str("<%s: %s>") % (self.__class__.__name__, self) def __deepcopy__(self, memodict): """ Utility method used by copy.deepcopy(). """ obj = Node(connector=self.connector, negated=self.negated) obj.__class__ = self.__class__ obj.children = copy.deepcopy(self.children, memodict) return obj def __len__(self): """ The size of a node if the number of children it has. """ return len(self.children) def __bool__(self): """ For truth value testing. """ return bool(self.children) def __nonzero__(self): # Python 2 compatibility return type(self).__bool__(self) def __contains__(self, other): """ Returns True is 'other' is a direct child of this instance. """ return other in self.children def add(self, data, conn_type, squash=True): """ Combines this tree and the data represented by data using the connector conn_type. The combine is done by squashing the node other away if possible. This tree (self) will never be pushed to a child node of the combined tree, nor will the connector or negated properties change. The function returns a node which can be used in place of data regardless if the node other got squashed or not. If `squash` is False the data is prepared and added as a child to this tree without further logic. """ if data in self.children: return data if not squash: self.children.append(data) return data if self.connector == conn_type: # We can reuse self.children to append or squash the node other. if (isinstance(data, Node) and not data.negated and (data.connector == conn_type or len(data) == 1)): # We can squash the other node's children directly into this # node. We are just doing (AB)(CD) == (ABCD) here, with the # addition that if the length of the other node is 1 the # connector doesn't matter. However, for the len(self) == 1 # case we don't want to do the squashing, as it would alter # self.connector. self.children.extend(data.children) return self else: # We could use perhaps additional logic here to see if some # children could be used for pushdown here. self.children.append(data) return data else: obj = self._new_instance(self.children, self.connector, self.negated) self.connector = conn_type self.children = [obj, data] return data def negate(self): """ Negate the sense of the root connector. """ self.negated = not self.negated
67578e92e37eed3583a5f99508498d83620cb9e39fa7b88cc566731bbc94bcea
from __future__ import absolute_import import inspect import warnings class RemovedInDjango20Warning(DeprecationWarning): pass class RemovedInDjango21Warning(PendingDeprecationWarning): pass RemovedInNextVersionWarning = RemovedInDjango20Warning class warn_about_renamed_method(object): def __init__(self, class_name, old_method_name, new_method_name, deprecation_warning): self.class_name = class_name self.old_method_name = old_method_name self.new_method_name = new_method_name self.deprecation_warning = deprecation_warning def __call__(self, f): def wrapped(*args, **kwargs): warnings.warn( "`%s.%s` is deprecated, use `%s` instead." % (self.class_name, self.old_method_name, self.new_method_name), self.deprecation_warning, 2) return f(*args, **kwargs) return wrapped class RenameMethodsBase(type): """ Handles the deprecation paths when renaming a method. It does the following: 1) Define the new method if missing and complain about it. 2) Define the old method if missing. 3) Complain whenever an old method is called. See #15363 for more details. """ renamed_methods = () def __new__(cls, name, bases, attrs): new_class = super(RenameMethodsBase, cls).__new__(cls, name, bases, attrs) for base in inspect.getmro(new_class): class_name = base.__name__ for renamed_method in cls.renamed_methods: old_method_name = renamed_method[0] old_method = base.__dict__.get(old_method_name) new_method_name = renamed_method[1] new_method = base.__dict__.get(new_method_name) deprecation_warning = renamed_method[2] wrapper = warn_about_renamed_method(class_name, *renamed_method) # Define the new method if missing and complain about it if not new_method and old_method: warnings.warn( "`%s.%s` method should be renamed `%s`." % (class_name, old_method_name, new_method_name), deprecation_warning, 2) setattr(base, new_method_name, old_method) setattr(base, old_method_name, wrapper(old_method)) # Define the old method as a wrapped call to the new method. if not old_method and new_method: setattr(base, old_method_name, wrapper(new_method)) return new_class class DeprecationInstanceCheck(type): def __instancecheck__(self, instance): warnings.warn( "`%s` is deprecated, use `%s` instead." % (self.__name__, self.alternative), self.deprecation_warning, 2 ) return super(DeprecationInstanceCheck, self).__instancecheck__(instance) class CallableBool: """ An boolean-like object that is also callable for backwards compatibility. """ do_not_call_in_templates = True def __init__(self, value): self.value = value def __bool__(self): return self.value def __call__(self): warnings.warn( "Using user.is_authenticated() and user.is_anonymous() as a method " "is deprecated. Remove the parentheses to use it as an attribute.", RemovedInDjango20Warning, stacklevel=2 ) return self.value def __nonzero__(self): # Python 2 compatibility return self.value def __repr__(self): return 'CallableBool(%r)' % self.value def __eq__(self, other): return self.value == other def __ne__(self, other): return self.value != other def __or__(self, other): return bool(self.value or other) def __hash__(self): return hash(self.value) CallableFalse = CallableBool(False) CallableTrue = CallableBool(True) class MiddlewareMixin(object): def __init__(self, get_response=None): self.get_response = get_response super(MiddlewareMixin, self).__init__() def __call__(self, request): response = None if hasattr(self, 'process_request'): response = self.process_request(request) if not response: response = self.get_response(request) if hasattr(self, 'process_response'): response = self.process_response(request, response) return response
0bf4215f4667415885ebc60262c9386e76296418822b164752a06f5b20dd52f5
# -*- encoding: utf-8 -*- from __future__ import unicode_literals import codecs import datetime import locale from decimal import Decimal from django.utils import six from django.utils.functional import Promise from django.utils.six.moves.urllib.parse import quote, unquote if six.PY3: from urllib.parse import unquote_to_bytes class DjangoUnicodeDecodeError(UnicodeDecodeError): def __init__(self, obj, *args): self.obj = obj UnicodeDecodeError.__init__(self, *args) def __str__(self): original = UnicodeDecodeError.__str__(self) return '%s. You passed in %r (%s)' % (original, self.obj, type(self.obj)) # For backwards compatibility. (originally in Django, then added to six 1.9) python_2_unicode_compatible = six.python_2_unicode_compatible def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'): """ Returns a text object representing 's' -- unicode on Python 2 and str on Python 3. Treats bytestrings using the 'encoding' codec. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, Promise): # The input is the result of a gettext_lazy() call. return s return force_text(s, encoding, strings_only, errors) _PROTECTED_TYPES = six.integer_types + ( type(None), float, Decimal, datetime.datetime, datetime.date, datetime.time ) def is_protected_type(obj): """Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_text(strings_only=True). """ return isinstance(obj, _PROTECTED_TYPES) def force_text(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_text, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first for performance reasons. if issubclass(type(s), six.text_type): return s if strings_only and is_protected_type(s): return s try: if not issubclass(type(s), six.string_types): if six.PY3: if isinstance(s, bytes): s = six.text_type(s, encoding, errors) else: s = six.text_type(s) elif hasattr(s, '__unicode__'): s = six.text_type(s) else: s = six.text_type(bytes(s), encoding, errors) else: # Note: We use .decode() here, instead of six.text_type(s, encoding, # errors), so that if s is a SafeBytes, it ends up being a # SafeText at the end. s = s.decode(encoding, errors) except UnicodeDecodeError as e: if not isinstance(s, Exception): raise DjangoUnicodeDecodeError(s, *e.args) else: # If we get to here, the caller has passed in an Exception # subclass populated with non-ASCII bytestring data without a # working unicode method. Try to handle this without raising a # further exception by individually forcing the exception args # to unicode. s = ' '.join(force_text(arg, encoding, strings_only, errors) for arg in s) return s def smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict'): """ Returns a bytestring version of 's', encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, Promise): # The input is the result of a gettext_lazy() call. return s return force_bytes(s, encoding, strings_only, errors) def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first for performance reasons. if isinstance(s, bytes): if encoding == 'utf-8': return s else: return s.decode('utf-8', errors).encode(encoding, errors) if strings_only and is_protected_type(s): return s if isinstance(s, six.memoryview): return bytes(s) if isinstance(s, Promise): return six.text_type(s).encode(encoding, errors) if not isinstance(s, six.string_types): try: if six.PY3: return six.text_type(s).encode(encoding) else: return bytes(s) except UnicodeEncodeError: if isinstance(s, Exception): # An Exception subclass containing non-ASCII data that doesn't # know how to print itself properly. We shouldn't raise a # further exception. return b' '.join(force_bytes(arg, encoding, strings_only, errors) for arg in s) return six.text_type(s).encode(encoding, errors) else: return s.encode(encoding, errors) if six.PY3: smart_str = smart_text force_str = force_text else: smart_str = smart_bytes force_str = force_bytes # backwards compatibility for Python 2 smart_unicode = smart_text force_unicode = force_text smart_str.__doc__ = """ Apply smart_text in Python 3 and smart_bytes in Python 2. This is suitable for writing to sys.stdout (for instance). """ force_str.__doc__ = """ Apply force_text in Python 3 and force_bytes in Python 2. """ def iri_to_uri(iri): """ Convert an Internationalized Resource Identifier (IRI) portion to a URI portion that is suitable for inclusion in a URL. This is the algorithm from section 3.1 of RFC 3987. However, since we are assuming input is either UTF-8 or unicode already, we can simplify things a little from the full method. Takes an IRI in UTF-8 bytes (e.g. '/I \xe2\x99\xa5 Django/') or unicode (e.g. '/I ♥ Django/') and returns ASCII bytes containing the encoded result (e.g. '/I%20%E2%99%A5%20Django/'). """ # The list of safe characters here is constructed from the "reserved" and # "unreserved" characters specified in sections 2.2 and 2.3 of RFC 3986: # reserved = gen-delims / sub-delims # gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" # sub-delims = "!" / "$" / "&" / "'" / "(" / ")" # / "*" / "+" / "," / ";" / "=" # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" # Of the unreserved characters, urllib.quote already considers all but # the ~ safe. # The % character is also added to the list of safe characters here, as the # end of section 3.1 of RFC 3987 specifically mentions that % must not be # converted. if iri is None: return iri return quote(force_bytes(iri), safe=b"/#%[]=:;$&()+,!?*@'~") def uri_to_iri(uri): """ Converts a Uniform Resource Identifier(URI) into an Internationalized Resource Identifier(IRI). This is the algorithm from section 3.2 of RFC 3987. Takes an URI in ASCII bytes (e.g. '/I%20%E2%99%A5%20Django/') and returns unicode containing the encoded result (e.g. '/I \xe2\x99\xa5 Django/'). """ if uri is None: return uri uri = force_bytes(uri) iri = unquote_to_bytes(uri) if six.PY3 else unquote(uri) return repercent_broken_unicode(iri).decode('utf-8') def escape_uri_path(path): """ Escape the unsafe characters from the path portion of a Uniform Resource Identifier (URI). """ # These are the "reserved" and "unreserved" characters specified in # sections 2.2 and 2.3 of RFC 2396: # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," # unreserved = alphanum | mark # mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" # The list of safe characters here is constructed subtracting ";", "=", # and "?" according to section 3.3 of RFC 2396. # The reason for not subtracting and escaping "/" is that we are escaping # the entire path, not a path segment. return quote(force_bytes(path), safe=b"/:@&+$,-_.!~*'()") def repercent_broken_unicode(path): """ As per section 3.2 of RFC 3987, step three of converting a URI into an IRI, we need to re-percent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ try: path.decode('utf-8') except UnicodeDecodeError as e: repercent = quote(path[e.start:e.end], safe=b"/#%[]=:;$&()+,!?*@'~") path = repercent_broken_unicode( path[:e.start] + force_bytes(repercent) + path[e.end:]) return path def filepath_to_uri(path): """Convert a file system path to a URI portion that is suitable for inclusion in a URL. We are assuming input is either UTF-8 or unicode already. This method will encode certain chars that would normally be recognized as special chars for URIs. Note that this method does not encode the ' character, as it is a valid character within URIs. See encodeURIComponent() JavaScript function for more details. Returns an ASCII string containing the encoded result. """ if path is None: return path # I know about `os.sep` and `os.altsep` but I want to leave # some flexibility for hardcoding separators. return quote(force_bytes(path).replace(b"\\", b"/"), safe=b"/~!*()'") def get_system_encoding(): """ The encoding of the default system locale but falls back to the given fallback encoding if the encoding is unsupported by python or could not be determined. See tickets #10335 and #5846 """ try: encoding = locale.getdefaultlocale()[1] or 'ascii' codecs.lookup(encoding) except Exception: encoding = 'ascii' return encoding DEFAULT_LOCALE_ENCODING = get_system_encoding()
e06307043c04e46bea359500bbcab1b11c09e07d33c06a05b07c43c733fcb18b
""" Django's standard crypto functions and utilities. """ from __future__ import unicode_literals import binascii import hashlib import hmac import random import struct import time from django.conf import settings from django.utils import six from django.utils.encoding import force_bytes from django.utils.six.moves import range # Use the system PRNG if possible try: random = random.SystemRandom() using_sysrandom = True except NotImplementedError: import warnings warnings.warn('A secure pseudo-random number generator is not available ' 'on your system. Falling back to Mersenne Twister.') using_sysrandom = False def salted_hmac(key_salt, value, secret=None): """ Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a secret (which defaults to settings.SECRET_KEY). A different key_salt should be passed in for every application of HMAC. """ if secret is None: secret = settings.SECRET_KEY key_salt = force_bytes(key_salt) secret = force_bytes(secret) # We need to generate a derived key from our base key. We can do this by # passing the key_salt and our base key through a pseudo-random function and # SHA1 works nicely. key = hashlib.sha1(key_salt + secret).digest() # If len(key_salt + secret) > sha_constructor().block_size, the above # line is redundant and could be replaced by key = key_salt + secret, since # the hmac module does the same thing for keys longer than the block size. # However, we need to ensure that we *always* do this. return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1) def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): """ Returns a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits """ if not using_sysrandom: # This is ugly, and a hack, but it makes things better than # the alternative of predictability. This re-seeds the PRNG # using a value that is hard for an attacker to predict, every # time a random string is required. This may change the # properties of the chosen random sequence slightly, but this # is better than absolute predictability. random.seed( hashlib.sha256( ("%s%s%s" % ( random.getstate(), time.time(), settings.SECRET_KEY)).encode('utf-8') ).digest()) return ''.join(random.choice(allowed_chars) for i in range(length)) if hasattr(hmac, "compare_digest"): # Prefer the stdlib implementation, when available. def constant_time_compare(val1, val2): return hmac.compare_digest(force_bytes(val1), force_bytes(val2)) else: def constant_time_compare(val1, val2): """ Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. For the sake of simplicity, this function executes in constant time only when the two strings have the same length. It short-circuits when they have different lengths. Since Django only uses it to compare hashes of known expected length, this is acceptable. """ if len(val1) != len(val2): return False result = 0 if six.PY3 and isinstance(val1, bytes) and isinstance(val2, bytes): for x, y in zip(val1, val2): result |= x ^ y else: for x, y in zip(val1, val2): result |= ord(x) ^ ord(y) return result == 0 def _bin_to_long(x): """ Convert a binary string into a long integer This is a clever optimization for fast xor vector math """ return int(binascii.hexlify(x), 16) def _long_to_bin(x, hex_format_string): """ Convert a long integer into a binary string. hex_format_string is like "%020x" for padding 10 characters. """ return binascii.unhexlify((hex_format_string % x).encode('ascii')) if hasattr(hashlib, "pbkdf2_hmac"): def pbkdf2(password, salt, iterations, dklen=0, digest=None): """ Implements PBKDF2 with the same API as Django's existing implementation, using the stdlib. This is used in Python 2.7.8+ and 3.4+. """ if digest is None: digest = hashlib.sha256 if not dklen: dklen = None password = force_bytes(password) salt = force_bytes(salt) return hashlib.pbkdf2_hmac( digest().name, password, salt, iterations, dklen) else: def pbkdf2(password, salt, iterations, dklen=0, digest=None): """ Implements PBKDF2 as defined in RFC 2898, section 5.2 HMAC+SHA256 is used as the default pseudo random function. As of 2014, 100,000 iterations was the recommended default which took 100ms on a 2.7Ghz Intel i7 with an optimized implementation. This is probably the bare minimum for security given 1000 iterations was recommended in 2001. This code is very well optimized for CPython and is about five times slower than OpenSSL's implementation. Look in django.contrib.auth.hashers for the present default, it is lower than the recommended 100,000 because of the performance difference between this and an optimized implementation. """ assert iterations > 0 if not digest: digest = hashlib.sha256 password = force_bytes(password) salt = force_bytes(salt) hlen = digest().digest_size if not dklen: dklen = hlen if dklen > (2 ** 32 - 1) * hlen: raise OverflowError('dklen too big') l = -(-dklen // hlen) r = dklen - (l - 1) * hlen hex_format_string = "%%0%ix" % (hlen * 2) inner, outer = digest(), digest() if len(password) > inner.block_size: password = digest(password).digest() password += b'\x00' * (inner.block_size - len(password)) inner.update(password.translate(hmac.trans_36)) outer.update(password.translate(hmac.trans_5C)) def F(i): u = salt + struct.pack(b'>I', i) result = 0 for j in range(int(iterations)): dig1, dig2 = inner.copy(), outer.copy() dig1.update(u) dig2.update(dig1.digest()) u = dig2.digest() result ^= _bin_to_long(u) return _long_to_bin(result, hex_format_string) T = [F(x) for x in range(1, l)] return b''.join(T) + F(l)[:r]
69c5f9fdc9207da4cd831f40c9a8fe8b326e8d6e315a823e392907e6c6664b0a
""" Functions for reversing a regular expression (used in reverse URL resolving). Used internally by Django and not intended for external use. This is not, and is not intended to be, a complete reg-exp decompiler. It should be good enough for a large class of URLS, however. """ from __future__ import unicode_literals from django.utils import six from django.utils.six.moves import zip # Mapping of an escape character to a representative of that class. So, e.g., # "\w" is replaced by "x" in a reverse URL. A value of None means to ignore # this sequence. Any missing key is mapped to itself. ESCAPE_MAPPINGS = { "A": None, "b": None, "B": None, "d": "0", "D": "x", "s": " ", "S": "x", "w": "x", "W": "!", "Z": None, } class Choice(list): """ Used to represent multiple possibilities at this point in a pattern string. We use a distinguished type, rather than a list, so that the usage in the code is clear. """ class Group(list): """ Used to represent a capturing group in the pattern string. """ class NonCapture(list): """ Used to represent a non-capturing group in the pattern string. """ def normalize(pattern): r""" Given a reg-exp pattern, normalizes it to an iterable of forms that suffice for reverse matching. This does the following: (1) For any repeating sections, keeps the minimum number of occurrences permitted (this means zero for optional groups). (2) If an optional group includes parameters, include one occurrence of that group (along with the zero occurrence case from step (1)). (3) Select the first (essentially an arbitrary) element from any character class. Select an arbitrary character for any unordered class (e.g. '.' or '\w') in the pattern. (4) Ignore comments, look-ahead and look-behind assertions, and any of the reg-exp flags that won't change what we construct ("iLmsu"). "(?x)" is an error, however. (5) Raise an error on any disjunctive ('|') constructs. Django's URLs for forward resolving are either all positional arguments or all keyword arguments. That is assumed here, as well. Although reverse resolving can be done using positional args when keyword args are specified, the two cannot be mixed in the same reverse() call. """ # Do a linear scan to work out the special features of this pattern. The # idea is that we scan once here and collect all the information we need to # make future decisions. result = [] non_capturing_groups = [] consume_next = True pattern_iter = next_char(iter(pattern)) num_args = 0 # A "while" loop is used here because later on we need to be able to peek # at the next character and possibly go around without consuming another # one at the top of the loop. try: ch, escaped = next(pattern_iter) except StopIteration: return [('', [])] try: while True: if escaped: result.append(ch) elif ch == '.': # Replace "any character" with an arbitrary representative. result.append(".") elif ch == '|': # FIXME: One day we'll should do this, but not in 1.0. raise NotImplementedError('Awaiting Implementation') elif ch == "^": pass elif ch == '$': break elif ch == ')': # This can only be the end of a non-capturing group, since all # other unescaped parentheses are handled by the grouping # section later (and the full group is handled there). # # We regroup everything inside the capturing group so that it # can be quantified, if necessary. start = non_capturing_groups.pop() inner = NonCapture(result[start:]) result = result[:start] + [inner] elif ch == '[': # Replace ranges with the first character in the range. ch, escaped = next(pattern_iter) result.append(ch) ch, escaped = next(pattern_iter) while escaped or ch != ']': ch, escaped = next(pattern_iter) elif ch == '(': # Some kind of group. ch, escaped = next(pattern_iter) if ch != '?' or escaped: # A positional group name = "_%d" % num_args num_args += 1 result.append(Group((("%%(%s)s" % name), name))) walk_to_end(ch, pattern_iter) else: ch, escaped = next(pattern_iter) if ch in "iLmsu#!=<": # All of these are ignorable. Walk to the end of the # group. walk_to_end(ch, pattern_iter) elif ch == ':': # Non-capturing group non_capturing_groups.append(len(result)) elif ch != 'P': # Anything else, other than a named group, is something # we cannot reverse. raise ValueError("Non-reversible reg-exp portion: '(?%s'" % ch) else: ch, escaped = next(pattern_iter) if ch not in ('<', '='): raise ValueError("Non-reversible reg-exp portion: '(?P%s'" % ch) # We are in a named capturing group. Extra the name and # then skip to the end. if ch == '<': terminal_char = '>' # We are in a named backreference. else: terminal_char = ')' name = [] ch, escaped = next(pattern_iter) while ch != terminal_char: name.append(ch) ch, escaped = next(pattern_iter) param = ''.join(name) # Named backreferences have already consumed the # parenthesis. if terminal_char != ')': result.append(Group((("%%(%s)s" % param), param))) walk_to_end(ch, pattern_iter) else: result.append(Group((("%%(%s)s" % param), None))) elif ch in "*?+{": # Quantifiers affect the previous item in the result list. count, ch = get_quantifier(ch, pattern_iter) if ch: # We had to look ahead, but it wasn't need to compute the # quantifier, so use this character next time around the # main loop. consume_next = False if count == 0: if contains(result[-1], Group): # If we are quantifying a capturing group (or # something containing such a group) and the minimum is # zero, we must also handle the case of one occurrence # being present. All the quantifiers (except {0,0}, # which we conveniently ignore) that have a 0 minimum # also allow a single occurrence. result[-1] = Choice([None, result[-1]]) else: result.pop() elif count > 1: result.extend([result[-1]] * (count - 1)) else: # Anything else is a literal. result.append(ch) if consume_next: ch, escaped = next(pattern_iter) else: consume_next = True except StopIteration: pass except NotImplementedError: # A case of using the disjunctive form. No results for you! return [('', [])] return list(zip(*flatten_result(result))) def next_char(input_iter): r""" An iterator that yields the next character from "pattern_iter", respecting escape sequences. An escaped character is replaced by a representative of its class (e.g. \w -> "x"). If the escaped character is one that is skipped, it is not returned (the next character is returned instead). Yields the next character, along with a boolean indicating whether it is a raw (unescaped) character or not. """ for ch in input_iter: if ch != '\\': yield ch, False continue ch = next(input_iter) representative = ESCAPE_MAPPINGS.get(ch, ch) if representative is None: continue yield representative, True def walk_to_end(ch, input_iter): """ The iterator is currently inside a capturing group. We want to walk to the close of this group, skipping over any nested groups and handling escaped parentheses correctly. """ if ch == '(': nesting = 1 else: nesting = 0 for ch, escaped in input_iter: if escaped: continue elif ch == '(': nesting += 1 elif ch == ')': if not nesting: return nesting -= 1 def get_quantifier(ch, input_iter): """ Parse a quantifier from the input, where "ch" is the first character in the quantifier. Returns the minimum number of occurrences permitted by the quantifier and either None or the next character from the input_iter if the next character is not part of the quantifier. """ if ch in '*?+': try: ch2, escaped = next(input_iter) except StopIteration: ch2 = None if ch2 == '?': ch2 = None if ch == '+': return 1, ch2 return 0, ch2 quant = [] while ch != '}': ch, escaped = next(input_iter) quant.append(ch) quant = quant[:-1] values = ''.join(quant).split(',') # Consume the trailing '?', if necessary. try: ch, escaped = next(input_iter) except StopIteration: ch = None if ch == '?': ch = None return int(values[0]), ch def contains(source, inst): """ Returns True if the "source" contains an instance of "inst". False, otherwise. """ if isinstance(source, inst): return True if isinstance(source, NonCapture): for elt in source: if contains(elt, inst): return True return False def flatten_result(source): """ Turns the given source sequence into a list of reg-exp possibilities and their arguments. Returns a list of strings and a list of argument lists. Each of the two lists will be of the same length. """ if source is None: return [''], [[]] if isinstance(source, Group): if source[1] is None: params = [] else: params = [source[1]] return [source[0]], [params] result = [''] result_args = [[]] pos = last = 0 for pos, elt in enumerate(source): if isinstance(elt, six.string_types): continue piece = ''.join(source[last:pos]) if isinstance(elt, Group): piece += elt[0] param = elt[1] else: param = None last = pos + 1 for i in range(len(result)): result[i] += piece if param: result_args[i].append(param) if isinstance(elt, (Choice, NonCapture)): if isinstance(elt, NonCapture): elt = [elt] inner_result, inner_args = [], [] for item in elt: res, args = flatten_result(item) inner_result.extend(res) inner_args.extend(args) new_result = [] new_args = [] for item, args in zip(result, result_args): for i_item, i_args in zip(inner_result, inner_args): new_result.append(item + i_item) new_args.append(args[:] + i_args) result = new_result result_args = new_args if pos >= last: piece = ''.join(source[last:]) for i in range(len(result)): result[i] += piece return result, result_args
3dc0a9dbc8483afa1d8105d89e8837df17b48449dc5d4385eac961de38073fde
try: from functools import lru_cache except ImportError: # backport of Python's 3.3 lru_cache, written by Raymond Hettinger and # licensed under MIT license, from: # <http://code.activestate.com/recipes/578078-py26-and-py30-backport-of-python-33s-lru-cache/> # Should be removed when Django only supports Python 3.2 and above. from collections import namedtuple from functools import update_wrapper from threading import RLock _CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"]) class _HashedSeq(list): __slots__ = 'hashvalue' def __init__(self, tup, hash=hash): self[:] = tup self.hashvalue = hash(tup) def __hash__(self): return self.hashvalue def _make_key(args, kwds, typed, kwd_mark = (object(),), fasttypes = {int, str, frozenset, type(None)}, sorted=sorted, tuple=tuple, type=type, len=len): 'Make a cache key from optionally typed positional and keyword arguments' key = args if kwds: sorted_items = sorted(kwds.items()) key += kwd_mark for item in sorted_items: key += item if typed: key += tuple(type(v) for v in args) if kwds: key += tuple(type(v) for k, v in sorted_items) elif len(key) == 1 and type(key[0]) in fasttypes: return key[0] return _HashedSeq(key) def lru_cache(maxsize=100, typed=False): """Least-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. If *typed* is True, arguments of different types will be cached separately. For example, f(3.0) and f(3) will be treated as distinct calls with distinct results. Arguments to the cached function must be hashable. View the cache statistics named tuple (hits, misses, maxsize, currsize) with f.cache_info(). Clear the cache and statistics with f.cache_clear(). Access the underlying function with f.__wrapped__. See: https://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used """ # Users should only access the lru_cache through its public API: # cache_info, cache_clear, and f.__wrapped__ # The internals of the lru_cache are encapsulated for thread safety and # to allow the implementation to change (including a possible C version). def decorating_function(user_function): cache = dict() stats = [0, 0] # make statistics updateable non-locally HITS, MISSES = 0, 1 # names for the stats fields make_key = _make_key cache_get = cache.get # bound method to lookup key or return None _len = len # localize the global len() function lock = RLock() # because linkedlist updates aren't threadsafe root = [] # root of the circular doubly linked list root[:] = [root, root, None, None] # initialize by pointing to self nonlocal_root = [root] # make updateable non-locally PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields if maxsize == 0: def wrapper(*args, **kwds): # no caching, just do a statistics update after a successful call result = user_function(*args, **kwds) stats[MISSES] += 1 return result elif maxsize is None: def wrapper(*args, **kwds): # simple caching without ordering or size limit key = make_key(args, kwds, typed) result = cache_get(key, root) # root used here as a unique not-found sentinel if result is not root: stats[HITS] += 1 return result result = user_function(*args, **kwds) cache[key] = result stats[MISSES] += 1 return result else: def wrapper(*args, **kwds): # size limited caching that tracks accesses by recency key = make_key(args, kwds, typed) if kwds or typed else args with lock: link = cache_get(key) if link is not None: # record recent use of the key by moving it to the front of the list root, = nonlocal_root link_prev, link_next, key, result = link link_prev[NEXT] = link_next link_next[PREV] = link_prev last = root[PREV] last[NEXT] = root[PREV] = link link[PREV] = last link[NEXT] = root stats[HITS] += 1 return result result = user_function(*args, **kwds) with lock: root, = nonlocal_root if key in cache: # getting here means that this same key was added to the # cache while the lock was released. since the link # update is already done, we need only return the # computed result and update the count of misses. pass elif _len(cache) >= maxsize: # use the old root to store the new key and result oldroot = root oldroot[KEY] = key oldroot[RESULT] = result # empty the oldest link and make it the new root root = nonlocal_root[0] = oldroot[NEXT] oldkey = root[KEY] oldvalue = root[RESULT] root[KEY] = root[RESULT] = None # now update the cache dictionary for the new links del cache[oldkey] cache[key] = oldroot else: # put result in a new link at the front of the list last = root[PREV] link = [last, root, key, result] last[NEXT] = root[PREV] = cache[key] = link stats[MISSES] += 1 return result def cache_info(): """Report cache statistics""" with lock: return _CacheInfo(stats[HITS], stats[MISSES], maxsize, len(cache)) def cache_clear(): """Clear the cache and cache statistics""" with lock: cache.clear() root = nonlocal_root[0] root[:] = [root, root, None, None] stats[:] = [0, 0] wrapper.__wrapped__ = user_function wrapper.cache_info = cache_info wrapper.cache_clear = cache_clear return update_wrapper(wrapper, user_function) return decorating_function
11ccb289af087def7ae5e6e0b3d1f87a2f392037c8e5fafa89c336d625a052be
from __future__ import unicode_literals import calendar import datetime from django.utils.html import avoid_wrapping from django.utils.timezone import is_aware, utc from django.utils.translation import ugettext, ungettext_lazy TIMESINCE_CHUNKS = ( (60 * 60 * 24 * 365, ungettext_lazy('%d year', '%d years')), (60 * 60 * 24 * 30, ungettext_lazy('%d month', '%d months')), (60 * 60 * 24 * 7, ungettext_lazy('%d week', '%d weeks')), (60 * 60 * 24, ungettext_lazy('%d day', '%d days')), (60 * 60, ungettext_lazy('%d hour', '%d hours')), (60, ungettext_lazy('%d minute', '%d minutes')) ) def timesince(d, now=None, reversed=False): """ Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to two adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. Adapted from http://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) if not now: now = datetime.datetime.now(utc if is_aware(d) else None) delta = (d - now) if reversed else (now - d) # Deal with leapyears by subtracing the number of leapdays delta -= datetime.timedelta(calendar.leapdays(d.year, now.year)) # ignore microseconds since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping(ugettext('0 minutes')) for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS): count = since // seconds if count != 0: break result = avoid_wrapping(name % count) if i + 1 < len(TIMESINCE_CHUNKS): # Now get the second item seconds2, name2 = TIMESINCE_CHUNKS[i + 1] count2 = (since - (seconds * count)) // seconds2 if count2 != 0: result += ugettext(', ') + avoid_wrapping(name2 % count2) return result def timeuntil(d, now=None): """ Like timesince, but returns a string measuring the time until the given time. """ return timesince(d, now, reversed=True)
ebe117e831978b51c4eb40c922b058490db9a3fa2363f1db557efda638ee5741
from __future__ import absolute_import import inspect from django.utils import six def getargspec(func): if six.PY2: return inspect.getargspec(func) sig = inspect.signature(func) args = [ p.name for p in sig.parameters.values() if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD ] varargs = [ p.name for p in sig.parameters.values() if p.kind == inspect.Parameter.VAR_POSITIONAL ] varargs = varargs[0] if varargs else None varkw = [ p.name for p in sig.parameters.values() if p.kind == inspect.Parameter.VAR_KEYWORD ] varkw = varkw[0] if varkw else None defaults = [ p.default for p in sig.parameters.values() if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD and p.default is not p.empty ] or None return args, varargs, varkw, defaults def get_func_args(func): if six.PY2: argspec = inspect.getargspec(func) return argspec.args[1:] # ignore 'self' sig = inspect.signature(func) return [ arg_name for arg_name, param in sig.parameters.items() if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD ] def get_func_full_args(func): """ Return a list of (argument name, default value) tuples. If the argument does not have a default value, omit it in the tuple. Arguments such as *args and **kwargs are also included. """ if six.PY2: argspec = inspect.getargspec(func) args = argspec.args[1:] # ignore 'self' defaults = argspec.defaults or [] # Split args into two lists depending on whether they have default value no_default = args[:len(args) - len(defaults)] with_default = args[len(args) - len(defaults):] # Join the two lists and combine it with default values args = [(arg,) for arg in no_default] + zip(with_default, defaults) # Add possible *args and **kwargs and prepend them with '*' or '**' varargs = [('*' + argspec.varargs,)] if argspec.varargs else [] kwargs = [('**' + argspec.keywords,)] if argspec.keywords else [] return args + varargs + kwargs sig = inspect.signature(func) args = [] for arg_name, param in sig.parameters.items(): name = arg_name # Ignore 'self' if name == 'self': continue if param.kind == inspect.Parameter.VAR_POSITIONAL: name = '*' + name elif param.kind == inspect.Parameter.VAR_KEYWORD: name = '**' + name if param.default != inspect.Parameter.empty: args.append((name, param.default)) else: args.append((name,)) return args def func_accepts_kwargs(func): if six.PY2: # Not all callables are inspectable with getargspec, so we'll # try a couple different ways but in the end fall back on assuming # it is -- we don't want to prevent registration of valid but weird # callables. try: argspec = inspect.getargspec(func) except TypeError: try: argspec = inspect.getargspec(func.__call__) except (TypeError, AttributeError): argspec = None return not argspec or argspec[2] is not None return any( p for p in inspect.signature(func).parameters.values() if p.kind == p.VAR_KEYWORD ) def func_accepts_var_args(func): """ Return True if function 'func' accepts positional arguments *args. """ if six.PY2: return inspect.getargspec(func)[1] is not None return any( p for p in inspect.signature(func).parameters.values() if p.kind == p.VAR_POSITIONAL ) def func_has_no_args(func): args = inspect.getargspec(func)[0] if six.PY2 else [ p for p in inspect.signature(func).parameters.values() if p.kind == p.POSITIONAL_OR_KEYWORD ] return len(args) == 1 def func_supports_parameter(func, parameter): if six.PY3: return parameter in inspect.signature(func).parameters else: args, varargs, varkw, defaults = inspect.getargspec(func) return parameter in args
8eaafc093e2a2d8f9143d07cd4627abaae89adbeb503cb868663a515b4dcd410
import copy from collections import OrderedDict from django.utils import six class OrderedSet(object): """ A set which keeps the ordering of the inserted items. Currently backs onto OrderedDict. """ def __init__(self, iterable=None): self.dict = OrderedDict(((x, None) for x in iterable) if iterable else []) def add(self, item): self.dict[item] = None def remove(self, item): del self.dict[item] def discard(self, item): try: self.remove(item) except KeyError: pass def __iter__(self): return iter(self.dict.keys()) def __contains__(self, item): return item in self.dict def __bool__(self): return bool(self.dict) def __nonzero__(self): # Python 2 compatibility return type(self).__bool__(self) def __len__(self): return len(self.dict) class MultiValueDictKeyError(KeyError): pass class MultiValueDict(dict): """ A subclass of dictionary customized to handle multiple values for the same key. >>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']}) >>> d['name'] 'Simon' >>> d.getlist('name') ['Adrian', 'Simon'] >>> d.getlist('doesnotexist') [] >>> d.getlist('doesnotexist', ['Adrian', 'Simon']) ['Adrian', 'Simon'] >>> d.get('lastname', 'nonexistent') 'nonexistent' >>> d.setlist('lastname', ['Holovaty', 'Willison']) This class exists to solve the irritating problem raised by cgi.parse_qs, which returns a list for every key, even though most Web forms submit single name-value pairs. """ def __init__(self, key_to_list_mapping=()): super(MultiValueDict, self).__init__(key_to_list_mapping) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, super(MultiValueDict, self).__repr__()) def __getitem__(self, key): """ Returns the last data value for this key, or [] if it's an empty list; raises KeyError if not found. """ try: list_ = super(MultiValueDict, self).__getitem__(key) except KeyError: raise MultiValueDictKeyError(repr(key)) try: return list_[-1] except IndexError: return [] def __setitem__(self, key, value): super(MultiValueDict, self).__setitem__(key, [value]) def __copy__(self): return self.__class__([ (k, v[:]) for k, v in self.lists() ]) def __deepcopy__(self, memo=None): if memo is None: memo = {} result = self.__class__() memo[id(self)] = result for key, value in dict.items(self): dict.__setitem__(result, copy.deepcopy(key, memo), copy.deepcopy(value, memo)) return result def __getstate__(self): obj_dict = self.__dict__.copy() obj_dict['_data'] = {k: self._getlist(k) for k in self} return obj_dict def __setstate__(self, obj_dict): data = obj_dict.pop('_data', {}) for k, v in data.items(): self.setlist(k, v) self.__dict__.update(obj_dict) def get(self, key, default=None): """ Returns the last data value for the passed key. If key doesn't exist or value is an empty list, then default is returned. """ try: val = self[key] except KeyError: return default if val == []: return default return val def _getlist(self, key, default=None, force_list=False): """ Return a list of values for the key. Used internally to manipulate values list. If force_list is True, return a new copy of values. """ try: values = super(MultiValueDict, self).__getitem__(key) except KeyError: if default is None: return [] return default else: if force_list: values = list(values) return values def getlist(self, key, default=None): """ Return the list of values for the key. If key doesn't exist, return a default value. """ return self._getlist(key, default, force_list=True) def setlist(self, key, list_): super(MultiValueDict, self).__setitem__(key, list_) def setdefault(self, key, default=None): if key not in self: self[key] = default # Do not return default here because __setitem__() may store # another value -- QueryDict.__setitem__() does. Look it up. return self[key] def setlistdefault(self, key, default_list=None): if key not in self: if default_list is None: default_list = [] self.setlist(key, default_list) # Do not return default_list here because setlist() may store # another value -- QueryDict.setlist() does. Look it up. return self._getlist(key) def appendlist(self, key, value): """Appends an item to the internal list associated with key.""" self.setlistdefault(key).append(value) def _iteritems(self): """ Yields (key, value) pairs, where value is the last item in the list associated with the key. """ for key in self: yield key, self[key] def _iterlists(self): """Yields (key, list) pairs.""" return six.iteritems(super(MultiValueDict, self)) def _itervalues(self): """Yield the last value on every key list.""" for key in self: yield self[key] if six.PY3: items = _iteritems lists = _iterlists values = _itervalues else: iteritems = _iteritems iterlists = _iterlists itervalues = _itervalues def items(self): return list(self.iteritems()) def lists(self): return list(self.iterlists()) def values(self): return list(self.itervalues()) def copy(self): """Returns a shallow copy of this object.""" return copy.copy(self) def update(self, *args, **kwargs): """ update() extends rather than replaces existing key lists. Also accepts keyword args. """ if len(args) > 1: raise TypeError("update expected at most 1 arguments, got %d" % len(args)) if args: other_dict = args[0] if isinstance(other_dict, MultiValueDict): for key, value_list in other_dict.lists(): self.setlistdefault(key).extend(value_list) else: try: for key, value in other_dict.items(): self.setlistdefault(key).append(value) except TypeError: raise ValueError("MultiValueDict.update() takes either a MultiValueDict or dictionary") for key, value in six.iteritems(kwargs): self.setlistdefault(key).append(value) def dict(self): """ Returns current object as a dict with singular values. """ return {key: self[key] for key in self} class ImmutableList(tuple): """ A tuple-like object that raises useful errors when it is asked to mutate. Example:: >>> a = ImmutableList(range(5), warning="You cannot mutate this.") >>> a[3] = '4' Traceback (most recent call last): ... AttributeError: You cannot mutate this. """ def __new__(cls, *args, **kwargs): if 'warning' in kwargs: warning = kwargs['warning'] del kwargs['warning'] else: warning = 'ImmutableList object is immutable.' self = tuple.__new__(cls, *args, **kwargs) self.warning = warning return self def complain(self, *wargs, **kwargs): if isinstance(self.warning, Exception): raise self.warning else: raise AttributeError(self.warning) # All list mutation functions complain. __delitem__ = complain __delslice__ = complain __iadd__ = complain __imul__ = complain __setitem__ = complain __setslice__ = complain append = complain extend = complain insert = complain pop = complain remove = complain sort = complain reverse = complain class DictWrapper(dict): """ Wraps accesses to a dictionary so that certain values (those starting with the specified prefix) are passed through a function before being returned. The prefix is removed before looking up the real value. Used by the SQL construction code to ensure that values are correctly quoted before being used. """ def __init__(self, data, func, prefix): super(DictWrapper, self).__init__(data) self.func = func self.prefix = prefix def __getitem__(self, key): """ Retrieves the real value after stripping the prefix string (if present). If the prefix is present, pass the value through self.func before returning, otherwise return the raw value. """ if key.startswith(self.prefix): use_func = True key = key[len(self.prefix):] else: use_func = False value = super(DictWrapper, self).__getitem__(key) if use_func: return self.func(value) return value
9cfe0417309b6e26c8a9b5505b1ce0e5e19d8e738558f2c2b40a65c17ca33fa0
""" PHP date() style date formatting See http://www.php.net/date for format strings Usage: >>> import datetime >>> d = datetime.datetime.now() >>> df = DateFormat(d) >>> print(df.format('jS F Y H:i')) 7th October 2003 11:39 >>> """ from __future__ import unicode_literals import calendar import datetime import re import time from django.utils import six from django.utils.dates import ( MONTHS, MONTHS_3, MONTHS_ALT, MONTHS_AP, WEEKDAYS, WEEKDAYS_ABBR, ) from django.utils.encoding import force_text from django.utils.timezone import get_default_timezone, is_aware, is_naive from django.utils.translation import ugettext as _ re_formatchars = re.compile(r'(?<!\\)([aAbBcdDeEfFgGhHiIjlLmMnNoOPrsStTUuwWyYzZ])') re_escaped = re.compile(r'\\(.)') class Formatter(object): def format(self, formatstr): pieces = [] for i, piece in enumerate(re_formatchars.split(force_text(formatstr))): if i % 2: if type(self.data) is datetime.date and hasattr(TimeFormat, piece): raise TypeError( "The format for date objects may not contain " "time-related format specifiers (found '%s')." % piece ) pieces.append(force_text(getattr(self, piece)())) elif piece: pieces.append(re_escaped.sub(r'\1', piece)) return ''.join(pieces) class TimeFormat(Formatter): def __init__(self, obj): self.data = obj self.timezone = None # We only support timezone when formatting datetime objects, # not date objects (timezone information not appropriate), # or time objects (against established django policy). if isinstance(obj, datetime.datetime): if is_naive(obj): self.timezone = get_default_timezone() else: self.timezone = obj.tzinfo def a(self): "'a.m.' or 'p.m.'" if self.data.hour > 11: return _('p.m.') return _('a.m.') def A(self): "'AM' or 'PM'" if self.data.hour > 11: return _('PM') return _('AM') def B(self): "Swatch Internet time" raise NotImplementedError('may be implemented in a future release') def e(self): """ Timezone name. If timezone information is not available, this method returns an empty string. """ if not self.timezone: return "" try: if hasattr(self.data, 'tzinfo') and self.data.tzinfo: # Have to use tzinfo.tzname and not datetime.tzname # because datatime.tzname does not expect Unicode return self.data.tzinfo.tzname(self.data) or "" except NotImplementedError: pass return "" def f(self): """ Time, in 12-hour hours and minutes, with minutes left off if they're zero. Examples: '1', '1:30', '2:05', '2' Proprietary extension. """ if self.data.minute == 0: return self.g() return '%s:%s' % (self.g(), self.i()) def g(self): "Hour, 12-hour format without leading zeros; i.e. '1' to '12'" if self.data.hour == 0: return 12 if self.data.hour > 12: return self.data.hour - 12 return self.data.hour def G(self): "Hour, 24-hour format without leading zeros; i.e. '0' to '23'" return self.data.hour def h(self): "Hour, 12-hour format; i.e. '01' to '12'" return '%02d' % self.g() def H(self): "Hour, 24-hour format; i.e. '00' to '23'" return '%02d' % self.G() def i(self): "Minutes; i.e. '00' to '59'" return '%02d' % self.data.minute def O(self): """ Difference to Greenwich time in hours; e.g. '+0200', '-0430'. If timezone information is not available, this method returns an empty string. """ if not self.timezone: return "" seconds = self.Z() if seconds == "": return "" sign = '-' if seconds < 0 else '+' seconds = abs(seconds) return "%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60) def P(self): """ Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off if they're zero and the strings 'midnight' and 'noon' if appropriate. Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.' Proprietary extension. """ if self.data.minute == 0 and self.data.hour == 0: return _('midnight') if self.data.minute == 0 and self.data.hour == 12: return _('noon') return '%s %s' % (self.f(), self.a()) def s(self): "Seconds; i.e. '00' to '59'" return '%02d' % self.data.second def T(self): """ Time zone of this machine; e.g. 'EST' or 'MDT'. If timezone information is not available, this method returns an empty string. """ if not self.timezone: return "" name = None try: name = self.timezone.tzname(self.data) except Exception: # pytz raises AmbiguousTimeError during the autumn DST change. # This happens mainly when __init__ receives a naive datetime # and sets self.timezone = get_default_timezone(). pass if name is None: name = self.format('O') return six.text_type(name) def u(self): "Microseconds; i.e. '000000' to '999999'" return '%06d' % self.data.microsecond def Z(self): """ Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. If timezone information is not available, this method returns an empty string. """ if not self.timezone: return "" try: offset = self.timezone.utcoffset(self.data) except Exception: # pytz raises AmbiguousTimeError during the autumn DST change. # This happens mainly when __init__ receives a naive datetime # and sets self.timezone = get_default_timezone(). return "" # `offset` is a datetime.timedelta. For negative values (to the west of # UTC) only days can be negative (days=-1) and seconds are always # positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0) # Positive offsets have days=0 return offset.days * 86400 + offset.seconds class DateFormat(TimeFormat): year_days = [None, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] def b(self): "Month, textual, 3 letters, lowercase; e.g. 'jan'" return MONTHS_3[self.data.month] def c(self): """ ISO 8601 Format Example : '2008-01-02T10:30:00.000123' """ return self.data.isoformat() def d(self): "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'" return '%02d' % self.data.day def D(self): "Day of the week, textual, 3 letters; e.g. 'Fri'" return WEEKDAYS_ABBR[self.data.weekday()] def E(self): "Alternative month names as required by some locales. Proprietary extension." return MONTHS_ALT[self.data.month] def F(self): "Month, textual, long; e.g. 'January'" return MONTHS[self.data.month] def I(self): "'1' if Daylight Savings Time, '0' otherwise." try: if self.timezone and self.timezone.dst(self.data): return '1' else: return '0' except Exception: # pytz raises AmbiguousTimeError during the autumn DST change. # This happens mainly when __init__ receives a naive datetime # and sets self.timezone = get_default_timezone(). return '' def j(self): "Day of the month without leading zeros; i.e. '1' to '31'" return self.data.day def l(self): "Day of the week, textual, long; e.g. 'Friday'" return WEEKDAYS[self.data.weekday()] def L(self): "Boolean for whether it is a leap year; i.e. True or False" return calendar.isleap(self.data.year) def m(self): "Month; i.e. '01' to '12'" return '%02d' % self.data.month def M(self): "Month, textual, 3 letters; e.g. 'Jan'" return MONTHS_3[self.data.month].title() def n(self): "Month without leading zeros; i.e. '1' to '12'" return self.data.month def N(self): "Month abbreviation in Associated Press style. Proprietary extension." return MONTHS_AP[self.data.month] def o(self): "ISO 8601 year number matching the ISO week number (W)" return self.data.isocalendar()[0] def r(self): "RFC 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'" return self.format('D, j M Y H:i:s O') def S(self): "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'" if self.data.day in (11, 12, 13): # Special case return 'th' last = self.data.day % 10 if last == 1: return 'st' if last == 2: return 'nd' if last == 3: return 'rd' return 'th' def t(self): "Number of days in the given month; i.e. '28' to '31'" return '%02d' % calendar.monthrange(self.data.year, self.data.month)[1] def U(self): "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)" if isinstance(self.data, datetime.datetime) and is_aware(self.data): return int(calendar.timegm(self.data.utctimetuple())) else: return int(time.mktime(self.data.timetuple())) def w(self): "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)" return (self.data.weekday() + 1) % 7 def W(self): "ISO-8601 week number of year, weeks starting on Monday" # Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt week_number = None jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1 weekday = self.data.weekday() + 1 day_of_year = self.z() if day_of_year <= (8 - jan1_weekday) and jan1_weekday > 4: if jan1_weekday == 5 or (jan1_weekday == 6 and calendar.isleap(self.data.year - 1)): week_number = 53 else: week_number = 52 else: if calendar.isleap(self.data.year): i = 366 else: i = 365 if (i - day_of_year) < (4 - weekday): week_number = 1 else: j = day_of_year + (7 - weekday) + (jan1_weekday - 1) week_number = j // 7 if jan1_weekday > 4: week_number -= 1 return week_number def y(self): "Year, 2 digits; e.g. '99'" return six.text_type(self.data.year)[2:] def Y(self): "Year, 4 digits; e.g. '1999'" return self.data.year def z(self): "Day of the year; i.e. '0' to '365'" doy = self.year_days[self.data.month] + self.data.day if self.L() and self.data.month > 2: doy += 1 return doy def format(value, format_string): "Convenience function" df = DateFormat(value) return df.format(format_string) def time_format(value, format_string): "Convenience function" tf = TimeFormat(value) return tf.format(format_string)
da51ab756ac2c0ab46593da823abaacf7af2dfee502b6c8b3220fc58459703f6
import copy import os import sys from importlib import import_module from django.utils import six def import_string(dotted_path): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed. """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: msg = "%s doesn't look like a module path" % dotted_path six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) module = import_module(module_path) try: return getattr(module, class_name) except AttributeError: msg = 'Module "%s" does not define a "%s" attribute/class' % ( module_path, class_name) six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) def autodiscover_modules(*args, **kwargs): """ Auto-discover INSTALLED_APPS modules and fail silently when not present. This forces an import on them to register any admin bits they may want. You may provide a register_to keyword parameter as a way to access a registry. This register_to object must have a _registry instance variable to access it. """ from django.apps import apps register_to = kwargs.get('register_to') for app_config in apps.get_app_configs(): for module_to_search in args: # Attempt to import the app's module. try: if register_to: before_import_registry = copy.copy(register_to._registry) import_module('%s.%s' % (app_config.name, module_to_search)) except Exception: # Reset the registry to the state before the last import # as this import will have to reoccur on the next request and # this could raise NotRegistered and AlreadyRegistered # exceptions (see #8245). if register_to: register_to._registry = before_import_registry # Decide whether to bubble up this error. If the app just # doesn't have the module in question, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(app_config.module, module_to_search): raise if six.PY3: from importlib.util import find_spec as importlib_find def module_has_submodule(package, module_name): """See if 'module' is in 'package'.""" try: package_name = package.__name__ package_path = package.__path__ except AttributeError: # package isn't a package. return False full_module_name = package_name + '.' + module_name return importlib_find(full_module_name, package_path) is not None else: import imp def module_has_submodule(package, module_name): """See if 'module' is in 'package'.""" name = ".".join([package.__name__, module_name]) try: # None indicates a cached miss; see mark_miss() in Python/import.c. return sys.modules[name] is not None except KeyError: pass try: package_path = package.__path__ # No __path__, then not a package. except AttributeError: # Since the remainder of this function assumes that we're dealing with # a package (module with a __path__), so if it's not, then bail here. return False for finder in sys.meta_path: if finder.find_module(name, package_path): return True for entry in package_path: try: # Try the cached finder. finder = sys.path_importer_cache[entry] if finder is None: # Implicit import machinery should be used. try: file_, _, _ = imp.find_module(module_name, [entry]) if file_: file_.close() return True except ImportError: continue # Else see if the finder knows of a loader. elif finder.find_module(name): return True else: continue except KeyError: # No cached finder, so try and make one. for hook in sys.path_hooks: try: finder = hook(entry) # XXX Could cache in sys.path_importer_cache if finder.find_module(name): return True else: # Once a finder is found, stop the search. break except ImportError: # Continue the search for a finder. continue else: # No finder found. # Try the implicit import machinery if searching a directory. if os.path.isdir(entry): try: file_, _, _ = imp.find_module(module_name, [entry]) if file_: file_.close() return True except ImportError: pass # XXX Could insert None or NullImporter else: # Exhausted the search, so the module cannot be found. return False def module_dir(module): """ Find the name of the directory that contains a module, if possible. Raise ValueError otherwise, e.g. for namespace packages that are split over several directories. """ # Convert to list because _NamespacePath does not support indexing on 3.3. paths = list(getattr(module, '__path__', [])) if len(paths) == 1: return paths[0] else: filename = getattr(module, '__file__', None) if filename is not None: return os.path.dirname(filename) raise ValueError("Cannot determine directory containing %s" % module)
830d013fa1cc8920f7e677ad88012e4e08ffdcbb27c02f1f135815dc77185e71
from django.utils import six from django.utils.six.moves import html_parser as _html_parser try: HTMLParseError = _html_parser.HTMLParseError except AttributeError: # create a dummy class for Python 3.5+ where it's been removed class HTMLParseError(Exception): pass if six.PY3: class HTMLParser(_html_parser.HTMLParser): """Explicitly set convert_charrefs to be False. This silences a deprecation warning on Python 3.4, but we can't do it at call time because Python 2.7 does not have the keyword argument. """ def __init__(self, convert_charrefs=False, **kwargs): _html_parser.HTMLParser.__init__(self, convert_charrefs=convert_charrefs, **kwargs) else: HTMLParser = _html_parser.HTMLParser
b5bde2e2ee1cf6a3065f0e96f03273278cd12119acba8c416edbadf4b945b372
"""Utilities for writing code that runs on Python 2 and 3""" # Copyright (c) 2010-2015 Benjamin Peterson # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import absolute_import import functools import itertools import operator import sys import types __author__ = "Benjamin Peterson <[email protected]>" __version__ = "1.10.0" # Useful for very coarse version differentiation. PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 PY34 = sys.version_info[0:2] >= (3, 4) if PY3: string_types = str, integer_types = int, class_types = type, text_type = str binary_type = bytes MAXSIZE = sys.maxsize else: string_types = basestring, integer_types = (int, long) class_types = (type, types.ClassType) text_type = unicode binary_type = str if sys.platform.startswith("java"): # Jython always uses 32 bits. MAXSIZE = int((1 << 31) - 1) else: # It's possible to have sizeof(long) != sizeof(Py_ssize_t). class X(object): def __len__(self): return 1 << 31 try: len(X()) except OverflowError: # 32-bit MAXSIZE = int((1 << 31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name] class _LazyDescr(object): def __init__(self, name): self.name = name def __get__(self, obj, tp): result = self._resolve() setattr(obj, self.name, result) # Invokes __set__. try: # This is a bit ugly, but it avoids running this again by # removing this descriptor. delattr(obj.__class__, self.name) except AttributeError: pass return result class MovedModule(_LazyDescr): def __init__(self, name, old, new=None): super(MovedModule, self).__init__(name) if PY3: if new is None: new = name self.mod = new else: self.mod = old def _resolve(self): return _import_module(self.mod) def __getattr__(self, attr): _module = self._resolve() value = getattr(_module, attr) setattr(self, attr, value) return value class _LazyModule(types.ModuleType): def __init__(self, name): super(_LazyModule, self).__init__(name) self.__doc__ = self.__class__.__doc__ def __dir__(self): attrs = ["__doc__", "__name__"] attrs += [attr.name for attr in self._moved_attributes] return attrs # Subclasses should override this _moved_attributes = [] class MovedAttribute(_LazyDescr): def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): super(MovedAttribute, self).__init__(name) if PY3: if new_mod is None: new_mod = name self.mod = new_mod if new_attr is None: if old_attr is None: new_attr = name else: new_attr = old_attr self.attr = new_attr else: self.mod = old_mod if old_attr is None: old_attr = name self.attr = old_attr def _resolve(self): module = _import_module(self.mod) return getattr(module, self.attr) class _SixMetaPathImporter(object): """ A meta path importer to import six.moves and its submodules. This class implements a PEP302 finder and loader. It should be compatible with Python 2.5 and all existing versions of Python3 """ def __init__(self, six_module_name): self.name = six_module_name self.known_modules = {} def _add_module(self, mod, *fullnames): for fullname in fullnames: self.known_modules[self.name + "." + fullname] = mod def _get_module(self, fullname): return self.known_modules[self.name + "." + fullname] def find_module(self, fullname, path=None): if fullname in self.known_modules: return self return None def __get_module(self, fullname): try: return self.known_modules[fullname] except KeyError: raise ImportError("This loader does not know module " + fullname) def load_module(self, fullname): try: # in case of a reload return sys.modules[fullname] except KeyError: pass mod = self.__get_module(fullname) if isinstance(mod, MovedModule): mod = mod._resolve() else: mod.__loader__ = self sys.modules[fullname] = mod return mod def is_package(self, fullname): """ Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451) """ return hasattr(self.__get_module(fullname), "__path__") def get_code(self, fullname): """Return None Required, if is_package is implemented""" self.__get_module(fullname) # eventually raises ImportError return None get_source = get_code # same as get_code _importer = _SixMetaPathImporter(__name__) class _MovedItems(_LazyModule): """Lazy loading of moved objects""" __path__ = [] # mark as package _moved_attributes = [ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), MovedAttribute("intern", "__builtin__", "sys"), MovedAttribute("map", "itertools", "builtins", "imap", "map"), MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"), MovedAttribute("reduce", "__builtin__", "functools"), MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), MovedAttribute("StringIO", "StringIO", "io"), MovedAttribute("UserDict", "UserDict", "collections"), MovedAttribute("UserList", "UserList", "collections"), MovedAttribute("UserString", "UserString", "collections"), MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), MovedModule("copyreg", "copy_reg"), MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), MovedModule("http_cookies", "Cookie", "http.cookies"), MovedModule("html_entities", "htmlentitydefs", "html.entities"), MovedModule("html_parser", "HTMLParser", "html.parser"), MovedModule("http_client", "httplib", "http.client"), MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), MovedModule("cPickle", "cPickle", "pickle"), MovedModule("queue", "Queue"), MovedModule("reprlib", "repr"), MovedModule("socketserver", "SocketServer"), MovedModule("_thread", "thread", "_thread"), MovedModule("tkinter", "Tkinter"), MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), MovedModule("tkinter_tix", "Tix", "tkinter.tix"), MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"), MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"), MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), MovedModule("tkinter_font", "tkFont", "tkinter.font"), MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"), MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), ] # Add windows specific modules. if sys.platform == "win32": _moved_attributes += [ MovedModule("winreg", "_winreg"), ] for attr in _moved_attributes: setattr(_MovedItems, attr.name, attr) if isinstance(attr, MovedModule): _importer._add_module(attr, "moves." + attr.name) del attr _MovedItems._moved_attributes = _moved_attributes moves = _MovedItems(__name__ + ".moves") _importer._add_module(moves, "moves") class Module_six_moves_urllib_parse(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_parse""" _urllib_parse_moved_attributes = [ MovedAttribute("ParseResult", "urlparse", "urllib.parse"), MovedAttribute("SplitResult", "urlparse", "urllib.parse"), MovedAttribute("parse_qs", "urlparse", "urllib.parse"), MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), MovedAttribute("urldefrag", "urlparse", "urllib.parse"), MovedAttribute("urljoin", "urlparse", "urllib.parse"), MovedAttribute("urlparse", "urlparse", "urllib.parse"), MovedAttribute("urlsplit", "urlparse", "urllib.parse"), MovedAttribute("urlunparse", "urlparse", "urllib.parse"), MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), MovedAttribute("quote", "urllib", "urllib.parse"), MovedAttribute("quote_plus", "urllib", "urllib.parse"), MovedAttribute("unquote", "urllib", "urllib.parse"), MovedAttribute("unquote_plus", "urllib", "urllib.parse"), MovedAttribute("urlencode", "urllib", "urllib.parse"), MovedAttribute("splitquery", "urllib", "urllib.parse"), MovedAttribute("splittag", "urllib", "urllib.parse"), MovedAttribute("splituser", "urllib", "urllib.parse"), MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), MovedAttribute("uses_params", "urlparse", "urllib.parse"), MovedAttribute("uses_query", "urlparse", "urllib.parse"), MovedAttribute("uses_relative", "urlparse", "urllib.parse"), ] for attr in _urllib_parse_moved_attributes: setattr(Module_six_moves_urllib_parse, attr.name, attr) del attr Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes _importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), "moves.urllib_parse", "moves.urllib.parse") class Module_six_moves_urllib_error(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_error""" _urllib_error_moved_attributes = [ MovedAttribute("URLError", "urllib2", "urllib.error"), MovedAttribute("HTTPError", "urllib2", "urllib.error"), MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), ] for attr in _urllib_error_moved_attributes: setattr(Module_six_moves_urllib_error, attr.name, attr) del attr Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes _importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), "moves.urllib_error", "moves.urllib.error") class Module_six_moves_urllib_request(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_request""" _urllib_request_moved_attributes = [ MovedAttribute("urlopen", "urllib2", "urllib.request"), MovedAttribute("install_opener", "urllib2", "urllib.request"), MovedAttribute("build_opener", "urllib2", "urllib.request"), MovedAttribute("pathname2url", "urllib", "urllib.request"), MovedAttribute("url2pathname", "urllib", "urllib.request"), MovedAttribute("getproxies", "urllib", "urllib.request"), MovedAttribute("Request", "urllib2", "urllib.request"), MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), MovedAttribute("BaseHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), MovedAttribute("FileHandler", "urllib2", "urllib.request"), MovedAttribute("FTPHandler", "urllib2", "urllib.request"), MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), MovedAttribute("urlretrieve", "urllib", "urllib.request"), MovedAttribute("urlcleanup", "urllib", "urllib.request"), MovedAttribute("URLopener", "urllib", "urllib.request"), MovedAttribute("FancyURLopener", "urllib", "urllib.request"), MovedAttribute("proxy_bypass", "urllib", "urllib.request"), ] for attr in _urllib_request_moved_attributes: setattr(Module_six_moves_urllib_request, attr.name, attr) del attr Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes _importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), "moves.urllib_request", "moves.urllib.request") class Module_six_moves_urllib_response(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_response""" _urllib_response_moved_attributes = [ MovedAttribute("addbase", "urllib", "urllib.response"), MovedAttribute("addclosehook", "urllib", "urllib.response"), MovedAttribute("addinfo", "urllib", "urllib.response"), MovedAttribute("addinfourl", "urllib", "urllib.response"), ] for attr in _urllib_response_moved_attributes: setattr(Module_six_moves_urllib_response, attr.name, attr) del attr Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes _importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), "moves.urllib_response", "moves.urllib.response") class Module_six_moves_urllib_robotparser(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_robotparser""" _urllib_robotparser_moved_attributes = [ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), ] for attr in _urllib_robotparser_moved_attributes: setattr(Module_six_moves_urllib_robotparser, attr.name, attr) del attr Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), "moves.urllib_robotparser", "moves.urllib.robotparser") class Module_six_moves_urllib(types.ModuleType): """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" __path__ = [] # mark as package parse = _importer._get_module("moves.urllib_parse") error = _importer._get_module("moves.urllib_error") request = _importer._get_module("moves.urllib_request") response = _importer._get_module("moves.urllib_response") robotparser = _importer._get_module("moves.urllib_robotparser") def __dir__(self): return ['parse', 'error', 'request', 'response', 'robotparser'] _importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib") def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move) def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,)) if PY3: _meth_func = "__func__" _meth_self = "__self__" _func_closure = "__closure__" _func_code = "__code__" _func_defaults = "__defaults__" _func_globals = "__globals__" else: _meth_func = "im_func" _meth_self = "im_self" _func_closure = "func_closure" _func_code = "func_code" _func_defaults = "func_defaults" _func_globals = "func_globals" try: advance_iterator = next except NameError: def advance_iterator(it): return it.next() next = advance_iterator try: callable = callable except NameError: def callable(obj): return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) if PY3: def get_unbound_function(unbound): return unbound create_bound_method = types.MethodType def create_unbound_method(func, cls): return func Iterator = object else: def get_unbound_function(unbound): return unbound.im_func def create_bound_method(func, obj): return types.MethodType(func, obj, obj.__class__) def create_unbound_method(func, cls): return types.MethodType(func, None, cls) class Iterator(object): def next(self): return type(self).__next__(self) callable = callable _add_doc(get_unbound_function, """Get the function out of a possibly unbound function""") get_method_function = operator.attrgetter(_meth_func) get_method_self = operator.attrgetter(_meth_self) get_function_closure = operator.attrgetter(_func_closure) get_function_code = operator.attrgetter(_func_code) get_function_defaults = operator.attrgetter(_func_defaults) get_function_globals = operator.attrgetter(_func_globals) if PY3: def iterkeys(d, **kw): return iter(d.keys(**kw)) def itervalues(d, **kw): return iter(d.values(**kw)) def iteritems(d, **kw): return iter(d.items(**kw)) def iterlists(d, **kw): return iter(d.lists(**kw)) viewkeys = operator.methodcaller("keys") viewvalues = operator.methodcaller("values") viewitems = operator.methodcaller("items") else: def iterkeys(d, **kw): return d.iterkeys(**kw) def itervalues(d, **kw): return d.itervalues(**kw) def iteritems(d, **kw): return d.iteritems(**kw) def iterlists(d, **kw): return d.iterlists(**kw) viewkeys = operator.methodcaller("viewkeys") viewvalues = operator.methodcaller("viewvalues") viewitems = operator.methodcaller("viewitems") _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") _add_doc(itervalues, "Return an iterator over the values of a dictionary.") _add_doc(iteritems, "Return an iterator over the (key, value) pairs of a dictionary.") _add_doc(iterlists, "Return an iterator over the (key, [values]) pairs of a dictionary.") if PY3: def b(s): return s.encode("latin-1") def u(s): return s unichr = chr import struct int2byte = struct.Struct(">B").pack del struct byte2int = operator.itemgetter(0) indexbytes = operator.getitem iterbytes = iter import io StringIO = io.StringIO BytesIO = io.BytesIO _assertCountEqual = "assertCountEqual" if sys.version_info[1] <= 1: _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" else: _assertRaisesRegex = "assertRaisesRegex" _assertRegex = "assertRegex" else: def b(s): return s # Workaround for standalone backslash def u(s): return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") unichr = unichr int2byte = chr def byte2int(bs): return ord(bs[0]) def indexbytes(buf, i): return ord(buf[i]) iterbytes = functools.partial(itertools.imap, ord) import StringIO StringIO = BytesIO = StringIO.StringIO _assertCountEqual = "assertItemsEqual" _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") def assertCountEqual(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs) def assertRaisesRegex(self, *args, **kwargs): return getattr(self, _assertRaisesRegex)(*args, **kwargs) def assertRegex(self, *args, **kwargs): return getattr(self, _assertRegex)(*args, **kwargs) if PY3: exec_ = getattr(moves.builtins, "exec") def reraise(tp, value, tb=None): if value is None: value = tp() if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("""exec _code_ in _globs_, _locs_""") exec_("""def reraise(tp, value, tb=None): raise tp, value, tb """) if sys.version_info[:2] == (3, 2): exec_("""def raise_from(value, from_value): if from_value is None: raise value raise value from from_value """) elif sys.version_info[:2] > (3, 2): exec_("""def raise_from(value, from_value): raise value from from_value """) else: def raise_from(value, from_value): raise value print_ = getattr(moves.builtins, "print", None) if print_ is None: def print_(*args, **kwargs): """The new-style print function for Python 2.4 and 2.5.""" fp = kwargs.pop("file", sys.stdout) if fp is None: return def write(data): if not isinstance(data, basestring): data = str(data) # If the file has an encoding, encode unicode with it. if (isinstance(fp, file) and isinstance(data, unicode) and fp.encoding is not None): errors = getattr(fp, "errors", None) if errors is None: errors = "strict" data = data.encode(fp.encoding, errors) fp.write(data) want_unicode = False sep = kwargs.pop("sep", None) if sep is not None: if isinstance(sep, unicode): want_unicode = True elif not isinstance(sep, str): raise TypeError("sep must be None or a string") end = kwargs.pop("end", None) if end is not None: if isinstance(end, unicode): want_unicode = True elif not isinstance(end, str): raise TypeError("end must be None or a string") if kwargs: raise TypeError("invalid keyword arguments to print()") if not want_unicode: for arg in args: if isinstance(arg, unicode): want_unicode = True break if want_unicode: newline = unicode("\n") space = unicode(" ") else: newline = "\n" space = " " if sep is None: sep = space if end is None: end = newline for i, arg in enumerate(args): if i: write(sep) write(arg) write(end) if sys.version_info[:2] < (3, 3): _print = print_ def print_(*args, **kwargs): fp = kwargs.get("file", sys.stdout) flush = kwargs.pop("flush", False) _print(*args, **kwargs) if flush and fp is not None: fp.flush() _add_doc(reraise, """Reraise an exception.""") if sys.version_info[0:2] < (3, 4): def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES): def wrapper(f): f = functools.wraps(wrapped, assigned, updated)(f) f.__wrapped__ = wrapped return f return wrapper else: wraps = functools.wraps def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {}) def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: if '__str__' not in klass.__dict__: raise ValueError("@python_2_unicode_compatible cannot be applied " "to %s because it doesn't define __str__()." % klass.__name__) klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode('utf-8') return klass # Complete the moves implementation. # This code is at the end of this module to speed up module loading. # Turn this module into a package. __path__ = [] # required for PEP 302 and PEP 451 __package__ = __name__ # see PEP 366 @ReservedAssignment if globals().get("__spec__") is not None: __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable # Remove other six meta path importers, since they cause problems. This can # happen if six is removed from sys.modules and then reloaded. (Setuptools does # this for some reason.) if sys.meta_path: for i, importer in enumerate(sys.meta_path): # Here's some real nastiness: Another "instance" of the six module might # be floating around. Therefore, we can't use isinstance() to check for # the six meta path importer, since the other six instance will have # inserted an importer with different class. if (type(importer).__name__ == "_SixMetaPathImporter" and importer.name == __name__): del sys.meta_path[i] break del i, importer # Finally, add the importer to the meta path import hook. sys.meta_path.append(_importer) ### Additional customizations for Django ### if PY3: memoryview = memoryview buffer_types = (bytes, bytearray, memoryview) else: # memoryview and buffer are not strictly equivalent, but should be fine for # django core usage (mainly BinaryField). However, Jython doesn't support # buffer (see http://bugs.jython.org/issue1521), so we have to be careful. if sys.platform.startswith('java'): memoryview = memoryview else: memoryview = buffer buffer_types = (bytearray, memoryview)
190d1e01de3040eb494a8148c73ed7cd10543c2dd439b9dafd74cb25ed6bbf9a
# Copyright (c) 2010 Guilherme Gondim. All rights reserved. # Copyright (c) 2009 Simon Willison. All rights reserved. # Copyright (c) 2002 Drew Perttula. All rights reserved. # # License: # Python Software Foundation License version 2 # # See the file "LICENSE" for terms & conditions for usage, and a DISCLAIMER OF # ALL WARRANTIES. # # This Baseconv distribution contains no GNU General Public Licensed (GPLed) # code so it may be used in proprietary projects just like prior ``baseconv`` # distributions. # # All trademarks referenced herein are property of their respective holders. # """ Convert numbers from base 10 integers to base X strings and back again. Sample usage:: >>> base20 = BaseConverter('0123456789abcdefghij') >>> base20.encode(1234) '31e' >>> base20.decode('31e') 1234 >>> base20.encode(-1234) '-31e' >>> base20.decode('-31e') -1234 >>> base11 = BaseConverter('0123456789-', sign='$') >>> base11.encode('$1234') '$-22' >>> base11.decode('$-22') '$1234' """ BASE2_ALPHABET = '01' BASE16_ALPHABET = '0123456789ABCDEF' BASE56_ALPHABET = '23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz' BASE36_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz' BASE62_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' BASE64_ALPHABET = BASE62_ALPHABET + '-_' class BaseConverter(object): decimal_digits = '0123456789' def __init__(self, digits, sign='-'): self.sign = sign self.digits = digits if sign in self.digits: raise ValueError('Sign character found in converter base digits.') def __repr__(self): return "<BaseConverter: base%s (%s)>" % (len(self.digits), self.digits) def encode(self, i): neg, value = self.convert(i, self.decimal_digits, self.digits, '-') if neg: return self.sign + value return value def decode(self, s): neg, value = self.convert(s, self.digits, self.decimal_digits, self.sign) if neg: value = '-' + value return int(value) def convert(self, number, from_digits, to_digits, sign): if str(number)[0] == sign: number = str(number)[1:] neg = 1 else: neg = 0 # make an integer out of the number x = 0 for digit in str(number): x = x * len(from_digits) + from_digits.index(digit) # create the result in base 'len(to_digits)' if x == 0: res = to_digits[0] else: res = '' while x > 0: digit = x % len(to_digits) res = to_digits[digit] + res x = int(x // len(to_digits)) return neg, res base2 = BaseConverter(BASE2_ALPHABET) base16 = BaseConverter(BASE16_ALPHABET) base36 = BaseConverter(BASE36_ALPHABET) base56 = BaseConverter(BASE56_ALPHABET) base62 = BaseConverter(BASE62_ALPHABET) base64 = BaseConverter(BASE64_ALPHABET, sign='$')
7bdbbe9c5493b7de1cdb163dd593c82c57a2f77c896ee75e7d697209f603779b
import datetime def _get_duration_components(duration): days = duration.days seconds = duration.seconds microseconds = duration.microseconds minutes = seconds // 60 seconds = seconds % 60 hours = minutes // 60 minutes = minutes % 60 return days, hours, minutes, seconds, microseconds def duration_string(duration): """Version of str(timedelta) which is not English specific.""" days, hours, minutes, seconds, microseconds = _get_duration_components(duration) string = '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds) if days: string = '{} '.format(days) + string if microseconds: string += '.{:06d}'.format(microseconds) return string def duration_iso_string(duration): if duration < datetime.timedelta(0): sign = '-' duration *= -1 else: sign = '' days, hours, minutes, seconds, microseconds = _get_duration_components(duration) ms = '.{:06d}'.format(microseconds) if microseconds else "" return '{}P{}DT{:02d}H{:02d}M{:02d}{}S'.format(sign, days, hours, minutes, seconds, ms)
80395c4c648423b4c11de1450951181b6aa67904c1c3a97460c3197613d195f5
""" Synchronization primitives: - reader-writer lock (preference to writers) (Contributed to Django by [email protected]) """ import contextlib import threading class RWLock(object): """ Classic implementation of reader-writer lock with preference to writers. Readers can access a resource simultaneously. Writers get an exclusive access. API is self-descriptive: reader_enters() reader_leaves() writer_enters() writer_leaves() """ def __init__(self): self.mutex = threading.RLock() self.can_read = threading.Semaphore(0) self.can_write = threading.Semaphore(0) self.active_readers = 0 self.active_writers = 0 self.waiting_readers = 0 self.waiting_writers = 0 def reader_enters(self): with self.mutex: if self.active_writers == 0 and self.waiting_writers == 0: self.active_readers += 1 self.can_read.release() else: self.waiting_readers += 1 self.can_read.acquire() def reader_leaves(self): with self.mutex: self.active_readers -= 1 if self.active_readers == 0 and self.waiting_writers != 0: self.active_writers += 1 self.waiting_writers -= 1 self.can_write.release() @contextlib.contextmanager def reader(self): self.reader_enters() try: yield finally: self.reader_leaves() def writer_enters(self): with self.mutex: if self.active_writers == 0 and self.waiting_writers == 0 and self.active_readers == 0: self.active_writers += 1 self.can_write.release() else: self.waiting_writers += 1 self.can_write.acquire() def writer_leaves(self): with self.mutex: self.active_writers -= 1 if self.waiting_writers != 0: self.active_writers += 1 self.waiting_writers -= 1 self.can_write.release() elif self.waiting_readers != 0: t = self.waiting_readers self.waiting_readers = 0 self.active_readers += t while t > 0: self.can_read.release() t -= 1 @contextlib.contextmanager def writer(self): self.writer_enters() try: yield finally: self.writer_leaves()
8734ab3b805bd345b2d196bb4a922cb2e179a486600969c5c7b32e2aab2e8bf2
"Commonly-used date structures" from django.utils.translation import pgettext_lazy, ugettext_lazy as _ WEEKDAYS = { 0: _('Monday'), 1: _('Tuesday'), 2: _('Wednesday'), 3: _('Thursday'), 4: _('Friday'), 5: _('Saturday'), 6: _('Sunday') } WEEKDAYS_ABBR = { 0: _('Mon'), 1: _('Tue'), 2: _('Wed'), 3: _('Thu'), 4: _('Fri'), 5: _('Sat'), 6: _('Sun') } WEEKDAYS_REV = { 'monday': 0, 'tuesday': 1, 'wednesday': 2, 'thursday': 3, 'friday': 4, 'saturday': 5, 'sunday': 6 } MONTHS = { 1: _('January'), 2: _('February'), 3: _('March'), 4: _('April'), 5: _('May'), 6: _('June'), 7: _('July'), 8: _('August'), 9: _('September'), 10: _('October'), 11: _('November'), 12: _('December') } MONTHS_3 = { 1: _('jan'), 2: _('feb'), 3: _('mar'), 4: _('apr'), 5: _('may'), 6: _('jun'), 7: _('jul'), 8: _('aug'), 9: _('sep'), 10: _('oct'), 11: _('nov'), 12: _('dec') } MONTHS_3_REV = { 'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6, 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12 } MONTHS_AP = { # month names in Associated Press style 1: pgettext_lazy('abbrev. month', 'Jan.'), 2: pgettext_lazy('abbrev. month', 'Feb.'), 3: pgettext_lazy('abbrev. month', 'March'), 4: pgettext_lazy('abbrev. month', 'April'), 5: pgettext_lazy('abbrev. month', 'May'), 6: pgettext_lazy('abbrev. month', 'June'), 7: pgettext_lazy('abbrev. month', 'July'), 8: pgettext_lazy('abbrev. month', 'Aug.'), 9: pgettext_lazy('abbrev. month', 'Sept.'), 10: pgettext_lazy('abbrev. month', 'Oct.'), 11: pgettext_lazy('abbrev. month', 'Nov.'), 12: pgettext_lazy('abbrev. month', 'Dec.') } MONTHS_ALT = { # required for long date representation by some locales 1: pgettext_lazy('alt. month', 'January'), 2: pgettext_lazy('alt. month', 'February'), 3: pgettext_lazy('alt. month', 'March'), 4: pgettext_lazy('alt. month', 'April'), 5: pgettext_lazy('alt. month', 'May'), 6: pgettext_lazy('alt. month', 'June'), 7: pgettext_lazy('alt. month', 'July'), 8: pgettext_lazy('alt. month', 'August'), 9: pgettext_lazy('alt. month', 'September'), 10: pgettext_lazy('alt. month', 'October'), 11: pgettext_lazy('alt. month', 'November'), 12: pgettext_lazy('alt. month', 'December') }
b677a25763320b571e44e7b240de2db4dd6d560d86f5caac664b8fa316662bea
"""HTML utilities suitable for global use.""" from __future__ import unicode_literals import re from django.utils import six from django.utils.encoding import force_str, force_text from django.utils.functional import keep_lazy, keep_lazy_text from django.utils.http import RFC3986_GENDELIMS, RFC3986_SUBDELIMS from django.utils.safestring import SafeData, SafeText, mark_safe from django.utils.six.moves.urllib.parse import ( parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit, ) from django.utils.text import normalize_newlines from .html_parser import HTMLParseError, HTMLParser # Configuration for urlize() function. TRAILING_PUNCTUATION_RE = re.compile( '^' # Beginning of word '(.*?)' # The URL in word '([.,:;!]+)' # Allowed non-wrapping, trailing punctuation '$' # End of word ) WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('&lt;', '&gt;'), ('"', '"'), ('\'', '\'')] # List of possible strings used for bullets in bulleted lists. DOTS = ['&middot;', '*', '\u2022', '&#149;', '&bull;', '&#8226;'] unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)') word_split_re = re.compile(r'''([\s<>"']+)''') simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE) simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE) simple_email_re = re.compile(r'^\S+@\S+\.\S+$') @keep_lazy(six.text_type, SafeText) def escape(text): """ Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML. This function always escapes its input, even if it's already escaped and marked as such. This may result in double-escaping. If this is a concern, use conditional_escape() instead. """ return mark_safe( force_text(text).replace('&', '&amp;').replace('<', '&lt;') .replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;') ) _js_escapes = { ord('\\'): '\\u005C', ord('\''): '\\u0027', ord('"'): '\\u0022', ord('>'): '\\u003E', ord('<'): '\\u003C', ord('&'): '\\u0026', ord('='): '\\u003D', ord('-'): '\\u002D', ord(';'): '\\u003B', ord('\u2028'): '\\u2028', ord('\u2029'): '\\u2029' } # Escape every ASCII character with a value less than 32. _js_escapes.update((ord('%c' % z), '\\u%04X' % z) for z in range(32)) @keep_lazy(six.text_type, SafeText) def escapejs(value): """Hex encodes characters for use in JavaScript strings.""" return mark_safe(force_text(value).translate(_js_escapes)) def conditional_escape(text): """ Similar to escape(), except that it doesn't operate on pre-escaped strings. This function relies on the __html__ convention used both by Django's SafeData class and by third-party libraries like markupsafe. """ if hasattr(text, '__html__'): return text.__html__() else: return escape(text) def format_html(format_string, *args, **kwargs): """ Similar to str.format, but passes all arguments through conditional_escape, and calls 'mark_safe' on the result. This function should be used instead of str.format or % interpolation to build up small HTML fragments. """ args_safe = map(conditional_escape, args) kwargs_safe = {k: conditional_escape(v) for (k, v) in six.iteritems(kwargs)} return mark_safe(format_string.format(*args_safe, **kwargs_safe)) def format_html_join(sep, format_string, args_generator): """ A wrapper of format_html, for the common case of a group of arguments that need to be formatted using the same format string, and then joined using 'sep'. 'sep' is also passed through conditional_escape. 'args_generator' should be an iterator that returns the sequence of 'args' that will be passed to format_html. Example: format_html_join('\n', "<li>{} {}</li>", ((u.first_name, u.last_name) for u in users)) """ return mark_safe(conditional_escape(sep).join( format_html(format_string, *tuple(args)) for args in args_generator)) @keep_lazy_text def linebreaks(value, autoescape=False): """Converts newlines into <p> and <br />s.""" value = normalize_newlines(force_text(value)) paras = re.split('\n{2,}', value) if autoescape: paras = ['<p>%s</p>' % escape(p).replace('\n', '<br />') for p in paras] else: paras = ['<p>%s</p>' % p.replace('\n', '<br />') for p in paras] return '\n\n'.join(paras) class MLStripper(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.reset() self.fed = [] def handle_data(self, d): self.fed.append(d) def handle_entityref(self, name): self.fed.append('&%s;' % name) def handle_charref(self, name): self.fed.append('&#%s;' % name) def get_data(self): return ''.join(self.fed) def _strip_once(value): """ Internal tag stripping utility used by strip_tags. """ s = MLStripper() try: s.feed(value) except HTMLParseError: return value try: s.close() except HTMLParseError: return s.get_data() + s.rawdata else: return s.get_data() @keep_lazy_text def strip_tags(value): """Returns the given HTML with all tags stripped.""" # Note: in typical case this loop executes _strip_once once. Loop condition # is redundant, but helps to reduce number of executions of _strip_once. value = force_text(value) while '<' in value and '>' in value: new_value = _strip_once(value) if len(new_value) >= len(value): # _strip_once was not able to detect more tags or length increased # due to http://bugs.python.org/issue20288 # (affects Python 2 < 2.7.7 and Python 3 < 3.3.5) break value = new_value return value @keep_lazy_text def strip_spaces_between_tags(value): """Returns the given HTML with spaces between tags removed.""" return re.sub(r'>\s+<', '><', force_text(value)) def smart_urlquote(url): "Quotes a URL if it isn't already quoted." def unquote_quote(segment): segment = unquote(force_str(segment)) # Tilde is part of RFC3986 Unreserved Characters # http://tools.ietf.org/html/rfc3986#section-2.3 # See also http://bugs.python.org/issue16285 segment = quote(segment, safe=RFC3986_SUBDELIMS + RFC3986_GENDELIMS + str('~')) return force_text(segment) # Handle IDN before quoting. try: scheme, netloc, path, query, fragment = urlsplit(url) except ValueError: # invalid IPv6 URL (normally square brackets in hostname part). return unquote_quote(url) try: netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE except UnicodeError: # invalid domain part return unquote_quote(url) if query: # Separately unquoting key/value, so as to not mix querystring separators # included in query values. See #22267. query_parts = [(unquote(force_str(q[0])), unquote(force_str(q[1]))) for q in parse_qsl(query, keep_blank_values=True)] # urlencode will take care of quoting query = urlencode(query_parts) path = unquote_quote(path) fragment = unquote_quote(fragment) return urlunsplit((scheme, netloc, path, query, fragment)) @keep_lazy_text def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): """ Converts any URLs in text into clickable links. Works on http://, https://, www. links, and also on links ending in one of the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org). Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens) and it'll still do the right thing. If trim_url_limit is not None, the URLs in the link text longer than this limit will be truncated to trim_url_limit-3 characters and appended with an ellipsis. If nofollow is True, the links will get a rel="nofollow" attribute. If autoescape is True, the link text and URLs will be autoescaped. """ safe_input = isinstance(text, SafeData) def trim_url(x, limit=trim_url_limit): if limit is None or len(x) <= limit: return x return '%s...' % x[:max(0, limit - 3)] def unescape(text, trail): """ If input URL is HTML-escaped, unescape it so as we can safely feed it to smart_urlquote. For example: http://example.com?x=1&amp;y=&lt;2&gt; => http://example.com?x=1&y=<2> """ unescaped = (text + trail).replace( '&amp;', '&').replace('&lt;', '<').replace( '&gt;', '>').replace('&quot;', '"').replace('&#39;', "'") if trail and unescaped.endswith(trail): # Remove trail for unescaped if it was not consumed by unescape unescaped = unescaped[:-len(trail)] elif trail == ';': # Trail was consumed by unescape (as end-of-entity marker), move it to text text += trail trail = '' return text, unescaped, trail def trim_punctuation(lead, middle, trail): """ Trim trailing and wrapping punctuation from `middle`. Return the items of the new state. """ # Continue trimming until middle remains unchanged. trimmed_something = True while trimmed_something: trimmed_something = False # Trim trailing punctuation. match = TRAILING_PUNCTUATION_RE.match(middle) if match: middle = match.group(1) trail = match.group(2) + trail trimmed_something = True # Trim wrapping punctuation. for opening, closing in WRAPPING_PUNCTUATION: if middle.startswith(opening): middle = middle[len(opening):] lead += opening trimmed_something = True # Keep parentheses at the end only if they're balanced. if (middle.endswith(closing) and middle.count(closing) == middle.count(opening) + 1): middle = middle[:-len(closing)] trail = closing + trail trimmed_something = True return lead, middle, trail words = word_split_re.split(force_text(text)) for i, word in enumerate(words): if '.' in word or '@' in word or ':' in word: # lead: Current punctuation trimmed from the beginning of the word. # middle: Current state of the word. # trail: Current punctuation trimmed from the end of the word. lead, middle, trail = '', word, '' # Deal with punctuation. lead, middle, trail = trim_punctuation(lead, middle, trail) # Make URL we want to point to. url = None nofollow_attr = ' rel="nofollow"' if nofollow else '' if simple_url_re.match(middle): middle, middle_unescaped, trail = unescape(middle, trail) url = smart_urlquote(middle_unescaped) elif simple_url_2_re.match(middle): middle, middle_unescaped, trail = unescape(middle, trail) url = smart_urlquote('http://%s' % middle_unescaped) elif ':' not in middle and simple_email_re.match(middle): local, domain = middle.rsplit('@', 1) try: domain = domain.encode('idna').decode('ascii') except UnicodeError: continue url = 'mailto:%s@%s' % (local, domain) nofollow_attr = '' # Make link. if url: trimmed = trim_url(middle) if autoescape and not safe_input: lead, trail = escape(lead), escape(trail) trimmed = escape(trimmed) middle = '<a href="%s"%s>%s</a>' % (escape(url), nofollow_attr, trimmed) words[i] = mark_safe('%s%s%s' % (lead, middle, trail)) else: if safe_input: words[i] = mark_safe(word) elif autoescape: words[i] = escape(word) elif safe_input: words[i] = mark_safe(word) elif autoescape: words[i] = escape(word) return ''.join(words) def avoid_wrapping(value): """ Avoid text wrapping in the middle of a phrase by adding non-breaking spaces where there previously were normal spaces. """ return value.replace(" ", "\xa0") def html_safe(klass): """ A decorator that defines the __html__ method. This helps non-Django templates to detect classes whose __str__ methods return SafeText. """ if '__html__' in klass.__dict__: raise ValueError( "can't apply @html_safe to %s because it defines " "__html__()." % klass.__name__ ) if six.PY2: if '__unicode__' not in klass.__dict__: raise ValueError( "can't apply @html_safe to %s because it doesn't " "define __unicode__()." % klass.__name__ ) klass_unicode = klass.__unicode__ klass.__unicode__ = lambda self: mark_safe(klass_unicode(self)) klass.__html__ = lambda self: unicode(self) # NOQA: unicode undefined on PY3 else: if '__str__' not in klass.__dict__: raise ValueError( "can't apply @html_safe to %s because it doesn't " "define __str__()." % klass.__name__ ) klass_str = klass.__str__ klass.__str__ = lambda self: mark_safe(klass_str(self)) klass.__html__ = lambda self: str(self) return klass
ebd96997cd741d72ef11fb151e1b5a48365440c7aa408e7576ce3a9c88261102
from __future__ import unicode_literals import logging import logging.config # needed when logging_config doesn't start with logging.config from copy import copy from django.conf import settings from django.core import mail from django.core.mail import get_connection from django.core.management.color import color_style from django.utils.module_loading import import_string from django.views.debug import ExceptionReporter # Default logging for Django. This sends an email to the site admins on every # HTTP 500 error. Depending on DEBUG, all other log records are either sent to # the console (DEBUG=True) or discarded (DEBUG=False) by means of the # require_debug_true filter. DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '[%(server_time)s] %(message)s', } }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'django.server': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'django.server', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django': { 'handlers': ['console', 'mail_admins'], 'level': 'INFO', }, 'django.server': { 'handlers': ['django.server'], 'level': 'INFO', 'propagate': False, }, } } def configure_logging(logging_config, logging_settings): if logging_config: # First find the logging configuration function ... logging_config_func = import_string(logging_config) logging.config.dictConfig(DEFAULT_LOGGING) # ... then invoke it with the logging settings if logging_settings: logging_config_func(logging_settings) class AdminEmailHandler(logging.Handler): """An exception log handler that emails log entries to site admins. If the request is passed as the first argument to the log record, request data will be provided in the email report. """ def __init__(self, include_html=False, email_backend=None): logging.Handler.__init__(self) self.include_html = include_html self.email_backend = email_backend def emit(self, record): try: request = record.request subject = '%s (%s IP): %s' % ( record.levelname, ('internal' if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS else 'EXTERNAL'), record.getMessage() ) except Exception: subject = '%s: %s' % ( record.levelname, record.getMessage() ) request = None subject = self.format_subject(subject) # Since we add a nicely formatted traceback on our own, create a copy # of the log record without the exception data. no_exc_record = copy(record) no_exc_record.exc_info = None no_exc_record.exc_text = None if record.exc_info: exc_info = record.exc_info else: exc_info = (None, record.getMessage(), None) reporter = ExceptionReporter(request, is_email=True, *exc_info) message = "%s\n\n%s" % (self.format(no_exc_record), reporter.get_traceback_text()) html_message = reporter.get_traceback_html() if self.include_html else None self.send_mail(subject, message, fail_silently=True, html_message=html_message) def send_mail(self, subject, message, *args, **kwargs): mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs) def connection(self): return get_connection(backend=self.email_backend, fail_silently=True) def format_subject(self, subject): """ Escape CR and LF characters. """ return subject.replace('\n', '\\n').replace('\r', '\\r') class CallbackFilter(logging.Filter): """ A logging filter that checks the return value of a given callable (which takes the record-to-be-logged as its only parameter) to decide whether to log a record. """ def __init__(self, callback): self.callback = callback def filter(self, record): if self.callback(record): return 1 return 0 class RequireDebugFalse(logging.Filter): def filter(self, record): return not settings.DEBUG class RequireDebugTrue(logging.Filter): def filter(self, record): return settings.DEBUG class ServerFormatter(logging.Formatter): def __init__(self, *args, **kwargs): self.style = color_style() super(ServerFormatter, self).__init__(*args, **kwargs) def format(self, record): msg = record.msg status_code = getattr(record, 'status_code', None) if status_code: if 200 <= status_code < 300: # Put 2XX first, since it should be the common case msg = self.style.HTTP_SUCCESS(msg) elif 100 <= status_code < 200: msg = self.style.HTTP_INFO(msg) elif status_code == 304: msg = self.style.HTTP_NOT_MODIFIED(msg) elif 300 <= status_code < 400: msg = self.style.HTTP_REDIRECT(msg) elif status_code == 404: msg = self.style.HTTP_NOT_FOUND(msg) elif 400 <= status_code < 500: msg = self.style.HTTP_BAD_REQUEST(msg) else: # Any 5XX, or any other status code msg = self.style.HTTP_SERVER_ERROR(msg) if self.uses_server_time() and not hasattr(record, 'server_time'): record.server_time = self.formatTime(record, self.datefmt) record.msg = msg return super(ServerFormatter, self).format(record) def uses_server_time(self): return self._fmt.find('%(server_time)') >= 0
b97946e950a264a54f1a291cc3c638b17c1d425ea1c05bc66533b0fe5138927b
""" Functions for working with "safe strings": strings that can be displayed safely without further escaping in HTML. Marking something as a "safe string" means that the producer of the string has already turned characters that should not be interpreted by the HTML engine (e.g. '<') into the appropriate entities. """ import warnings from django.utils import six from django.utils.deprecation import RemovedInDjango20Warning from django.utils.functional import Promise, curry, wraps class EscapeData(object): pass class EscapeBytes(bytes, EscapeData): """ A byte string that should be HTML-escaped when output. """ pass class EscapeText(six.text_type, EscapeData): """ A unicode string object that should be HTML-escaped when output. """ pass if six.PY3: EscapeString = EscapeText else: EscapeString = EscapeBytes # backwards compatibility for Python 2 EscapeUnicode = EscapeText class SafeData(object): def __html__(self): """ Returns the html representation of a string for interoperability. This allows other template engines to understand Django's SafeData. """ return self class SafeBytes(bytes, SafeData): """ A bytes subclass that has been specifically marked as "safe" (requires no further escaping) for HTML output purposes. """ def __add__(self, rhs): """ Concatenating a safe byte string with another safe byte string or safe unicode string is safe. Otherwise, the result is no longer safe. """ t = super(SafeBytes, self).__add__(rhs) if isinstance(rhs, SafeText): return SafeText(t) elif isinstance(rhs, SafeBytes): return SafeBytes(t) return t def _proxy_method(self, *args, **kwargs): """ Wrap a call to a normal unicode method up so that we return safe results. The method that is being wrapped is passed in the 'method' argument. """ method = kwargs.pop('method') data = method(self, *args, **kwargs) if isinstance(data, bytes): return SafeBytes(data) else: return SafeText(data) decode = curry(_proxy_method, method=bytes.decode) class SafeText(six.text_type, SafeData): """ A unicode (Python 2) / str (Python 3) subclass that has been specifically marked as "safe" for HTML output purposes. """ def __add__(self, rhs): """ Concatenating a safe unicode string with another safe byte string or safe unicode string is safe. Otherwise, the result is no longer safe. """ t = super(SafeText, self).__add__(rhs) if isinstance(rhs, SafeData): return SafeText(t) return t def _proxy_method(self, *args, **kwargs): """ Wrap a call to a normal unicode method up so that we return safe results. The method that is being wrapped is passed in the 'method' argument. """ method = kwargs.pop('method') data = method(self, *args, **kwargs) if isinstance(data, bytes): return SafeBytes(data) else: return SafeText(data) encode = curry(_proxy_method, method=six.text_type.encode) if six.PY3: SafeString = SafeText else: SafeString = SafeBytes # backwards compatibility for Python 2 SafeUnicode = SafeText def _safety_decorator(safety_marker, func): @wraps(func) def wrapped(*args, **kwargs): return safety_marker(func(*args, **kwargs)) return wrapped def mark_safe(s): """ Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string or unicode object is appropriate. If used on a method as a decorator, mark the returned data as safe. Can be called multiple times on a single string. """ if hasattr(s, '__html__'): return s if isinstance(s, bytes) or (isinstance(s, Promise) and s._delegate_bytes): return SafeBytes(s) if isinstance(s, (six.text_type, Promise)): return SafeText(s) if callable(s): return _safety_decorator(mark_safe, s) return SafeString(str(s)) def mark_for_escaping(s): """ Explicitly mark a string as requiring HTML escaping upon output. Has no effect on SafeData subclasses. Can be called multiple times on a single string (the resulting escaping is only applied once). """ warnings.warn('mark_for_escaping() is deprecated.', RemovedInDjango20Warning) if hasattr(s, '__html__') or isinstance(s, EscapeData): return s if isinstance(s, bytes) or (isinstance(s, Promise) and s._delegate_bytes): return EscapeBytes(s) if isinstance(s, (six.text_type, Promise)): return EscapeText(s) return EscapeString(str(s))
8c5fe4cdaf2936d163a6303fbb0be3c9968c6b140d9e07aba318602d3476a4f7
""" Based on "python-archive" -- http://pypi.python.org/pypi/python-archive/ Copyright (c) 2010 Gary Wilson Jr. <[email protected]> and contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import os import shutil import tarfile import zipfile from django.utils import six class ArchiveException(Exception): """ Base exception class for all archive errors. """ class UnrecognizedArchiveFormat(ArchiveException): """ Error raised when passed file is not a recognized archive format. """ def extract(path, to_path=''): """ Unpack the tar or zip file at the specified path to the directory specified by to_path. """ with Archive(path) as archive: archive.extract(to_path) class Archive(object): """ The external API class that encapsulates an archive implementation. """ def __init__(self, file): self._archive = self._archive_cls(file)(file) @staticmethod def _archive_cls(file): cls = None if isinstance(file, six.string_types): filename = file else: try: filename = file.name except AttributeError: raise UnrecognizedArchiveFormat( "File object not a recognized archive format.") base, tail_ext = os.path.splitext(filename.lower()) cls = extension_map.get(tail_ext) if not cls: base, ext = os.path.splitext(base) cls = extension_map.get(ext) if not cls: raise UnrecognizedArchiveFormat( "Path not a recognized archive format: %s" % filename) return cls def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() def extract(self, to_path=''): self._archive.extract(to_path) def list(self): self._archive.list() def close(self): self._archive.close() class BaseArchive(object): """ Base Archive class. Implementations should inherit this class. """ def split_leading_dir(self, path): path = str(path) path = path.lstrip('/').lstrip('\\') if '/' in path and (('\\' in path and path.find('/') < path.find('\\')) or '\\' not in path): return path.split('/', 1) elif '\\' in path: return path.split('\\', 1) else: return path, '' def has_leading_dir(self, paths): """ Returns true if all the paths have the same leading path name (i.e., everything is in one subdirectory in an archive) """ common_prefix = None for path in paths: prefix, rest = self.split_leading_dir(path) if not prefix: return False elif common_prefix is None: common_prefix = prefix elif prefix != common_prefix: return False return True def extract(self): raise NotImplementedError('subclasses of BaseArchive must provide an extract() method') def list(self): raise NotImplementedError('subclasses of BaseArchive must provide a list() method') class TarArchive(BaseArchive): def __init__(self, file): self._archive = tarfile.open(file) def list(self, *args, **kwargs): self._archive.list(*args, **kwargs) def extract(self, to_path): members = self._archive.getmembers() leading = self.has_leading_dir(x.name for x in members) for member in members: name = member.name if leading: name = self.split_leading_dir(name)[1] filename = os.path.join(to_path, name) if member.isdir(): if filename and not os.path.exists(filename): os.makedirs(filename) else: try: extracted = self._archive.extractfile(member) except (KeyError, AttributeError) as exc: # Some corrupt tar files seem to produce this # (specifically bad symlinks) print("In the tar file %s the member %s is invalid: %s" % (name, member.name, exc)) else: dirname = os.path.dirname(filename) if dirname and not os.path.exists(dirname): os.makedirs(dirname) with open(filename, 'wb') as outfile: shutil.copyfileobj(extracted, outfile) finally: if extracted: extracted.close() def close(self): self._archive.close() class ZipArchive(BaseArchive): def __init__(self, file): self._archive = zipfile.ZipFile(file) def list(self, *args, **kwargs): self._archive.printdir(*args, **kwargs) def extract(self, to_path): namelist = self._archive.namelist() leading = self.has_leading_dir(namelist) for name in namelist: data = self._archive.read(name) if leading: name = self.split_leading_dir(name)[1] filename = os.path.join(to_path, name) dirname = os.path.dirname(filename) if dirname and not os.path.exists(dirname): os.makedirs(dirname) if filename.endswith(('/', '\\')): # A directory if not os.path.exists(filename): os.makedirs(filename) else: with open(filename, 'wb') as outfile: outfile.write(data) def close(self): self._archive.close() extension_map = { '.tar': TarArchive, '.tar.bz2': TarArchive, '.tar.gz': TarArchive, '.tgz': TarArchive, '.tz2': TarArchive, '.zip': ZipArchive, }
df83d01ae388ba001b6b0e03985a55ace740506e679dcb1466636f3692997207
""" Utility functions for generating "lorem ipsum" Latin text. """ from __future__ import unicode_literals import random COMMON_P = ( '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.' ) WORDS = ( 'exercitationem', 'perferendis', 'perspiciatis', 'laborum', 'eveniet', 'sunt', 'iure', 'nam', 'nobis', 'eum', 'cum', 'officiis', 'excepturi', 'odio', 'consectetur', 'quasi', 'aut', 'quisquam', 'vel', 'eligendi', 'itaque', 'non', 'odit', 'tempore', 'quaerat', 'dignissimos', 'facilis', 'neque', 'nihil', 'expedita', 'vitae', 'vero', 'ipsum', 'nisi', 'animi', 'cumque', 'pariatur', 'velit', 'modi', 'natus', 'iusto', 'eaque', 'sequi', 'illo', 'sed', 'ex', 'et', 'voluptatibus', 'tempora', 'veritatis', 'ratione', 'assumenda', 'incidunt', 'nostrum', 'placeat', 'aliquid', 'fuga', 'provident', 'praesentium', 'rem', 'necessitatibus', 'suscipit', 'adipisci', 'quidem', 'possimus', 'voluptas', 'debitis', 'sint', 'accusantium', 'unde', 'sapiente', 'voluptate', 'qui', 'aspernatur', 'laudantium', 'soluta', 'amet', 'quo', 'aliquam', 'saepe', 'culpa', 'libero', 'ipsa', 'dicta', 'reiciendis', 'nesciunt', 'doloribus', 'autem', 'impedit', 'minima', 'maiores', 'repudiandae', 'ipsam', 'obcaecati', 'ullam', 'enim', 'totam', 'delectus', 'ducimus', 'quis', 'voluptates', 'dolores', 'molestiae', 'harum', 'dolorem', 'quia', 'voluptatem', 'molestias', 'magni', 'distinctio', 'omnis', 'illum', 'dolorum', 'voluptatum', 'ea', 'quas', 'quam', 'corporis', 'quae', 'blanditiis', 'atque', 'deserunt', 'laboriosam', 'earum', 'consequuntur', 'hic', 'cupiditate', 'quibusdam', 'accusamus', 'ut', 'rerum', 'error', 'minus', 'eius', 'ab', 'ad', 'nemo', 'fugit', 'officia', 'at', 'in', 'id', 'quos', 'reprehenderit', 'numquam', 'iste', 'fugiat', 'sit', 'inventore', 'beatae', 'repellendus', 'magnam', 'recusandae', 'quod', 'explicabo', 'doloremque', 'aperiam', 'consequatur', 'asperiores', 'commodi', 'optio', 'dolor', 'labore', 'temporibus', 'repellat', 'veniam', 'architecto', 'est', 'esse', 'mollitia', 'nulla', 'a', 'similique', 'eos', 'alias', 'dolore', 'tenetur', 'deleniti', 'porro', 'facere', 'maxime', 'corrupti', ) COMMON_WORDS = ( 'lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipisicing', 'elit', 'sed', 'do', 'eiusmod', 'tempor', 'incididunt', 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua', ) def sentence(): """ Returns a randomly generated sentence of lorem ipsum text. The first word is capitalized, and the sentence ends in either a period or question mark. Commas are added at random. """ # Determine the number of comma-separated sections and number of words in # each section for this sentence. sections = [' '.join(random.sample(WORDS, random.randint(3, 12))) for i in range(random.randint(1, 5))] s = ', '.join(sections) # Convert to sentence case and add end punctuation. return '%s%s%s' % (s[0].upper(), s[1:], random.choice('?.')) def paragraph(): """ Returns a randomly generated paragraph of lorem ipsum text. The paragraph consists of between 1 and 4 sentences, inclusive. """ return ' '.join(sentence() for i in range(random.randint(1, 4))) def paragraphs(count, common=True): """ Returns a list of paragraphs as returned by paragraph(). If `common` is True, then the first paragraph will be the standard 'lorem ipsum' paragraph. Otherwise, the first paragraph will be random Latin text. Either way, subsequent paragraphs will be random Latin text. """ paras = [] for i in range(count): if common and i == 0: paras.append(COMMON_P) else: paras.append(paragraph()) return paras def words(count, common=True): """ Returns a string of `count` lorem ipsum words separated by a single space. If `common` is True, then the first 19 words will be the standard 'lorem ipsum' words. Otherwise, all words will be selected randomly. """ if common: word_list = list(COMMON_WORDS) else: word_list = [] c = len(word_list) if count > c: count -= c while count > 0: c = min(count, len(WORDS)) count -= c word_list += random.sample(WORDS, c) else: word_list = word_list[:count] return ' '.join(word_list)
cdc11c68624a1873712999155cba0990cdbdca6cae39a10d7a8b949a5f8e4224
""" Syndication feed generation library -- used for generating RSS, etc. Sample usage: >>> from django.utils import feedgenerator >>> feed = feedgenerator.Rss201rev2Feed( ... title="Poynter E-Media Tidbits", ... link="http://www.poynter.org/column.asp?id=31", ... description="A group Weblog by the sharpest minds in online media/journalism/publishing.", ... language="en", ... ) >>> feed.add_item( ... title="Hello", ... link="http://www.holovaty.com/test/", ... description="Testing." ... ) >>> with open('test.rss', 'w') as fp: ... feed.write(fp, 'utf-8') For definitions of the different versions of RSS, see: http://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss """ from __future__ import unicode_literals import datetime import warnings from django.utils import datetime_safe, six from django.utils.deprecation import RemovedInDjango20Warning from django.utils.encoding import force_text, iri_to_uri from django.utils.six import StringIO from django.utils.six.moves.urllib.parse import urlparse from django.utils.timezone import utc from django.utils.xmlutils import SimplerXMLGenerator def rfc2822_date(date): # We can't use strftime() because it produces locale-dependent results, so # we have to map english month and day names manually months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',) days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') # Support datetime objects older than 1900 date = datetime_safe.new_datetime(date) # We do this ourselves to be timezone aware, email.Utils is not tz aware. dow = days[date.weekday()] month = months[date.month - 1] time_str = date.strftime('%s, %%d %s %%Y %%H:%%M:%%S ' % (dow, month)) if six.PY2: # strftime returns a byte string in Python 2 time_str = time_str.decode('utf-8') offset = date.utcoffset() # Historically, this function assumes that naive datetimes are in UTC. if offset is None: return time_str + '-0000' else: timezone = (offset.days * 24 * 60) + (offset.seconds // 60) hour, minute = divmod(timezone, 60) return time_str + '%+03d%02d' % (hour, minute) def rfc3339_date(date): # Support datetime objects older than 1900 date = datetime_safe.new_datetime(date) time_str = date.strftime('%Y-%m-%dT%H:%M:%S') if six.PY2: # strftime returns a byte string in Python 2 time_str = time_str.decode('utf-8') offset = date.utcoffset() # Historically, this function assumes that naive datetimes are in UTC. if offset is None: return time_str + 'Z' else: timezone = (offset.days * 24 * 60) + (offset.seconds // 60) hour, minute = divmod(timezone, 60) return time_str + '%+03d:%02d' % (hour, minute) def get_tag_uri(url, date): """ Creates a TagURI. See http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id """ bits = urlparse(url) d = '' if date is not None: d = ',%s' % datetime_safe.new_datetime(date).strftime('%Y-%m-%d') return 'tag:%s%s:%s/%s' % (bits.hostname, d, bits.path, bits.fragment) class SyndicationFeed(object): "Base class for all syndication feeds. Subclasses should provide write()" def __init__(self, title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs): def to_unicode(s): return force_text(s, strings_only=True) if categories: categories = [force_text(c) for c in categories] if ttl is not None: # Force ints to unicode ttl = force_text(ttl) self.feed = { 'title': to_unicode(title), 'link': iri_to_uri(link), 'description': to_unicode(description), 'language': to_unicode(language), 'author_email': to_unicode(author_email), 'author_name': to_unicode(author_name), 'author_link': iri_to_uri(author_link), 'subtitle': to_unicode(subtitle), 'categories': categories or (), 'feed_url': iri_to_uri(feed_url), 'feed_copyright': to_unicode(feed_copyright), 'id': feed_guid or link, 'ttl': ttl, } self.feed.update(kwargs) self.items = [] def add_item(self, title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, unique_id_is_permalink=None, enclosure=None, categories=(), item_copyright=None, ttl=None, updateddate=None, enclosures=None, **kwargs): """ Adds an item to the feed. All args are expected to be Python Unicode objects except pubdate and updateddate, which are datetime.datetime objects, and enclosures, which is an iterable of instances of the Enclosure class. """ def to_unicode(s): return force_text(s, strings_only=True) if categories: categories = [to_unicode(c) for c in categories] if ttl is not None: # Force ints to unicode ttl = force_text(ttl) if enclosure is None: enclosures = [] if enclosures is None else enclosures else: warnings.warn( "The enclosure keyword argument is deprecated, " "use enclosures instead.", RemovedInDjango20Warning, stacklevel=2, ) enclosures = [enclosure] item = { 'title': to_unicode(title), 'link': iri_to_uri(link), 'description': to_unicode(description), 'author_email': to_unicode(author_email), 'author_name': to_unicode(author_name), 'author_link': iri_to_uri(author_link), 'pubdate': pubdate, 'updateddate': updateddate, 'comments': to_unicode(comments), 'unique_id': to_unicode(unique_id), 'unique_id_is_permalink': unique_id_is_permalink, 'enclosures': enclosures, 'categories': categories or (), 'item_copyright': to_unicode(item_copyright), 'ttl': ttl, } item.update(kwargs) self.items.append(item) def num_items(self): return len(self.items) def root_attributes(self): """ Return extra attributes to place on the root (i.e. feed/channel) element. Called from write(). """ return {} def add_root_elements(self, handler): """ Add elements in the root (i.e. feed/channel) element. Called from write(). """ pass def item_attributes(self, item): """ Return extra attributes to place on each item (i.e. item/entry) element. """ return {} def add_item_elements(self, handler, item): """ Add elements on each item (i.e. item/entry) element. """ pass def write(self, outfile, encoding): """ Outputs the feed in the given encoding to outfile, which is a file-like object. Subclasses should override this. """ raise NotImplementedError('subclasses of SyndicationFeed must provide a write() method') def writeString(self, encoding): """ Returns the feed in the given encoding as a string. """ s = StringIO() self.write(s, encoding) return s.getvalue() def latest_post_date(self): """ Returns the latest item's pubdate or updateddate. If no items have either of these attributes this returns the current UTC date/time. """ latest_date = None date_keys = ('updateddate', 'pubdate') for item in self.items: for date_key in date_keys: item_date = item.get(date_key) if item_date: if latest_date is None or item_date > latest_date: latest_date = item_date # datetime.now(tz=utc) is slower, as documented in django.utils.timezone.now return latest_date or datetime.datetime.utcnow().replace(tzinfo=utc) class Enclosure(object): "Represents an RSS enclosure" def __init__(self, url, length, mime_type): "All args are expected to be Python Unicode objects" self.length, self.mime_type = length, mime_type self.url = iri_to_uri(url) class RssFeed(SyndicationFeed): content_type = 'application/rss+xml; charset=utf-8' def write(self, outfile, encoding): handler = SimplerXMLGenerator(outfile, encoding) handler.startDocument() handler.startElement("rss", self.rss_attributes()) handler.startElement("channel", self.root_attributes()) self.add_root_elements(handler) self.write_items(handler) self.endChannelElement(handler) handler.endElement("rss") def rss_attributes(self): return {"version": self._version, "xmlns:atom": "http://www.w3.org/2005/Atom"} def write_items(self, handler): for item in self.items: handler.startElement('item', self.item_attributes(item)) self.add_item_elements(handler, item) handler.endElement("item") def add_root_elements(self, handler): handler.addQuickElement("title", self.feed['title']) handler.addQuickElement("link", self.feed['link']) handler.addQuickElement("description", self.feed['description']) if self.feed['feed_url'] is not None: handler.addQuickElement("atom:link", None, {"rel": "self", "href": self.feed['feed_url']}) if self.feed['language'] is not None: handler.addQuickElement("language", self.feed['language']) for cat in self.feed['categories']: handler.addQuickElement("category", cat) if self.feed['feed_copyright'] is not None: handler.addQuickElement("copyright", self.feed['feed_copyright']) handler.addQuickElement("lastBuildDate", rfc2822_date(self.latest_post_date())) if self.feed['ttl'] is not None: handler.addQuickElement("ttl", self.feed['ttl']) def endChannelElement(self, handler): handler.endElement("channel") @property def mime_type(self): warnings.warn( 'The mime_type attribute of RssFeed is deprecated. ' 'Use content_type instead.', RemovedInDjango20Warning, stacklevel=2 ) return self.content_type class RssUserland091Feed(RssFeed): _version = "0.91" def add_item_elements(self, handler, item): handler.addQuickElement("title", item['title']) handler.addQuickElement("link", item['link']) if item['description'] is not None: handler.addQuickElement("description", item['description']) class Rss201rev2Feed(RssFeed): # Spec: http://blogs.law.harvard.edu/tech/rss _version = "2.0" def add_item_elements(self, handler, item): handler.addQuickElement("title", item['title']) handler.addQuickElement("link", item['link']) if item['description'] is not None: handler.addQuickElement("description", item['description']) # Author information. if item["author_name"] and item["author_email"]: handler.addQuickElement("author", "%s (%s)" % (item['author_email'], item['author_name'])) elif item["author_email"]: handler.addQuickElement("author", item["author_email"]) elif item["author_name"]: handler.addQuickElement( "dc:creator", item["author_name"], {"xmlns:dc": "http://purl.org/dc/elements/1.1/"} ) if item['pubdate'] is not None: handler.addQuickElement("pubDate", rfc2822_date(item['pubdate'])) if item['comments'] is not None: handler.addQuickElement("comments", item['comments']) if item['unique_id'] is not None: guid_attrs = {} if isinstance(item.get('unique_id_is_permalink'), bool): guid_attrs['isPermaLink'] = str(item['unique_id_is_permalink']).lower() handler.addQuickElement("guid", item['unique_id'], guid_attrs) if item['ttl'] is not None: handler.addQuickElement("ttl", item['ttl']) # Enclosure. if item['enclosures']: enclosures = list(item['enclosures']) if len(enclosures) > 1: raise ValueError( "RSS feed items may only have one enclosure, see " "http://www.rssboard.org/rss-profile#element-channel-item-enclosure" ) enclosure = enclosures[0] handler.addQuickElement('enclosure', '', { 'url': enclosure.url, 'length': enclosure.length, 'type': enclosure.mime_type, }) # Categories. for cat in item['categories']: handler.addQuickElement("category", cat) class Atom1Feed(SyndicationFeed): # Spec: https://tools.ietf.org/html/rfc4287 content_type = 'application/atom+xml; charset=utf-8' ns = "http://www.w3.org/2005/Atom" def write(self, outfile, encoding): handler = SimplerXMLGenerator(outfile, encoding) handler.startDocument() handler.startElement('feed', self.root_attributes()) self.add_root_elements(handler) self.write_items(handler) handler.endElement("feed") def root_attributes(self): if self.feed['language'] is not None: return {"xmlns": self.ns, "xml:lang": self.feed['language']} else: return {"xmlns": self.ns} def add_root_elements(self, handler): handler.addQuickElement("title", self.feed['title']) handler.addQuickElement("link", "", {"rel": "alternate", "href": self.feed['link']}) if self.feed['feed_url'] is not None: handler.addQuickElement("link", "", {"rel": "self", "href": self.feed['feed_url']}) handler.addQuickElement("id", self.feed['id']) handler.addQuickElement("updated", rfc3339_date(self.latest_post_date())) if self.feed['author_name'] is not None: handler.startElement("author", {}) handler.addQuickElement("name", self.feed['author_name']) if self.feed['author_email'] is not None: handler.addQuickElement("email", self.feed['author_email']) if self.feed['author_link'] is not None: handler.addQuickElement("uri", self.feed['author_link']) handler.endElement("author") if self.feed['subtitle'] is not None: handler.addQuickElement("subtitle", self.feed['subtitle']) for cat in self.feed['categories']: handler.addQuickElement("category", "", {"term": cat}) if self.feed['feed_copyright'] is not None: handler.addQuickElement("rights", self.feed['feed_copyright']) def write_items(self, handler): for item in self.items: handler.startElement("entry", self.item_attributes(item)) self.add_item_elements(handler, item) handler.endElement("entry") def add_item_elements(self, handler, item): handler.addQuickElement("title", item['title']) handler.addQuickElement("link", "", {"href": item['link'], "rel": "alternate"}) if item['pubdate'] is not None: handler.addQuickElement('published', rfc3339_date(item['pubdate'])) if item['updateddate'] is not None: handler.addQuickElement('updated', rfc3339_date(item['updateddate'])) # Author information. if item['author_name'] is not None: handler.startElement("author", {}) handler.addQuickElement("name", item['author_name']) if item['author_email'] is not None: handler.addQuickElement("email", item['author_email']) if item['author_link'] is not None: handler.addQuickElement("uri", item['author_link']) handler.endElement("author") # Unique ID. if item['unique_id'] is not None: unique_id = item['unique_id'] else: unique_id = get_tag_uri(item['link'], item['pubdate']) handler.addQuickElement("id", unique_id) # Summary. if item['description'] is not None: handler.addQuickElement("summary", item['description'], {"type": "html"}) # Enclosures. for enclosure in item['enclosures']: handler.addQuickElement('link', '', { 'rel': 'enclosure', 'href': enclosure.url, 'length': enclosure.length, 'type': enclosure.mime_type, }) # Categories. for cat in item['categories']: handler.addQuickElement("category", "", {"term": cat}) # Rights. if item['item_copyright'] is not None: handler.addQuickElement("rights", item['item_copyright']) @property def mime_type(self): warnings.warn( 'The mime_type attribute of Atom1Feed is deprecated. ' 'Use content_type instead.', RemovedInDjango20Warning, stacklevel=2 ) return self.content_type # This isolates the decision of what the system default is, so calling code can # do "feedgenerator.DefaultFeed" instead of "feedgenerator.Rss201rev2Feed". DefaultFeed = Rss201rev2Feed
da41322c2e1be9e74c79ecbee642438c9307a65ed310d486a3321384da4df99c
from importlib import import_module from django.utils.version import get_docs_version def deconstructible(*args, **kwargs): """ Class decorator that allow the decorated class to be serialized by the migrations subsystem. Accepts an optional kwarg `path` to specify the import path. """ path = kwargs.pop('path', None) def decorator(klass): def __new__(cls, *args, **kwargs): # We capture the arguments to make returning them trivial obj = super(klass, cls).__new__(cls) obj._constructor_args = (args, kwargs) return obj def deconstruct(obj): """ Returns a 3-tuple of class import path, positional arguments, and keyword arguments. """ # Python 2/fallback version if path: module_name, _, name = path.rpartition('.') else: module_name = obj.__module__ name = obj.__class__.__name__ # Make sure it's actually there and not an inner class module = import_module(module_name) if not hasattr(module, name): raise ValueError( "Could not find object %s in %s.\n" "Please note that you cannot serialize things like inner " "classes. Please move the object into the main module " "body to use migrations.\n" "For more information, see " "https://docs.djangoproject.com/en/%s/topics/migrations/#serializing-values" % (name, module_name, get_docs_version())) return ( path or '%s.%s' % (obj.__class__.__module__, name), obj._constructor_args[0], obj._constructor_args[1], ) klass.__new__ = staticmethod(__new__) klass.deconstruct = deconstruct return klass if not args: return decorator return decorator(*args, **kwargs)
95297e9eebf252711736ed258372b2645d4e1d7d7cb689fecac9d774d8a0b7d6
from __future__ import unicode_literals import os.path import re from django.utils import six # backport of Python 3.4's glob.escape if six.PY3: from glob import escape as glob_escape else: _magic_check = re.compile('([*?[])') def glob_escape(pathname): """ Escape all special characters. """ drive, pathname = os.path.splitdrive(pathname) pathname = _magic_check.sub(r'[\1]', pathname) return drive + pathname
d33cb1297929f933ab3b1d44b48c0f7bc149cf7c99c4c47ca49153ba3d4b9130
import copy import operator import warnings from functools import total_ordering, wraps from django.utils import six from django.utils.deprecation import RemovedInDjango20Warning # You can't trivially replace this with `functools.partial` because this binds # to classes and returns bound instances, whereas functools.partial (on # CPython) is a type and its instances don't bind. def curry(_curried_func, *args, **kwargs): def _curried(*moreargs, **morekwargs): return _curried_func(*(args + moreargs), **dict(kwargs, **morekwargs)) return _curried class cached_property(object): """ Decorator that converts a method with a single self argument into a property cached on the instance. Optional ``name`` argument allows you to make cached properties of other methods. (e.g. url = cached_property(get_absolute_url, name='url') ) """ def __init__(self, func, name=None): self.func = func self.__doc__ = getattr(func, '__doc__') self.name = name or func.__name__ def __get__(self, instance, cls=None): if instance is None: return self res = instance.__dict__[self.name] = self.func(instance) return res class Promise(object): """ This is just a base class for the proxy class created in the closure of the lazy function. It can be used to recognize promises in code. """ pass def lazy(func, *resultclasses): """ Turns any callable into a lazy evaluated callable. You need to give result classes or types -- at least one is needed so that the automatic forcing of the lazy evaluation code is triggered. Results are not memoized; the function is evaluated on every access. """ @total_ordering class __proxy__(Promise): """ Encapsulate a function call and act as a proxy for methods that are called on the result of that function. The function is not evaluated until one of the methods on the result is called. """ __prepared = False def __init__(self, args, kw): self.__args = args self.__kw = kw if not self.__prepared: self.__prepare_class__() self.__prepared = True def __reduce__(self): return ( _lazy_proxy_unpickle, (func, self.__args, self.__kw) + resultclasses ) def __repr__(self): return repr(self.__cast()) @classmethod def __prepare_class__(cls): for resultclass in resultclasses: for type_ in resultclass.mro(): for method_name in type_.__dict__.keys(): # All __promise__ return the same wrapper method, they # look up the correct implementation when called. if hasattr(cls, method_name): continue meth = cls.__promise__(method_name) setattr(cls, method_name, meth) cls._delegate_bytes = bytes in resultclasses cls._delegate_text = six.text_type in resultclasses assert not (cls._delegate_bytes and cls._delegate_text), ( "Cannot call lazy() with both bytes and text return types.") if cls._delegate_text: if six.PY3: cls.__str__ = cls.__text_cast else: cls.__unicode__ = cls.__text_cast cls.__str__ = cls.__bytes_cast_encoded elif cls._delegate_bytes: if six.PY3: cls.__bytes__ = cls.__bytes_cast else: cls.__str__ = cls.__bytes_cast @classmethod def __promise__(cls, method_name): # Builds a wrapper around some magic method def __wrapper__(self, *args, **kw): # Automatically triggers the evaluation of a lazy value and # applies the given magic method of the result type. res = func(*self.__args, **self.__kw) return getattr(res, method_name)(*args, **kw) return __wrapper__ def __text_cast(self): return func(*self.__args, **self.__kw) def __bytes_cast(self): return bytes(func(*self.__args, **self.__kw)) def __bytes_cast_encoded(self): return func(*self.__args, **self.__kw).encode('utf-8') def __cast(self): if self._delegate_bytes: return self.__bytes_cast() elif self._delegate_text: return self.__text_cast() else: return func(*self.__args, **self.__kw) def __str__(self): # object defines __str__(), so __prepare_class__() won't overload # a __str__() method from the proxied class. return str(self.__cast()) def __ne__(self, other): if isinstance(other, Promise): other = other.__cast() return self.__cast() != other def __eq__(self, other): if isinstance(other, Promise): other = other.__cast() return self.__cast() == other def __lt__(self, other): if isinstance(other, Promise): other = other.__cast() return self.__cast() < other def __hash__(self): return hash(self.__cast()) def __mod__(self, rhs): if self._delegate_bytes and six.PY2: return bytes(self) % rhs elif self._delegate_text: return six.text_type(self) % rhs return self.__cast() % rhs def __deepcopy__(self, memo): # Instances of this class are effectively immutable. It's just a # collection of functions. So we don't need to do anything # complicated for copying. memo[id(self)] = self return self @wraps(func) def __wrapper__(*args, **kw): # Creates the proxy object, instead of the actual value. return __proxy__(args, kw) return __wrapper__ def _lazy_proxy_unpickle(func, args, kwargs, *resultclasses): return lazy(func, *resultclasses)(*args, **kwargs) def lazystr(text): """ Shortcut for the common case of a lazy callable that returns str. """ from django.utils.encoding import force_text # Avoid circular import return lazy(force_text, six.text_type)(text) def allow_lazy(func, *resultclasses): warnings.warn( "django.utils.functional.allow_lazy() is deprecated in favor of " "django.utils.functional.keep_lazy()", RemovedInDjango20Warning, 2) return keep_lazy(*resultclasses)(func) def keep_lazy(*resultclasses): """ A decorator that allows a function to be called with one or more lazy arguments. If none of the args are lazy, the function is evaluated immediately, otherwise a __proxy__ is returned that will evaluate the function when needed. """ if not resultclasses: raise TypeError("You must pass at least one argument to keep_lazy().") def decorator(func): lazy_func = lazy(func, *resultclasses) @wraps(func) def wrapper(*args, **kwargs): for arg in list(args) + list(six.itervalues(kwargs)): if isinstance(arg, Promise): break else: return func(*args, **kwargs) return lazy_func(*args, **kwargs) return wrapper return decorator def keep_lazy_text(func): """ A decorator for functions that accept lazy arguments and return text. """ return keep_lazy(six.text_type)(func) empty = object() def new_method_proxy(func): def inner(self, *args): if self._wrapped is empty: self._setup() return func(self._wrapped, *args) return inner class LazyObject(object): """ A wrapper for another class that can be used to delay instantiation of the wrapped class. By subclassing, you have the opportunity to intercept and alter the instantiation. If you don't need to do that, use SimpleLazyObject. """ # Avoid infinite recursion when tracing __init__ (#19456). _wrapped = None def __init__(self): # Note: if a subclass overrides __init__(), it will likely need to # override __copy__() and __deepcopy__() as well. self._wrapped = empty __getattr__ = new_method_proxy(getattr) def __setattr__(self, name, value): if name == "_wrapped": # Assign to __dict__ to avoid infinite __setattr__ loops. self.__dict__["_wrapped"] = value else: if self._wrapped is empty: self._setup() setattr(self._wrapped, name, value) def __delattr__(self, name): if name == "_wrapped": raise TypeError("can't delete _wrapped.") if self._wrapped is empty: self._setup() delattr(self._wrapped, name) def _setup(self): """ Must be implemented by subclasses to initialize the wrapped object. """ raise NotImplementedError('subclasses of LazyObject must provide a _setup() method') # Because we have messed with __class__ below, we confuse pickle as to what # class we are pickling. We're going to have to initialize the wrapped # object to successfully pickle it, so we might as well just pickle the # wrapped object since they're supposed to act the same way. # # Unfortunately, if we try to simply act like the wrapped object, the ruse # will break down when pickle gets our id(). Thus we end up with pickle # thinking, in effect, that we are a distinct object from the wrapped # object, but with the same __dict__. This can cause problems (see #25389). # # So instead, we define our own __reduce__ method and custom unpickler. We # pickle the wrapped object as the unpickler's argument, so that pickle # will pickle it normally, and then the unpickler simply returns its # argument. def __reduce__(self): if self._wrapped is empty: self._setup() return (unpickle_lazyobject, (self._wrapped,)) # We have to explicitly override __getstate__ so that older versions of # pickle don't try to pickle the __dict__ (which in the case of a # SimpleLazyObject may contain a lambda). The value will end up being # ignored by our __reduce__ and custom unpickler. def __getstate__(self): return {} def __copy__(self): if self._wrapped is empty: # If uninitialized, copy the wrapper. Use type(self), not # self.__class__, because the latter is proxied. return type(self)() else: # If initialized, return a copy of the wrapped object. return copy.copy(self._wrapped) def __deepcopy__(self, memo): if self._wrapped is empty: # We have to use type(self), not self.__class__, because the # latter is proxied. result = type(self)() memo[id(self)] = result return result return copy.deepcopy(self._wrapped, memo) if six.PY3: __bytes__ = new_method_proxy(bytes) __str__ = new_method_proxy(str) __bool__ = new_method_proxy(bool) else: __str__ = new_method_proxy(str) __unicode__ = new_method_proxy(unicode) # NOQA: unicode undefined on PY3 __nonzero__ = new_method_proxy(bool) # Introspection support __dir__ = new_method_proxy(dir) # Need to pretend to be the wrapped class, for the sake of objects that # care about this (especially in equality tests) __class__ = property(new_method_proxy(operator.attrgetter("__class__"))) __eq__ = new_method_proxy(operator.eq) __ne__ = new_method_proxy(operator.ne) __hash__ = new_method_proxy(hash) # List/Tuple/Dictionary methods support __getitem__ = new_method_proxy(operator.getitem) __setitem__ = new_method_proxy(operator.setitem) __delitem__ = new_method_proxy(operator.delitem) __iter__ = new_method_proxy(iter) __len__ = new_method_proxy(len) __contains__ = new_method_proxy(operator.contains) def unpickle_lazyobject(wrapped): """ Used to unpickle lazy objects. Just return its argument, which will be the wrapped object. """ return wrapped class SimpleLazyObject(LazyObject): """ A lazy object initialized from any function. Designed for compound objects of unknown type. For builtins or objects of known type, use django.utils.functional.lazy. """ def __init__(self, func): """ Pass in a callable that returns the object to be wrapped. If copies are made of the resulting SimpleLazyObject, which can happen in various circumstances within Django, then you must ensure that the callable can be safely run more than once and will return the same value. """ self.__dict__['_setupfunc'] = func super(SimpleLazyObject, self).__init__() def _setup(self): self._wrapped = self._setupfunc() # Return a meaningful representation of the lazy object for debugging # without evaluating the wrapped object. def __repr__(self): if self._wrapped is empty: repr_attr = self._setupfunc else: repr_attr = self._wrapped return '<%s: %r>' % (type(self).__name__, repr_attr) def __copy__(self): if self._wrapped is empty: # If uninitialized, copy the wrapper. Use SimpleLazyObject, not # self.__class__, because the latter is proxied. return SimpleLazyObject(self._setupfunc) else: # If initialized, return a copy of the wrapped object. return copy.copy(self._wrapped) def __deepcopy__(self, memo): if self._wrapped is empty: # We have to use SimpleLazyObject, not self.__class__, because the # latter is proxied. result = SimpleLazyObject(self._setupfunc) memo[id(self)] = result return result return copy.deepcopy(self._wrapped, memo) class lazy_property(property): """ A property that works with subclasses by wrapping the decorated functions of the base class. """ def __new__(cls, fget=None, fset=None, fdel=None, doc=None): if fget is not None: @wraps(fget) def fget(instance, instance_type=None, name=fget.__name__): return getattr(instance, name)() if fset is not None: @wraps(fset) def fset(instance, value, name=fset.__name__): return getattr(instance, name)(value) if fdel is not None: @wraps(fdel) def fdel(instance, name=fdel.__name__): return getattr(instance, name)() return property(fget, fset, fdel, doc) def partition(predicate, values): """ Splits the values into two sets, based on the return value of the function (True/False). e.g.: >>> partition(lambda x: x > 3, range(5)) [0, 1, 2, 3], [4] """ results = ([], []) for item in values: results[predicate(item)].append(item) return results
e70d67a66131ae8beeab1108e4af9e73c2ba11f02c9798f077000e1151754dc7
# This code was mostly based on ipaddr-py # Copyright 2007 Google Inc. https://github.com/google/ipaddr-py # Licensed under the Apache License, Version 2.0 (the "License"). import re from django.core.exceptions import ValidationError from django.utils.six.moves import range from django.utils.translation import ugettext_lazy as _ def clean_ipv6_address(ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address.")): """ Cleans an IPv6 address string. Validity is checked by calling is_valid_ipv6_address() - if an invalid address is passed, ValidationError is raised. Replaces the longest continuous zero-sequence with "::" and removes leading zeroes and makes sure all hextets are lowercase. Args: ip_str: A valid IPv6 address. unpack_ipv4: if an IPv4-mapped address is found, return the plain IPv4 address (default=False). error_message: An error message used in the ValidationError. Returns: A compressed IPv6 address, or the same value """ best_doublecolon_start = -1 best_doublecolon_len = 0 doublecolon_start = -1 doublecolon_len = 0 if not is_valid_ipv6_address(ip_str): raise ValidationError(error_message, code='invalid') # This algorithm can only handle fully exploded # IP strings ip_str = _explode_shorthand_ip_string(ip_str) ip_str = _sanitize_ipv4_mapping(ip_str) # If needed, unpack the IPv4 and return straight away # - no need in running the rest of the algorithm if unpack_ipv4: ipv4_unpacked = _unpack_ipv4(ip_str) if ipv4_unpacked: return ipv4_unpacked hextets = ip_str.split(":") for index in range(len(hextets)): # Remove leading zeroes if '.' not in hextets[index]: hextets[index] = hextets[index].lstrip('0') if not hextets[index]: hextets[index] = '0' # Determine best hextet to compress if hextets[index] == '0': doublecolon_len += 1 if doublecolon_start == -1: # Start of a sequence of zeros. doublecolon_start = index if doublecolon_len > best_doublecolon_len: # This is the longest sequence of zeros so far. best_doublecolon_len = doublecolon_len best_doublecolon_start = doublecolon_start else: doublecolon_len = 0 doublecolon_start = -1 # Compress the most suitable hextet if best_doublecolon_len > 1: best_doublecolon_end = (best_doublecolon_start + best_doublecolon_len) # For zeros at the end of the address. if best_doublecolon_end == len(hextets): hextets += [''] hextets[best_doublecolon_start:best_doublecolon_end] = [''] # For zeros at the beginning of the address. if best_doublecolon_start == 0: hextets = [''] + hextets result = ":".join(hextets) return result.lower() def _sanitize_ipv4_mapping(ip_str): """ Sanitize IPv4 mapping in an expanded IPv6 address. This converts ::ffff:0a0a:0a0a to ::ffff:10.10.10.10. If there is nothing to sanitize, returns an unchanged string. Args: ip_str: A string, the expanded IPv6 address. Returns: The sanitized output string, if applicable. """ if not ip_str.lower().startswith('0000:0000:0000:0000:0000:ffff:'): # not an ipv4 mapping return ip_str hextets = ip_str.split(':') if '.' in hextets[-1]: # already sanitized return ip_str ipv4_address = "%d.%d.%d.%d" % ( int(hextets[6][0:2], 16), int(hextets[6][2:4], 16), int(hextets[7][0:2], 16), int(hextets[7][2:4], 16), ) result = ':'.join(hextets[0:6]) result += ':' + ipv4_address return result def _unpack_ipv4(ip_str): """ Unpack an IPv4 address that was mapped in a compressed IPv6 address. This converts 0000:0000:0000:0000:0000:ffff:10.10.10.10 to 10.10.10.10. If there is nothing to sanitize, returns None. Args: ip_str: A string, the expanded IPv6 address. Returns: The unpacked IPv4 address, or None if there was nothing to unpack. """ if not ip_str.lower().startswith('0000:0000:0000:0000:0000:ffff:'): return None return ip_str.rsplit(':', 1)[1] def is_valid_ipv6_address(ip_str): """ Ensure we have a valid IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A boolean, True if this is a valid IPv6 address. """ from django.core.validators import validate_ipv4_address symbols_re = re.compile(r'^[0-9a-fA-F:.]+$') if not symbols_re.match(ip_str): return False # We need to have at least one ':'. if ':' not in ip_str: return False # We can only have one '::' shortener. if ip_str.count('::') > 1: return False # '::' should be encompassed by start, digits or end. if ':::' in ip_str: return False # A single colon can neither start nor end an address. if ((ip_str.startswith(':') and not ip_str.startswith('::')) or (ip_str.endswith(':') and not ip_str.endswith('::'))): return False # We can never have more than 7 ':' (1::2:3:4:5:6:7:8 is invalid) if ip_str.count(':') > 7: return False # If we have no concatenation, we need to have 8 fields with 7 ':'. if '::' not in ip_str and ip_str.count(':') != 7: # We might have an IPv4 mapped address. if ip_str.count('.') != 3: return False ip_str = _explode_shorthand_ip_string(ip_str) # Now that we have that all squared away, let's check that each of the # hextets are between 0x0 and 0xFFFF. for hextet in ip_str.split(':'): if hextet.count('.') == 3: # If we have an IPv4 mapped address, the IPv4 portion has to # be at the end of the IPv6 portion. if not ip_str.split(':')[-1] == hextet: return False try: validate_ipv4_address(hextet) except ValidationError: return False else: try: # a value error here means that we got a bad hextet, # something like 0xzzzz if int(hextet, 16) < 0x0 or int(hextet, 16) > 0xFFFF: return False except ValueError: return False return True def _explode_shorthand_ip_string(ip_str): """ Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address. """ if not _is_shorthand_ip(ip_str): # We've already got a longhand ip_str. return ip_str new_ip = [] hextet = ip_str.split('::') # If there is a ::, we need to expand it with zeroes # to get to 8 hextets - unless there is a dot in the last hextet, # meaning we're doing v4-mapping if '.' in ip_str.split(':')[-1]: fill_to = 7 else: fill_to = 8 if len(hextet) > 1: sep = len(hextet[0].split(':')) + len(hextet[1].split(':')) new_ip = hextet[0].split(':') for __ in range(fill_to - sep): new_ip.append('0000') new_ip += hextet[1].split(':') else: new_ip = ip_str.split(':') # Now need to make sure every hextet is 4 lower case characters. # If a hextet is < 4 characters, we've got missing leading 0's. ret_ip = [] for hextet in new_ip: ret_ip.append(('0' * (4 - len(hextet)) + hextet).lower()) return ':'.join(ret_ip) def _is_shorthand_ip(ip_str): """Determine if the address is shortened. Args: ip_str: A string, the IPv6 address. Returns: A boolean, True if the address is shortened. """ if ip_str.count('::') == 1: return True if any(len(x) < 4 for x in ip_str.split(':')): return True return False
cfe46024ecdcb84914d21ec95d1cdae00712afee678d1fbe0003535581e5e897
""" Providing iterator functions that are not in all version of Python we support. Where possible, we try to use the system-native version and only fall back to these implementations if necessary. """ def is_iterable(x): "A implementation independent way of checking for iterables" try: iter(x) except TypeError: return False else: return True
f945fc7fa6164620ba5e8dad45e6316e00baad3334a54ab910d99b4c5a648e24
from __future__ import unicode_literals import base64 import calendar import datetime import re import sys import unicodedata import warnings from binascii import Error as BinasciiError from email.utils import formatdate from django.core.exceptions import TooManyFieldsSent from django.utils import six from django.utils.datastructures import MultiValueDict from django.utils.deprecation import RemovedInDjango21Warning from django.utils.encoding import force_bytes, force_str, force_text from django.utils.functional import keep_lazy_text from django.utils.six.moves.urllib.parse import ( quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode, urlparse, ) # based on RFC 7232, Appendix C ETAG_MATCH = re.compile(r''' \A( # start of string and capture group (?:W/)? # optional weak indicator " # opening quote [^"]* # any sequence of non-quote characters " # end quote )\Z # end of string and capture group ''', re.X) MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split() __D = r'(?P<day>\d{2})' __D2 = r'(?P<day>[ \d]\d)' __M = r'(?P<mon>\w{3})' __Y = r'(?P<year>\d{4})' __Y2 = r'(?P<year>\d{2})' __T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})' RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T)) RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T)) ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y)) RFC3986_GENDELIMS = str(":/?#[]@") RFC3986_SUBDELIMS = str("!$&'()*+,;=") FIELDS_MATCH = re.compile('[&;]') @keep_lazy_text def urlquote(url, safe='/'): """ A version of Python's urllib.quote() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring. """ return force_text(quote(force_str(url), force_str(safe))) @keep_lazy_text def urlquote_plus(url, safe=''): """ A version of Python's urllib.quote_plus() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring. """ return force_text(quote_plus(force_str(url), force_str(safe))) @keep_lazy_text def urlunquote(quoted_url): """ A wrapper for Python's urllib.unquote() function that can operate on the result of django.utils.http.urlquote(). """ return force_text(unquote(force_str(quoted_url))) @keep_lazy_text def urlunquote_plus(quoted_url): """ A wrapper for Python's urllib.unquote_plus() function that can operate on the result of django.utils.http.urlquote_plus(). """ return force_text(unquote_plus(force_str(quoted_url))) def urlencode(query, doseq=0): """ A version of Python's urllib.urlencode() function that can operate on unicode strings. The parameters are first cast to UTF-8 encoded strings and then encoded as per normal. """ if isinstance(query, MultiValueDict): query = query.lists() elif hasattr(query, 'items'): query = query.items() return original_urlencode( [(force_str(k), [force_str(i) for i in v] if isinstance(v, (list, tuple)) else force_str(v)) for k, v in query], doseq) def cookie_date(epoch_seconds=None): """ Formats the time to ensure compatibility with Netscape's cookie standard. Accepts a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, defaults to the current time. Outputs a string in the format 'Wdy, DD-Mon-YYYY HH:MM:SS GMT'. """ rfcdate = formatdate(epoch_seconds) return '%s-%s-%s GMT' % (rfcdate[:7], rfcdate[8:11], rfcdate[12:25]) def http_date(epoch_seconds=None): """ Formats the time to match the RFC1123 date format as specified by HTTP RFC7231 section 7.1.1.1. Accepts a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, defaults to the current time. Outputs a string in the format 'Wdy, DD Mon YYYY HH:MM:SS GMT'. """ return formatdate(epoch_seconds, usegmt=True) def parse_http_date(date): """ Parses a date format as specified by HTTP RFC7231 section 7.1.1.1. The three formats allowed by the RFC are accepted, even if only the first one is still in widespread use. Returns an integer expressed in seconds since the epoch, in UTC. """ # emails.Util.parsedate does the job for RFC1123 dates; unfortunately # RFC7231 makes it mandatory to support RFC850 dates too. So we roll # our own RFC-compliant parsing. for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE: m = regex.match(date) if m is not None: break else: raise ValueError("%r is not in a valid HTTP date format" % date) try: year = int(m.group('year')) if year < 100: if year < 70: year += 2000 else: year += 1900 month = MONTHS.index(m.group('mon').lower()) + 1 day = int(m.group('day')) hour = int(m.group('hour')) min = int(m.group('min')) sec = int(m.group('sec')) result = datetime.datetime(year, month, day, hour, min, sec) return calendar.timegm(result.utctimetuple()) except Exception: six.reraise(ValueError, ValueError("%r is not a valid date" % date), sys.exc_info()[2]) def parse_http_date_safe(date): """ Same as parse_http_date, but returns None if the input is invalid. """ try: return parse_http_date(date) except Exception: pass # Base 36 functions: useful for generating compact URLs def base36_to_int(s): """ Converts a base 36 string to an ``int``. Raises ``ValueError` if the input won't fit into an int. """ # To prevent overconsumption of server resources, reject any # base36 string that is long than 13 base36 digits (13 digits # is sufficient to base36-encode any 64-bit integer) if len(s) > 13: raise ValueError("Base36 input too large") value = int(s, 36) # ... then do a final check that the value will fit into an int to avoid # returning a long (#15067). The long type was removed in Python 3. if six.PY2 and value > sys.maxint: raise ValueError("Base36 input too large") return value def int_to_base36(i): """ Converts an integer to a base36 string """ char_set = '0123456789abcdefghijklmnopqrstuvwxyz' if i < 0: raise ValueError("Negative base36 conversion input.") if six.PY2: if not isinstance(i, six.integer_types): raise TypeError("Non-integer base36 conversion input.") if i > sys.maxint: raise ValueError("Base36 conversion input too large.") if i < 36: return char_set[i] b36 = '' while i != 0: i, n = divmod(i, 36) b36 = char_set[n] + b36 return b36 def urlsafe_base64_encode(s): """ Encodes a bytestring in base64 for use in URLs, stripping any trailing equal signs. """ return base64.urlsafe_b64encode(s).rstrip(b'\n=') def urlsafe_base64_decode(s): """ Decodes a base64 encoded string, adding back any trailing equal signs that might have been stripped. """ s = force_bytes(s) try: return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b'=')) except (LookupError, BinasciiError) as e: raise ValueError(e) def parse_etags(etag_str): """ Parse a string of ETags given in an If-None-Match or If-Match header as defined by RFC 7232. Return a list of quoted ETags, or ['*'] if all ETags should be matched. """ if etag_str.strip() == '*': return ['*'] else: # Parse each ETag individually, and return any that are valid. etag_matches = (ETAG_MATCH.match(etag.strip()) for etag in etag_str.split(',')) return [match.group(1) for match in etag_matches if match] def quote_etag(etag_str): """ If the provided string is already a quoted ETag, return it. Otherwise, wrap the string in quotes, making it a strong ETag. """ if ETAG_MATCH.match(etag_str): return etag_str else: return '"%s"' % etag_str def is_same_domain(host, pattern): """ Return ``True`` if the host is either an exact match or a match to the wildcard pattern. Any pattern beginning with a period matches a domain and all of its subdomains. (e.g. ``.example.com`` matches ``example.com`` and ``foo.example.com``). Anything else is an exact string match. """ if not pattern: return False pattern = pattern.lower() return ( pattern[0] == '.' and (host.endswith(pattern) or host == pattern[1:]) or pattern == host ) def is_safe_url(url, host=None, allowed_hosts=None, require_https=False): """ Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host and uses a safe scheme). Always returns ``False`` on an empty url. If ``require_https`` is ``True``, only 'https' will be considered a valid scheme, as opposed to 'http' and 'https' with the default, ``False``. """ if url is not None: url = url.strip() if not url: return False if six.PY2: try: url = force_text(url) except UnicodeDecodeError: return False if allowed_hosts is None: allowed_hosts = set() if host: warnings.warn( "The host argument is deprecated, use allowed_hosts instead.", RemovedInDjango21Warning, stacklevel=2, ) # Avoid mutating the passed in allowed_hosts. allowed_hosts = allowed_hosts | {host} # Chrome treats \ completely as / in paths but it could be part of some # basic auth credentials so we need to check both URLs. return (_is_safe_url(url, allowed_hosts, require_https=require_https) and _is_safe_url(url.replace('\\', '/'), allowed_hosts, require_https=require_https)) def _is_safe_url(url, allowed_hosts, require_https=False): # Chrome considers any URL with more than two slashes to be absolute, but # urlparse is not so flexible. Treat any url with three slashes as unsafe. if url.startswith('///'): return False url_info = urlparse(url) # Forbid URLs like http:///example.com - with a scheme, but without a hostname. # In that URL, example.com is not the hostname but, a path component. However, # Chrome will still consider example.com to be the hostname, so we must not # allow this syntax. if not url_info.netloc and url_info.scheme: return False # Forbid URLs that start with control characters. Some browsers (like # Chrome) ignore quite a few control characters at the start of a # URL and might consider the URL as scheme relative. if unicodedata.category(url[0])[0] == 'C': return False scheme = url_info.scheme # Consider URLs without a scheme (e.g. //example.com/p) to be http. if not url_info.scheme and url_info.netloc: scheme = 'http' valid_schemes = ['https'] if require_https else ['http', 'https'] return ((not url_info.netloc or url_info.netloc in allowed_hosts) and (not scheme or scheme in valid_schemes)) def limited_parse_qsl(qs, keep_blank_values=False, encoding='utf-8', errors='replace', fields_limit=None): """ Return a list of key/value tuples parsed from query string. Copied from urlparse with an additional "fields_limit" argument. Copyright (C) 2013 Python Software Foundation (see LICENSE.python). Arguments: qs: percent-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. encoding and errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. fields_limit: maximum number of fields parsed or an exception is raised. None means no limit and is the default. """ if fields_limit: pairs = FIELDS_MATCH.split(qs, fields_limit) if len(pairs) > fields_limit: raise TooManyFieldsSent( 'The number of GET/POST parameters exceeded ' 'settings.DATA_UPLOAD_MAX_NUMBER_FIELDS.' ) else: pairs = FIELDS_MATCH.split(qs) r = [] for name_value in pairs: if not name_value: continue nv = name_value.split(str('='), 1) if len(nv) != 2: # Handle case of a control-name with no equal sign if keep_blank_values: nv.append('') else: continue if len(nv[1]) or keep_blank_values: if six.PY3: name = nv[0].replace('+', ' ') name = unquote(name, encoding=encoding, errors=errors) value = nv[1].replace('+', ' ') value = unquote(value, encoding=encoding, errors=errors) else: name = unquote(nv[0].replace(b'+', b' ')) value = unquote(nv[1].replace(b'+', b' ')) r.append((name, value)) return r
0b13cd503734fda4a1d96ba172b8cd1ee3fb125350fd90ca5bc06afc0f91ecb6
""" This module contains helper functions for controlling caching. It does so by managing the "Vary" header of responses. It includes functions to patch the header of response objects directly and decorators that change functions to do that header-patching themselves. For information on the Vary header, see: https://tools.ietf.org/html/rfc7231#section-7.1.4 Essentially, the "Vary" HTTP header defines which headers a cache should take into account when building its cache key. Requests with the same path but different header content for headers named in "Vary" need to get different cache keys to prevent delivery of wrong content. An example: i18n middleware would need to distinguish caches by the "Accept-language" header. """ from __future__ import unicode_literals import hashlib import logging import re import time import warnings from django.conf import settings from django.core.cache import caches from django.http import HttpResponse, HttpResponseNotModified from django.utils.deprecation import RemovedInDjango21Warning from django.utils.encoding import force_bytes, force_text, iri_to_uri from django.utils.http import ( http_date, parse_etags, parse_http_date_safe, quote_etag, ) from django.utils.timezone import get_current_timezone_name from django.utils.translation import get_language cc_delim_re = re.compile(r'\s*,\s*') logger = logging.getLogger('django.request') def patch_cache_control(response, **kwargs): """ This function patches the Cache-Control header by adding all keyword arguments to it. The transformation is as follows: * All keyword parameter names are turned to lowercase, and underscores are converted to hyphens. * If the value of a parameter is True (exactly True, not just a true value), only the parameter name is added to the header. * All other parameters are added with their value, after applying str() to it. """ def dictitem(s): t = s.split('=', 1) if len(t) > 1: return (t[0].lower(), t[1]) else: return (t[0].lower(), True) def dictvalue(t): if t[1] is True: return t[0] else: return '%s=%s' % (t[0], t[1]) if response.get('Cache-Control'): cc = cc_delim_re.split(response['Cache-Control']) cc = dict(dictitem(el) for el in cc) else: cc = {} # If there's already a max-age header but we're being asked to set a new # max-age, use the minimum of the two ages. In practice this happens when # a decorator and a piece of middleware both operate on a given view. if 'max-age' in cc and 'max_age' in kwargs: kwargs['max_age'] = min(int(cc['max-age']), kwargs['max_age']) # Allow overriding private caching and vice versa if 'private' in cc and 'public' in kwargs: del cc['private'] elif 'public' in cc and 'private' in kwargs: del cc['public'] for (k, v) in kwargs.items(): cc[k.replace('_', '-')] = v cc = ', '.join(dictvalue(el) for el in cc.items()) response['Cache-Control'] = cc def get_max_age(response): """ Returns the max-age from the response Cache-Control header as an integer (or ``None`` if it wasn't found or wasn't an integer. """ if not response.has_header('Cache-Control'): return cc = dict(_to_tuple(el) for el in cc_delim_re.split(response['Cache-Control'])) if 'max-age' in cc: try: return int(cc['max-age']) except (ValueError, TypeError): pass def set_response_etag(response): if not response.streaming: response['ETag'] = quote_etag(hashlib.md5(response.content).hexdigest()) return response def _precondition_failed(request): logger.warning( 'Precondition Failed: %s', request.path, extra={ 'status_code': 412, 'request': request, }, ) return HttpResponse(status=412) def _not_modified(request, response=None): new_response = HttpResponseNotModified() if response: # Preserve the headers required by Section 4.1 of RFC 7232, as well as # Last-Modified. for header in ('Cache-Control', 'Content-Location', 'Date', 'ETag', 'Expires', 'Last-Modified', 'Vary'): if header in response: new_response[header] = response[header] # Preserve cookies as per the cookie specification: "If a proxy server # receives a response which contains a Set-cookie header, it should # propagate the Set-cookie header to the client, regardless of whether # the response was 304 (Not Modified) or 200 (OK). # https://curl.haxx.se/rfc/cookie_spec.html new_response.cookies = response.cookies return new_response def get_conditional_response(request, etag=None, last_modified=None, response=None): # Only return conditional responses on successful requests. if response and not (200 <= response.status_code < 300): return response # Get HTTP request headers. if_match_etags = parse_etags(request.META.get('HTTP_IF_MATCH', '')) if_unmodified_since = request.META.get('HTTP_IF_UNMODIFIED_SINCE') if if_unmodified_since: if_unmodified_since = parse_http_date_safe(if_unmodified_since) if_none_match_etags = parse_etags(request.META.get('HTTP_IF_NONE_MATCH', '')) if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE') if if_modified_since: if_modified_since = parse_http_date_safe(if_modified_since) # Step 1 of section 6 of RFC 7232: Test the If-Match precondition. if (if_match_etags and not _if_match_passes(etag, if_match_etags)): return _precondition_failed(request) # Step 2: Test the If-Unmodified-Since precondition. if (not if_match_etags and if_unmodified_since and not _if_unmodified_since_passes(last_modified, if_unmodified_since)): return _precondition_failed(request) # Step 3: Test the If-None-Match precondition. if (if_none_match_etags and not _if_none_match_passes(etag, if_none_match_etags)): if request.method in ('GET', 'HEAD'): return _not_modified(request, response) else: return _precondition_failed(request) # Step 4: Test the If-Modified-Since precondition. if (not if_none_match_etags and if_modified_since and not _if_modified_since_passes(last_modified, if_modified_since)): if request.method in ('GET', 'HEAD'): return _not_modified(request, response) # Step 5: Test the If-Range precondition (not supported). # Step 6: Return original response since there isn't a conditional response. return response def _if_match_passes(target_etag, etags): """ Test the If-Match comparison as defined in section 3.1 of RFC 7232. """ if not target_etag: # If there isn't an ETag, then there can't be a match. return False elif etags == ['*']: # The existence of an ETag means that there is "a current # representation for the target resource", even if the ETag is weak, # so there is a match to '*'. return True elif target_etag.startswith('W/'): # A weak ETag can never strongly match another ETag. return False else: # Since the ETag is strong, this will only return True if there's a # strong match. return target_etag in etags def _if_unmodified_since_passes(last_modified, if_unmodified_since): """ Test the If-Unmodified-Since comparison as defined in section 3.4 of RFC 7232. """ return last_modified and last_modified <= if_unmodified_since def _if_none_match_passes(target_etag, etags): """ Test the If-None-Match comparison as defined in section 3.2 of RFC 7232. """ if not target_etag: # If there isn't an ETag, then there isn't a match. return True elif etags == ['*']: # The existence of an ETag means that there is "a current # representation for the target resource", so there is a match to '*'. return False else: # The comparison should be weak, so look for a match after stripping # off any weak indicators. target_etag = target_etag.strip('W/') etags = (etag.strip('W/') for etag in etags) return target_etag not in etags def _if_modified_since_passes(last_modified, if_modified_since): """ Test the If-Modified-Since comparison as defined in section 3.3 of RFC 7232. """ return not last_modified or last_modified > if_modified_since def patch_response_headers(response, cache_timeout=None): """ Add HTTP caching headers to the given HttpResponse: Expires and Cache-Control. Each header is only added if it isn't already set. cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used by default. """ if cache_timeout is None: cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS if cache_timeout < 0: cache_timeout = 0 # Can't have max-age negative if settings.USE_ETAGS and not response.has_header('ETag'): warnings.warn( "The USE_ETAGS setting is deprecated in favor of " "ConditionalGetMiddleware which sets the ETag regardless of the " "setting. patch_response_headers() won't do ETag processing in " "Django 2.1.", RemovedInDjango21Warning ) if hasattr(response, 'render') and callable(response.render): response.add_post_render_callback(set_response_etag) else: response = set_response_etag(response) if not response.has_header('Expires'): response['Expires'] = http_date(time.time() + cache_timeout) patch_cache_control(response, max_age=cache_timeout) def add_never_cache_headers(response): """ Adds headers to a response to indicate that a page should never be cached. """ patch_response_headers(response, cache_timeout=-1) patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True) def patch_vary_headers(response, newheaders): """ Adds (or updates) the "Vary" header in the given HttpResponse object. newheaders is a list of header names that should be in "Vary". Existing headers in "Vary" aren't removed. """ # Note that we need to keep the original order intact, because cache # implementations may rely on the order of the Vary contents in, say, # computing an MD5 hash. if response.has_header('Vary'): vary_headers = cc_delim_re.split(response['Vary']) else: vary_headers = [] # Use .lower() here so we treat headers as case-insensitive. existing_headers = set(header.lower() for header in vary_headers) additional_headers = [newheader for newheader in newheaders if newheader.lower() not in existing_headers] response['Vary'] = ', '.join(vary_headers + additional_headers) def has_vary_header(response, header_query): """ Checks to see if the response has a given header name in its Vary header. """ if not response.has_header('Vary'): return False vary_headers = cc_delim_re.split(response['Vary']) existing_headers = set(header.lower() for header in vary_headers) return header_query.lower() in existing_headers def _i18n_cache_key_suffix(request, cache_key): """If necessary, adds the current locale or time zone to the cache key.""" if settings.USE_I18N or settings.USE_L10N: # first check if LocaleMiddleware or another middleware added # LANGUAGE_CODE to request, then fall back to the active language # which in turn can also fall back to settings.LANGUAGE_CODE cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language()) if settings.USE_TZ: # The datetime module doesn't restrict the output of tzname(). # Windows is known to use non-standard, locale-dependent names. # User-defined tzinfo classes may return absolutely anything. # Hence this paranoid conversion to create a valid cache key. tz_name = force_text(get_current_timezone_name(), errors='ignore') cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_') return cache_key def _generate_cache_key(request, method, headerlist, key_prefix): """Returns a cache key from the headers given in the header list.""" ctx = hashlib.md5() for header in headerlist: value = request.META.get(header) if value is not None: ctx.update(force_bytes(value)) url = hashlib.md5(force_bytes(iri_to_uri(request.build_absolute_uri()))) cache_key = 'views.decorators.cache.cache_page.%s.%s.%s.%s' % ( key_prefix, method, url.hexdigest(), ctx.hexdigest()) return _i18n_cache_key_suffix(request, cache_key) def _generate_cache_header_key(key_prefix, request): """Returns a cache key for the header cache.""" url = hashlib.md5(force_bytes(iri_to_uri(request.build_absolute_uri()))) cache_key = 'views.decorators.cache.cache_header.%s.%s' % ( key_prefix, url.hexdigest()) return _i18n_cache_key_suffix(request, cache_key) def get_cache_key(request, key_prefix=None, method='GET', cache=None): """ Returns a cache key based on the request URL and query. It can be used in the request phase because it pulls the list of headers to take into account from the global URL registry and uses those to build a cache key to check against. If there is no headerlist stored, the page needs to be rebuilt, so this function returns None. """ if key_prefix is None: key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX cache_key = _generate_cache_header_key(key_prefix, request) if cache is None: cache = caches[settings.CACHE_MIDDLEWARE_ALIAS] headerlist = cache.get(cache_key) if headerlist is not None: return _generate_cache_key(request, method, headerlist, key_prefix) else: return None def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None): """ Learns what headers to take into account for some request URL from the response object. It stores those headers in a global URL registry so that later access to that URL will know what headers to take into account without building the response object itself. The headers are named in the Vary header of the response, but we want to prevent response generation. The list of headers to use for cache key generation is stored in the same cache as the pages themselves. If the cache ages some data out of the cache, this just means that we have to build the response once to get at the Vary header and so at the list of headers to use for the cache key. """ if key_prefix is None: key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX if cache_timeout is None: cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS cache_key = _generate_cache_header_key(key_prefix, request) if cache is None: cache = caches[settings.CACHE_MIDDLEWARE_ALIAS] if response.has_header('Vary'): is_accept_language_redundant = settings.USE_I18N or settings.USE_L10N # If i18n or l10n are used, the generated cache key will be suffixed # with the current locale. Adding the raw value of Accept-Language is # redundant in that case and would result in storing the same content # under multiple keys in the cache. See #18191 for details. headerlist = [] for header in cc_delim_re.split(response['Vary']): header = header.upper().replace('-', '_') if header == 'ACCEPT_LANGUAGE' and is_accept_language_redundant: continue headerlist.append('HTTP_' + header) headerlist.sort() cache.set(cache_key, headerlist, cache_timeout) return _generate_cache_key(request, request.method, headerlist, key_prefix) else: # if there is no Vary header, we still need a cache key # for the request.build_absolute_uri() cache.set(cache_key, [], cache_timeout) return _generate_cache_key(request, request.method, [], key_prefix) def _to_tuple(s): t = s.split('=', 1) if len(t) == 2: return t[0].lower(), t[1] return t[0].lower(), True
dff7863658807a181b86e5485c06685d61063e72157a8b2fe9e44e8fee688b45
import datetime import decimal import unicodedata from importlib import import_module from django.conf import settings from django.utils import dateformat, datetime_safe, numberformat, six from django.utils.encoding import force_str from django.utils.functional import lazy from django.utils.safestring import mark_safe from django.utils.translation import ( check_for_language, get_language, to_locale, ) # format_cache is a mapping from (format_type, lang) to the format string. # By using the cache, it is possible to avoid running get_format_modules # repeatedly. _format_cache = {} _format_modules_cache = {} ISO_INPUT_FORMATS = { 'DATE_INPUT_FORMATS': ['%Y-%m-%d'], 'TIME_INPUT_FORMATS': ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M'], 'DATETIME_INPUT_FORMATS': [ '%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M', '%Y-%m-%d' ], } FORMAT_SETTINGS = frozenset([ 'DECIMAL_SEPARATOR', 'THOUSAND_SEPARATOR', 'NUMBER_GROUPING', 'FIRST_DAY_OF_WEEK', 'MONTH_DAY_FORMAT', 'TIME_FORMAT', 'DATE_FORMAT', 'DATETIME_FORMAT', 'SHORT_DATE_FORMAT', 'SHORT_DATETIME_FORMAT', 'YEAR_MONTH_FORMAT', 'DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS', 'DATETIME_INPUT_FORMATS', ]) def reset_format_cache(): """Clear any cached formats. This method is provided primarily for testing purposes, so that the effects of cached formats can be removed. """ global _format_cache, _format_modules_cache _format_cache = {} _format_modules_cache = {} def iter_format_modules(lang, format_module_path=None): """ Does the heavy lifting of finding format modules. """ if not check_for_language(lang): return if format_module_path is None: format_module_path = settings.FORMAT_MODULE_PATH format_locations = [] if format_module_path: if isinstance(format_module_path, six.string_types): format_module_path = [format_module_path] for path in format_module_path: format_locations.append(path + '.%s') format_locations.append('django.conf.locale.%s') locale = to_locale(lang) locales = [locale] if '_' in locale: locales.append(locale.split('_')[0]) for location in format_locations: for loc in locales: try: yield import_module('%s.formats' % (location % loc)) except ImportError: pass def get_format_modules(lang=None, reverse=False): """ Returns a list of the format modules found """ if lang is None: lang = get_language() if lang not in _format_modules_cache: _format_modules_cache[lang] = list(iter_format_modules(lang, settings.FORMAT_MODULE_PATH)) modules = _format_modules_cache[lang] if reverse: return list(reversed(modules)) return modules def get_format(format_type, lang=None, use_l10n=None): """ For a specific format type, returns the format for the current language (locale), defaults to the format in the settings. format_type is the name of the format, e.g. 'DATE_FORMAT' If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ format_type = force_str(format_type) if use_l10n or (use_l10n is None and settings.USE_L10N): if lang is None: lang = get_language() cache_key = (format_type, lang) try: cached = _format_cache[cache_key] if cached is not None: return cached except KeyError: for module in get_format_modules(lang): try: val = getattr(module, format_type) for iso_input in ISO_INPUT_FORMATS.get(format_type, ()): if iso_input not in val: if isinstance(val, tuple): val = list(val) val.append(iso_input) _format_cache[cache_key] = val return val except AttributeError: pass _format_cache[cache_key] = None if format_type not in FORMAT_SETTINGS: return format_type # Return the general setting by default return getattr(settings, format_type) get_format_lazy = lazy(get_format, six.text_type, list, tuple) def date_format(value, format=None, use_l10n=None): """ Formats a datetime.date or datetime.datetime object using a localizable format If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ return dateformat.format(value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n)) def time_format(value, format=None, use_l10n=None): """ Formats a datetime.time object using a localizable format If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ return dateformat.time_format(value, get_format(format or 'TIME_FORMAT', use_l10n=use_l10n)) def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False): """ Formats a numeric value using localization settings If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ if use_l10n or (use_l10n is None and settings.USE_L10N): lang = get_language() else: lang = None return numberformat.format( value, get_format('DECIMAL_SEPARATOR', lang, use_l10n=use_l10n), decimal_pos, get_format('NUMBER_GROUPING', lang, use_l10n=use_l10n), get_format('THOUSAND_SEPARATOR', lang, use_l10n=use_l10n), force_grouping=force_grouping ) def localize(value, use_l10n=None): """ Checks if value is a localizable type (date, number...) and returns it formatted as a string using current locale format. If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ if isinstance(value, six.string_types): # Handle strings first for performance reasons. return value elif isinstance(value, bool): # Make sure booleans don't get treated as numbers return mark_safe(six.text_type(value)) elif isinstance(value, (decimal.Decimal, float) + six.integer_types): return number_format(value, use_l10n=use_l10n) elif isinstance(value, datetime.datetime): return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n) elif isinstance(value, datetime.date): return date_format(value, use_l10n=use_l10n) elif isinstance(value, datetime.time): return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n) return value def localize_input(value, default=None): """ Checks if an input value is a localizable type and returns it formatted with the appropriate formatting string of the current locale. """ if isinstance(value, six.string_types): # Handle strings first for performance reasons. return value elif isinstance(value, bool): # Don't treat booleans as numbers. return six.text_type(value) elif isinstance(value, (decimal.Decimal, float) + six.integer_types): return number_format(value) elif isinstance(value, datetime.datetime): value = datetime_safe.new_datetime(value) format = force_str(default or get_format('DATETIME_INPUT_FORMATS')[0]) return value.strftime(format) elif isinstance(value, datetime.date): value = datetime_safe.new_date(value) format = force_str(default or get_format('DATE_INPUT_FORMATS')[0]) return value.strftime(format) elif isinstance(value, datetime.time): format = force_str(default or get_format('TIME_INPUT_FORMATS')[0]) return value.strftime(format) return value def sanitize_separators(value): """ Sanitizes a value according to the current decimal and thousand separator setting. Used with form field input. """ if settings.USE_L10N and isinstance(value, six.string_types): parts = [] decimal_separator = get_format('DECIMAL_SEPARATOR') if decimal_separator in value: value, decimals = value.split(decimal_separator, 1) parts.append(decimals) if settings.USE_THOUSAND_SEPARATOR: thousand_sep = get_format('THOUSAND_SEPARATOR') if thousand_sep == '.' and value.count('.') == 1 and len(value.split('.')[-1]) != 3: # Special case where we suspect a dot meant decimal separator (see #22171) pass else: for replacement in { thousand_sep, unicodedata.normalize('NFKD', thousand_sep)}: value = value.replace(replacement, '') parts.append(value) value = '.'.join(reversed(parts)) return value
f45354ecd291f280f4a663755c5a823467414cf7be4b8ad4fb555be96819f0f8
"""JsLex: a lexer for Javascript""" # Originally from https://bitbucket.org/ned/jslex from __future__ import unicode_literals import re class Tok(object): """ A specification for a token class. """ num = 0 def __init__(self, name, regex, next=None): self.id = Tok.num Tok.num += 1 self.name = name self.regex = regex self.next = next def literals(choices, prefix="", suffix=""): """ Create a regex from a space-separated list of literal `choices`. If provided, `prefix` and `suffix` will be attached to each choice individually. """ return "|".join(prefix + re.escape(c) + suffix for c in choices.split()) class Lexer(object): """ A generic multi-state regex-based lexer. """ def __init__(self, states, first): self.regexes = {} self.toks = {} for state, rules in states.items(): parts = [] for tok in rules: groupid = "t%d" % tok.id self.toks[groupid] = tok parts.append("(?P<%s>%s)" % (groupid, tok.regex)) self.regexes[state] = re.compile("|".join(parts), re.MULTILINE | re.VERBOSE) self.state = first def lex(self, text): """ Lexically analyze `text`. Yields pairs (`name`, `tokentext`). """ end = len(text) state = self.state regexes = self.regexes toks = self.toks start = 0 while start < end: for match in regexes[state].finditer(text, start): name = match.lastgroup tok = toks[name] toktext = match.group(name) start += len(toktext) yield (tok.name, toktext) if tok.next: state = tok.next break self.state = state class JsLexer(Lexer): """ A Javascript lexer >>> lexer = JsLexer() >>> list(lexer.lex("a = 1")) [('id', 'a'), ('ws', ' '), ('punct', '='), ('ws', ' '), ('dnum', '1')] This doesn't properly handle non-ASCII characters in the Javascript source. """ # Because these tokens are matched as alternatives in a regex, longer # possibilities must appear in the list before shorter ones, for example, # '>>' before '>'. # # Note that we don't have to detect malformed Javascript, only properly # lex correct Javascript, so much of this is simplified. # Details of Javascript lexical structure are taken from # http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf # A useful explanation of automatic semicolon insertion is at # http://inimino.org/~inimino/blog/javascript_semicolons both_before = [ Tok("comment", r"/\*(.|\n)*?\*/"), Tok("linecomment", r"//.*?$"), Tok("ws", r"\s+"), Tok("keyword", literals(""" break case catch class const continue debugger default delete do else enum export extends finally for function if import in instanceof new return super switch this throw try typeof var void while with """, suffix=r"\b"), next='reg'), Tok("reserved", literals("null true false", suffix=r"\b"), next='div'), Tok("id", r""" ([a-zA-Z_$ ]|\\u[0-9a-fA-Z]{4}) # first char ([a-zA-Z_$0-9]|\\u[0-9a-fA-F]{4})* # rest chars """, next='div'), Tok("hnum", r"0[xX][0-9a-fA-F]+", next='div'), Tok("onum", r"0[0-7]+"), Tok("dnum", r""" ( (0|[1-9][0-9]*) # DecimalIntegerLiteral \. # dot [0-9]* # DecimalDigits-opt ([eE][-+]?[0-9]+)? # ExponentPart-opt | \. # dot [0-9]+ # DecimalDigits ([eE][-+]?[0-9]+)? # ExponentPart-opt | (0|[1-9][0-9]*) # DecimalIntegerLiteral ([eE][-+]?[0-9]+)? # ExponentPart-opt ) """, next='div'), Tok("punct", literals(""" >>>= === !== >>> <<= >>= <= >= == != << >> && || += -= *= %= &= |= ^= """), next="reg"), Tok("punct", literals("++ -- ) ]"), next='div'), Tok("punct", literals("{ } ( [ . ; , < > + - * % & | ^ ! ~ ? : ="), next='reg'), Tok("string", r'"([^"\\]|(\\(.|\n)))*?"', next='div'), Tok("string", r"'([^'\\]|(\\(.|\n)))*?'", next='div'), ] both_after = [ Tok("other", r"."), ] states = { # slash will mean division 'div': both_before + [ Tok("punct", literals("/= /"), next='reg'), ] + both_after, # slash will mean regex 'reg': both_before + [ Tok("regex", r""" / # opening slash # First character is.. ( [^*\\/[] # anything but * \ / or [ | \\. # or an escape sequence | \[ # or a class, which has ( [^\]\\] # anything but \ or ] | \\. # or an escape sequence )* # many times \] ) # Following characters are same, except for excluding a star ( [^\\/[] # anything but \ / or [ | \\. # or an escape sequence | \[ # or a class, which has ( [^\]\\] # anything but \ or ] | \\. # or an escape sequence )* # many times \] )* # many times / # closing slash [a-zA-Z0-9]* # trailing flags """, next='div'), ] + both_after, } def __init__(self): super(JsLexer, self).__init__(self.states, 'reg') def prepare_js_for_gettext(js): """ Convert the Javascript source `js` into something resembling C for xgettext. What actually happens is that all the regex literals are replaced with "REGEX". """ def escape_quotes(m): """Used in a regex to properly escape double quotes.""" s = m.group(0) if s == '"': return r'\"' else: return s lexer = JsLexer() c = [] for name, tok in lexer.lex(js): if name == 'regex': # C doesn't grok regexes, and they aren't needed for gettext, # so just output a string instead. tok = '"REGEX"' elif name == 'string': # C doesn't have single-quoted strings, so make all strings # double-quoted. if tok.startswith("'"): guts = re.sub(r"\\.|.", escape_quotes, tok[1:-1]) tok = '"' + guts + '"' elif name == 'id': # C can't deal with Unicode escapes in identifiers. We don't # need them for gettext anyway, so replace them with something # innocuous tok = tok.replace("\\", "U") c.append(tok) return ''.join(c)
aa99d6514e055a997d3750d6e6f4d66fb0107787d4a97ab2b835c15f7655777f
from __future__ import unicode_literals import os import sys import tempfile from os.path import abspath, dirname, isabs, join, normcase, normpath, sep from django.core.exceptions import SuspiciousFileOperation from django.utils import six from django.utils.encoding import force_text if six.PY2: fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() # Under Python 2, define our own abspath function that can handle joining # unicode paths to a current working directory that has non-ASCII characters # in it. This isn't necessary on Windows since the Windows version of abspath # handles this correctly. It also handles drive letters differently than the # pure Python implementation, so it's best not to replace it. if six.PY3 or os.name == 'nt': abspathu = abspath else: def abspathu(path): """ Version of os.path.abspath that uses the unicode representation of the current working directory, thus avoiding a UnicodeDecodeError in join when the cwd has non-ASCII characters. """ if not isabs(path): path = join(os.getcwdu(), path) return normpath(path) def upath(path): """ Always return a unicode path. """ if six.PY2 and not isinstance(path, six.text_type): return path.decode(fs_encoding) return path def npath(path): """ Always return a native path, that is unicode on Python 3 and bytestring on Python 2. """ if six.PY2 and not isinstance(path, bytes): return path.encode(fs_encoding) return path def safe_join(base, *paths): """ Joins one or more path components to the base path component intelligently. Returns a normalized, absolute version of the final path. The final path must be located inside of the base path component (otherwise a ValueError is raised). """ base = force_text(base) paths = [force_text(p) for p in paths] final_path = abspathu(join(base, *paths)) base_path = abspathu(base) # Ensure final_path starts with base_path (using normcase to ensure we # don't false-negative on case insensitive operating systems like Windows), # further, one of the following conditions must be true: # a) The next character is the path separator (to prevent conditions like # safe_join("/dir", "/../d")) # b) The final path must be the same as the base path. # c) The base path must be the most root path (meaning either "/" or "C:\\") if (not normcase(final_path).startswith(normcase(base_path + sep)) and normcase(final_path) != normcase(base_path) and dirname(normcase(base_path)) != normcase(base_path)): raise SuspiciousFileOperation( 'The joined path ({}) is located outside of the base path ' 'component ({})'.format(final_path, base_path)) return final_path def symlinks_supported(): """ A function to check if creating symlinks are supported in the host platform and/or if they are allowed to be created (e.g. on Windows it requires admin permissions). """ tmpdir = tempfile.mkdtemp() original_path = os.path.join(tmpdir, 'original') symlink_path = os.path.join(tmpdir, 'symlink') os.makedirs(original_path) try: os.symlink(original_path, symlink_path) supported = True except (OSError, NotImplementedError, AttributeError): supported = False else: os.remove(symlink_path) finally: os.rmdir(original_path) os.rmdir(tmpdir) return supported
25041afd78be0d16bd00a3c95256ebd39da2d272708c83f13c7a0415261c8d65
""" termcolors.py """ from django.utils import six color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white') foreground = {color_names[x]: '3%s' % x for x in range(8)} background = {color_names[x]: '4%s' % x for x in range(8)} RESET = '0' opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'} def colorize(text='', opts=(), **kwargs): """ Returns your text, enclosed in ANSI graphics codes. Depends on the keyword arguments 'fg' and 'bg', and the contents of the opts tuple/list. Returns the RESET code if no parameters are given. Valid colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' Valid options: 'bold' 'underscore' 'blink' 'reverse' 'conceal' 'noreset' - string will not be auto-terminated with the RESET code Examples: colorize('hello', fg='red', bg='blue', opts=('blink',)) colorize() colorize('goodbye', opts=('underscore',)) print(colorize('first line', fg='red', opts=('noreset',))) print('this should be red too') print(colorize('and so should this')) print('this should not be red') """ code_list = [] if text == '' and len(opts) == 1 and opts[0] == 'reset': return '\x1b[%sm' % RESET for k, v in six.iteritems(kwargs): if k == 'fg': code_list.append(foreground[v]) elif k == 'bg': code_list.append(background[v]) for o in opts: if o in opt_dict: code_list.append(opt_dict[o]) if 'noreset' not in opts: text = '%s\x1b[%sm' % (text or '', RESET) return '%s%s' % (('\x1b[%sm' % ';'.join(code_list)), text or '') def make_style(opts=(), **kwargs): """ Returns a function with default parameters for colorize() Example: bold_red = make_style(opts=('bold',), fg='red') print(bold_red('hello')) KEYWORD = make_style(fg='yellow') COMMENT = make_style(fg='blue', opts=('bold',)) """ return lambda text: colorize(text, opts, **kwargs) NOCOLOR_PALETTE = 'nocolor' DARK_PALETTE = 'dark' LIGHT_PALETTE = 'light' PALETTES = { NOCOLOR_PALETTE: { 'ERROR': {}, 'SUCCESS': {}, 'WARNING': {}, 'NOTICE': {}, 'SQL_FIELD': {}, 'SQL_COLTYPE': {}, 'SQL_KEYWORD': {}, 'SQL_TABLE': {}, 'HTTP_INFO': {}, 'HTTP_SUCCESS': {}, 'HTTP_REDIRECT': {}, 'HTTP_NOT_MODIFIED': {}, 'HTTP_BAD_REQUEST': {}, 'HTTP_NOT_FOUND': {}, 'HTTP_SERVER_ERROR': {}, 'MIGRATE_HEADING': {}, 'MIGRATE_LABEL': {}, }, DARK_PALETTE: { 'ERROR': {'fg': 'red', 'opts': ('bold',)}, 'SUCCESS': {'fg': 'green', 'opts': ('bold',)}, 'WARNING': {'fg': 'yellow', 'opts': ('bold',)}, 'NOTICE': {'fg': 'red'}, 'SQL_FIELD': {'fg': 'green', 'opts': ('bold',)}, 'SQL_COLTYPE': {'fg': 'green'}, 'SQL_KEYWORD': {'fg': 'yellow'}, 'SQL_TABLE': {'opts': ('bold',)}, 'HTTP_INFO': {'opts': ('bold',)}, 'HTTP_SUCCESS': {}, 'HTTP_REDIRECT': {'fg': 'green'}, 'HTTP_NOT_MODIFIED': {'fg': 'cyan'}, 'HTTP_BAD_REQUEST': {'fg': 'red', 'opts': ('bold',)}, 'HTTP_NOT_FOUND': {'fg': 'yellow'}, 'HTTP_SERVER_ERROR': {'fg': 'magenta', 'opts': ('bold',)}, 'MIGRATE_HEADING': {'fg': 'cyan', 'opts': ('bold',)}, 'MIGRATE_LABEL': {'opts': ('bold',)}, }, LIGHT_PALETTE: { 'ERROR': {'fg': 'red', 'opts': ('bold',)}, 'SUCCESS': {'fg': 'green', 'opts': ('bold',)}, 'WARNING': {'fg': 'yellow', 'opts': ('bold',)}, 'NOTICE': {'fg': 'red'}, 'SQL_FIELD': {'fg': 'green', 'opts': ('bold',)}, 'SQL_COLTYPE': {'fg': 'green'}, 'SQL_KEYWORD': {'fg': 'blue'}, 'SQL_TABLE': {'opts': ('bold',)}, 'HTTP_INFO': {'opts': ('bold',)}, 'HTTP_SUCCESS': {}, 'HTTP_REDIRECT': {'fg': 'green', 'opts': ('bold',)}, 'HTTP_NOT_MODIFIED': {'fg': 'green'}, 'HTTP_BAD_REQUEST': {'fg': 'red', 'opts': ('bold',)}, 'HTTP_NOT_FOUND': {'fg': 'red'}, 'HTTP_SERVER_ERROR': {'fg': 'magenta', 'opts': ('bold',)}, 'MIGRATE_HEADING': {'fg': 'cyan', 'opts': ('bold',)}, 'MIGRATE_LABEL': {'opts': ('bold',)}, } } DEFAULT_PALETTE = DARK_PALETTE def parse_color_setting(config_string): """Parse a DJANGO_COLORS environment variable to produce the system palette The general form of a palette definition is: "palette;role=fg;role=fg/bg;role=fg,option,option;role=fg/bg,option,option" where: palette is a named palette; one of 'light', 'dark', or 'nocolor'. role is a named style used by Django fg is a background color. bg is a background color. option is a display options. Specifying a named palette is the same as manually specifying the individual definitions for each role. Any individual definitions following the palette definition will augment the base palette definition. Valid roles: 'error', 'success', 'warning', 'notice', 'sql_field', 'sql_coltype', 'sql_keyword', 'sql_table', 'http_info', 'http_success', 'http_redirect', 'http_not_modified', 'http_bad_request', 'http_not_found', 'http_server_error', 'migrate_heading', 'migrate_label' Valid colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' Valid options: 'bold', 'underscore', 'blink', 'reverse', 'conceal', 'noreset' """ if not config_string: return PALETTES[DEFAULT_PALETTE] # Split the color configuration into parts parts = config_string.lower().split(';') palette = PALETTES[NOCOLOR_PALETTE].copy() for part in parts: if part in PALETTES: # A default palette has been specified palette.update(PALETTES[part]) elif '=' in part: # Process a palette defining string definition = {} # Break the definition into the role, # plus the list of specific instructions. # The role must be in upper case role, instructions = part.split('=') role = role.upper() styles = instructions.split(',') styles.reverse() # The first instruction can contain a slash # to break apart fg/bg. colors = styles.pop().split('/') colors.reverse() fg = colors.pop() if fg in color_names: definition['fg'] = fg if colors and colors[-1] in color_names: definition['bg'] = colors[-1] # All remaining instructions are options opts = tuple(s for s in styles if s in opt_dict.keys()) if opts: definition['opts'] = opts # The nocolor palette has all available roles. # Use that palette as the basis for determining # if the role is valid. if role in PALETTES[NOCOLOR_PALETTE] and definition: palette[role] = definition # If there are no colors specified, return the empty palette. if palette == PALETTES[NOCOLOR_PALETTE]: return None return palette
4a79979add8dc2126116ebdbaf8c4e2be5c193eba0e9ccc4bd4146af2c69fb49
""" Django's support for templates. The django.template namespace contains two independent subsystems: 1. Multiple Template Engines: support for pluggable template backends, built-in backends and backend-independent APIs 2. Django Template Language: Django's own template engine, including its built-in loaders, context processors, tags and filters. Ideally these subsystems would be implemented in distinct packages. However keeping them together made the implementation of Multiple Template Engines less disruptive . Here's a breakdown of which modules belong to which subsystem. Multiple Template Engines: - django.template.backends.* - django.template.loader - django.template.response Django Template Language: - django.template.base - django.template.context - django.template.context_processors - django.template.loaders.* - django.template.debug - django.template.defaultfilters - django.template.defaulttags - django.template.engine - django.template.loader_tags - django.template.smartif Shared: - django.template.utils """ # Multiple Template Engines from .engine import Engine from .utils import EngineHandler engines = EngineHandler() __all__ = ('Engine', 'engines') # Django Template Language # Public exceptions from .base import VariableDoesNotExist # NOQA isort:skip from .context import ContextPopException # NOQA isort:skip from .exceptions import TemplateDoesNotExist, TemplateSyntaxError # NOQA isort:skip # Template parts from .base import ( # NOQA isort:skip Context, Node, NodeList, Origin, RequestContext, StringOrigin, Template, Variable, ) # Library management from .library import Library # NOQA isort:skip __all__ += ('Template', 'Context', 'RequestContext')
57aef16161bb2e7e21113f1860feab104269803192961921bbcfee2f0b7ffaba
from django.utils import six from django.utils.deprecation import ( DeprecationInstanceCheck, RemovedInDjango20Warning, ) from . import engines from .base import Origin from .exceptions import TemplateDoesNotExist def get_template(template_name, using=None): """ Loads and returns a template for the given name. Raises TemplateDoesNotExist if no such template exists. """ chain = [] engines = _engine_list(using) for engine in engines: try: return engine.get_template(template_name) except TemplateDoesNotExist as e: chain.append(e) raise TemplateDoesNotExist(template_name, chain=chain) def select_template(template_name_list, using=None): """ Loads and returns a template for one of the given names. Tries names in order and returns the first template found. Raises TemplateDoesNotExist if no such template exists. """ if isinstance(template_name_list, six.string_types): raise TypeError( 'select_template() takes an iterable of template names but got a ' 'string: %r. Use get_template() if you want to load a single ' 'template by name.' % template_name_list ) chain = [] engines = _engine_list(using) for template_name in template_name_list: for engine in engines: try: return engine.get_template(template_name) except TemplateDoesNotExist as e: chain.append(e) if template_name_list: raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) else: raise TemplateDoesNotExist("No template names provided") def render_to_string(template_name, context=None, request=None, using=None): """ Loads a template and renders it with a context. Returns a string. template_name may be a string or a list of strings. """ if isinstance(template_name, (list, tuple)): template = select_template(template_name, using=using) else: template = get_template(template_name, using=using) return template.render(context, request) def _engine_list(using=None): return engines.all() if using is None else [engines[using]] class LoaderOrigin(six.with_metaclass(DeprecationInstanceCheck, Origin)): alternative = 'django.template.Origin' deprecation_warning = RemovedInDjango20Warning
57b0c6418bb407ec792278d3a6807072d2d4777f442565eaf956b18ee20097d7
""" This module contains generic exceptions used by template backends. Although, due to historical reasons, the Django template language also internally uses these exceptions, other exceptions specific to the DTL should not be added here. """ class TemplateDoesNotExist(Exception): """ The exception used when a template does not exist. Accepts the following optional arguments: backend The template backend class used when raising this exception. tried A list of sources that were tried when finding the template. This is formatted as a list of tuples containing (origin, status), where origin is an Origin object or duck type and status is a string with the reason the template wasn't found. chain A list of intermediate TemplateDoesNotExist exceptions. This is used to encapsulate multiple exceptions when loading templates from multiple engines. """ def __init__(self, msg, tried=None, backend=None, chain=None): self.backend = backend if tried is None: tried = [] self.tried = tried if chain is None: chain = [] self.chain = chain super(TemplateDoesNotExist, self).__init__(msg) class TemplateSyntaxError(Exception): """ The exception used for syntax errors during parsing or rendering. """ pass
f96a56de949aa137e15d6f538144311f0970366cda4e825ace2896c7dcd9e503
from django.http import HttpResponse from django.utils import six from .loader import get_template, select_template class ContentNotRenderedError(Exception): pass class SimpleTemplateResponse(HttpResponse): rendering_attrs = ['template_name', 'context_data', '_post_render_callbacks'] def __init__(self, template, context=None, content_type=None, status=None, charset=None, using=None): # It would seem obvious to call these next two members 'template' and # 'context', but those names are reserved as part of the test Client # API. To avoid the name collision, we use different names. self.template_name = template self.context_data = context self.using = using self._post_render_callbacks = [] # _request stores the current request object in subclasses that know # about requests, like TemplateResponse. It's defined in the base class # to minimize code duplication. # It's called self._request because self.request gets overwritten by # django.test.client.Client. Unlike template_name and context_data, # _request should not be considered part of the public API. self._request = None # content argument doesn't make sense here because it will be replaced # with rendered template so we always pass empty string in order to # prevent errors and provide shorter signature. super(SimpleTemplateResponse, self).__init__('', content_type, status, charset) # _is_rendered tracks whether the template and context has been baked # into a final response. # Super __init__ doesn't know any better than to set self.content to # the empty string we just gave it, which wrongly sets _is_rendered # True, so we initialize it to False after the call to super __init__. self._is_rendered = False def __getstate__(self): """Pickling support function. Ensures that the object can't be pickled before it has been rendered, and that the pickled state only includes rendered data, not the data used to construct the response. """ obj_dict = self.__dict__.copy() if not self._is_rendered: raise ContentNotRenderedError('The response content must be ' 'rendered before it can be pickled.') for attr in self.rendering_attrs: if attr in obj_dict: del obj_dict[attr] return obj_dict def resolve_template(self, template): "Accepts a template object, path-to-template or list of paths" if isinstance(template, (list, tuple)): return select_template(template, using=self.using) elif isinstance(template, six.string_types): return get_template(template, using=self.using) else: return template def resolve_context(self, context): return context @property def rendered_content(self): """Returns the freshly rendered content for the template and context described by the TemplateResponse. This *does not* set the final content of the response. To set the response content, you must either call render(), or set the content explicitly using the value of this property. """ template = self.resolve_template(self.template_name) context = self.resolve_context(self.context_data) content = template.render(context, self._request) return content def add_post_render_callback(self, callback): """Adds a new post-rendering callback. If the response has already been rendered, invoke the callback immediately. """ if self._is_rendered: callback(self) else: self._post_render_callbacks.append(callback) def render(self): """Renders (thereby finalizing) the content of the response. If the content has already been rendered, this is a no-op. Returns the baked response instance. """ retval = self if not self._is_rendered: self.content = self.rendered_content for post_callback in self._post_render_callbacks: newretval = post_callback(retval) if newretval is not None: retval = newretval return retval @property def is_rendered(self): return self._is_rendered def __iter__(self): if not self._is_rendered: raise ContentNotRenderedError( 'The response content must be rendered before it can be iterated over.' ) return super(SimpleTemplateResponse, self).__iter__() @property def content(self): if not self._is_rendered: raise ContentNotRenderedError( 'The response content must be rendered before it can be accessed.' ) return super(SimpleTemplateResponse, self).content @content.setter def content(self, value): """Sets the content for the response """ HttpResponse.content.fset(self, value) self._is_rendered = True class TemplateResponse(SimpleTemplateResponse): rendering_attrs = SimpleTemplateResponse.rendering_attrs + ['_request'] def __init__(self, request, template, context=None, content_type=None, status=None, charset=None, using=None): super(TemplateResponse, self).__init__( template, context, content_type, status, charset, using) self._request = request