repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/string_lookup/tests.py
tests/string_lookup/tests.py
from django.test import TestCase from .models import Article, Bar, Base, Child, Foo, Whiz class StringLookupTests(TestCase): def test_string_form_referencing(self): """ Regression test for #1661 and #1662 String form referencing of models works, both as pre and post reference, on all RelatedField types. """ f1 = Foo(name="Foo1") f1.save() f2 = Foo(name="Foo2") f2.save() w1 = Whiz(name="Whiz1") w1.save() b1 = Bar(name="Bar1", normal=f1, fwd=w1, back=f2) b1.save() self.assertEqual(b1.normal, f1) self.assertEqual(b1.fwd, w1) self.assertEqual(b1.back, f2) base1 = Base(name="Base1") base1.save() child1 = Child(name="Child1", parent=base1) child1.save() self.assertEqual(child1.parent, base1) def test_unicode_chars_in_queries(self): """ Regression tests for #3937 make sure we can use unicode characters in queries. If these tests fail on MySQL, it's a problem with the test setup. A properly configured UTF-8 database can handle this. """ fx = Foo(name="Bjorn", friend="François") fx.save() self.assertEqual(Foo.objects.get(friend__contains="\xe7"), fx) def test_queries_on_textfields(self): """ Regression tests for #5087 make sure we can perform queries on TextFields. """ a = Article(name="Test", text="The quick brown fox jumps over the lazy dog.") a.save() self.assertEqual( Article.objects.get( text__exact="The quick brown fox jumps over the lazy dog." ), a, ) self.assertEqual(Article.objects.get(text__contains="quick brown fox"), a) def test_ipaddress_on_postgresql(self): """ Regression test for #708 "like" queries on IP address fields require casting with HOST() (on PostgreSQL). """ a = Article(name="IP test", text="The body", submitted_from="192.0.2.100") a.save() self.assertSequenceEqual( Article.objects.filter(submitted_from__contains="192.0.2"), [a] ) # The searches do not match the subnet mask (/32 in this case) self.assertEqual( Article.objects.filter(submitted_from__contains="32").count(), 0 )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_checks/models.py
tests/admin_checks/models.py
""" Tests of ModelAdmin system checks logic. """ from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Album(models.Model): title = models.CharField(max_length=150) class Song(models.Model): title = models.CharField(max_length=150) album = models.ForeignKey(Album, models.CASCADE) original_release = models.DateField(editable=False) class Meta: ordering = ("title",) def __str__(self): return self.title def readonly_method_on_model(self): # does nothing pass class TwoAlbumFKAndAnE(models.Model): album1 = models.ForeignKey(Album, models.CASCADE, related_name="album1_set") album2 = models.ForeignKey(Album, models.CASCADE, related_name="album2_set") e = models.CharField(max_length=1) class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): name = models.CharField(max_length=100) subtitle = models.CharField(max_length=100) price = models.FloatField() authors = models.ManyToManyField(Author, through="AuthorsBooks") class AuthorsBooks(models.Model): author = models.ForeignKey(Author, models.CASCADE) book = models.ForeignKey(Book, models.CASCADE) featured = models.BooleanField() class State(models.Model): name = models.CharField(max_length=15) class City(models.Model): state = models.ForeignKey(State, models.CASCADE) class Influence(models.Model): name = models.TextField() content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_checks/__init__.py
tests/admin_checks/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_checks/tests.py
tests/admin_checks/tests.py
from django import forms from django.contrib import admin from django.contrib.admin import AdminSite from django.contrib.auth.backends import ModelBackend from django.contrib.auth.middleware import AuthenticationMiddleware from django.contrib.contenttypes.admin import GenericStackedInline from django.contrib.messages.middleware import MessageMiddleware from django.contrib.sessions.middleware import SessionMiddleware from django.core import checks from django.test import SimpleTestCase, override_settings from .models import Album, Author, Book, City, Influence, Song, State, TwoAlbumFKAndAnE class SongForm(forms.ModelForm): pass class ValidFields(admin.ModelAdmin): form = SongForm fields = ["title"] class ValidFormFieldsets(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): class ExtraFieldForm(SongForm): name = forms.CharField(max_length=50) return ExtraFieldForm fieldsets = ( ( None, { "fields": ("name",), }, ), ) class MyAdmin(admin.ModelAdmin): def check(self, **kwargs): return ["error!"] class AuthenticationMiddlewareSubclass(AuthenticationMiddleware): pass class MessageMiddlewareSubclass(MessageMiddleware): pass class ModelBackendSubclass(ModelBackend): pass class SessionMiddlewareSubclass(SessionMiddleware): pass @override_settings( SILENCED_SYSTEM_CHECKS=["fields.W342"], # ForeignKey(unique=True) INSTALLED_APPS=[ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.messages", "admin_checks", ], ) class SystemChecksTestCase(SimpleTestCase): databases = "__all__" def test_checks_are_performed(self): admin.site.register(Song, MyAdmin) try: errors = checks.run_checks() expected = ["error!"] self.assertEqual(errors, expected) finally: admin.site.unregister(Song) @override_settings(INSTALLED_APPS=["django.contrib.admin"]) def test_apps_dependencies(self): errors = admin.checks.check_dependencies() expected = [ checks.Error( "'django.contrib.contenttypes' must be in " "INSTALLED_APPS in order to use the admin application.", id="admin.E401", ), checks.Error( "'django.contrib.auth' must be in INSTALLED_APPS in order " "to use the admin application.", id="admin.E405", ), checks.Error( "'django.contrib.messages' must be in INSTALLED_APPS in order " "to use the admin application.", id="admin.E406", ), ] self.assertEqual(errors, expected) @override_settings(TEMPLATES=[]) def test_no_template_engines(self): self.assertEqual( admin.checks.check_dependencies(), [ checks.Error( "A 'django.template.backends.django.DjangoTemplates' " "instance must be configured in TEMPLATES in order to use " "the admin application.", id="admin.E403", ) ], ) @override_settings( TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [], }, } ], ) def test_context_processor_dependencies(self): expected = [ checks.Error( "'django.contrib.auth.context_processors.auth' must be " "enabled in DjangoTemplates (TEMPLATES) if using the default " "auth backend in order to use the admin application.", id="admin.E402", ), checks.Error( "'django.contrib.messages.context_processors.messages' must " "be enabled in DjangoTemplates (TEMPLATES) in order to use " "the admin application.", id="admin.E404", ), checks.Warning( "'django.template.context_processors.request' must be enabled " "in DjangoTemplates (TEMPLATES) in order to use the admin " "navigation sidebar.", id="admin.W411", ), ] self.assertEqual(admin.checks.check_dependencies(), expected) # The first error doesn't happen if # 'django.contrib.auth.backends.ModelBackend' isn't in # AUTHENTICATION_BACKENDS. with self.settings(AUTHENTICATION_BACKENDS=[]): self.assertEqual(admin.checks.check_dependencies(), expected[1:]) @override_settings( AUTHENTICATION_BACKENDS=["admin_checks.tests.ModelBackendSubclass"], TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.request", "django.contrib.messages.context_processors.messages", ], }, } ], ) def test_context_processor_dependencies_model_backend_subclass(self): self.assertEqual( admin.checks.check_dependencies(), [ checks.Error( "'django.contrib.auth.context_processors.auth' must be " "enabled in DjangoTemplates (TEMPLATES) if using the default " "auth backend in order to use the admin application.", id="admin.E402", ), ], ) @override_settings( TEMPLATES=[ { "BACKEND": "django.template.backends.dummy.TemplateStrings", "DIRS": [], "APP_DIRS": True, }, { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ], ) def test_several_templates_backends(self): self.assertEqual(admin.checks.check_dependencies(), []) @override_settings(MIDDLEWARE=[]) def test_middleware_dependencies(self): errors = admin.checks.check_dependencies() expected = [ checks.Error( "'django.contrib.auth.middleware.AuthenticationMiddleware' " "must be in MIDDLEWARE in order to use the admin application.", id="admin.E408", ), checks.Error( "'django.contrib.messages.middleware.MessageMiddleware' " "must be in MIDDLEWARE in order to use the admin application.", id="admin.E409", ), checks.Error( "'django.contrib.sessions.middleware.SessionMiddleware' " "must be in MIDDLEWARE in order to use the admin application.", hint=( "Insert " "'django.contrib.sessions.middleware.SessionMiddleware' " "before " "'django.contrib.auth.middleware.AuthenticationMiddleware'." ), id="admin.E410", ), ] self.assertEqual(errors, expected) @override_settings( MIDDLEWARE=[ "admin_checks.tests.AuthenticationMiddlewareSubclass", "admin_checks.tests.MessageMiddlewareSubclass", "admin_checks.tests.SessionMiddlewareSubclass", ] ) def test_middleware_subclasses(self): self.assertEqual(admin.checks.check_dependencies(), []) @override_settings( MIDDLEWARE=[ "django.contrib.does.not.Exist", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", ] ) def test_admin_check_ignores_import_error_in_middleware(self): self.assertEqual(admin.checks.check_dependencies(), []) def test_custom_adminsite(self): class CustomAdminSite(admin.AdminSite): pass custom_site = CustomAdminSite() custom_site.register(Song, MyAdmin) try: errors = checks.run_checks() expected = ["error!"] self.assertEqual(errors, expected) finally: custom_site.unregister(Song) def test_allows_checks_relying_on_other_modeladmins(self): class MyBookAdmin(admin.ModelAdmin): def check(self, **kwargs): errors = super().check(**kwargs) if not self.admin_site.is_registered(Author): errors.append("AuthorAdmin missing!") return errors class MyAuthorAdmin(admin.ModelAdmin): pass admin.site.register(Book, MyBookAdmin) admin.site.register(Author, MyAuthorAdmin) try: self.assertEqual(admin.site.check(None), []) finally: admin.site.unregister(Book) admin.site.unregister(Author) def test_field_name_not_in_list_display(self): class SongAdmin(admin.ModelAdmin): list_editable = ["original_release"] errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "The value of 'list_editable[0]' refers to 'original_release', " "which is not contained in 'list_display'.", obj=SongAdmin, id="admin.E122", ) ] self.assertEqual(errors, expected) def test_list_editable_not_a_list_or_tuple(self): class SongAdmin(admin.ModelAdmin): list_editable = "test" self.assertEqual( SongAdmin(Song, AdminSite()).check(), [ checks.Error( "The value of 'list_editable' must be a list or tuple.", obj=SongAdmin, id="admin.E120", ) ], ) def test_list_editable_missing_field(self): class SongAdmin(admin.ModelAdmin): list_editable = ("test",) self.assertEqual( SongAdmin(Song, AdminSite()).check(), [ checks.Error( "The value of 'list_editable[0]' refers to 'test', which is " "not a field of 'admin_checks.Song'.", obj=SongAdmin, id="admin.E121", ) ], ) def test_readonly_and_editable(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ["original_release"] list_display = ["pk", "original_release"] list_editable = ["original_release"] fieldsets = [ ( None, { "fields": ["title", "original_release"], }, ), ] errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "The value of 'list_editable[0]' refers to 'original_release', " "which is not editable through the admin.", obj=SongAdmin, id="admin.E125", ) ] self.assertEqual(errors, expected) def test_pk_not_editable(self): # PKs cannot be edited in the list. class SongAdmin(admin.ModelAdmin): list_display = ["title", "id"] list_editable = ["id"] errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "The value of 'list_editable[0]' refers to 'id', which is not editable " "through the admin.", obj=SongAdmin, id="admin.E125", ) ] self.assertEqual(errors, expected) def test_editable(self): class SongAdmin(admin.ModelAdmin): list_display = ["pk", "title"] list_editable = ["title"] fieldsets = [ ( None, { "fields": ["title", "original_release"], }, ), ] errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_custom_modelforms_with_fields_fieldsets(self): """ # Regression test for #8027: custom ModelForms with fields/fieldsets """ errors = ValidFields(Song, AdminSite()).check() self.assertEqual(errors, []) def test_custom_get_form_with_fieldsets(self): """ The fieldsets checks are skipped when the ModelAdmin.get_form() method is overridden. """ errors = ValidFormFieldsets(Song, AdminSite()).check() self.assertEqual(errors, []) def test_fieldsets_fields_non_tuple(self): """ The first fieldset's fields must be a list/tuple. """ class NotATupleAdmin(admin.ModelAdmin): list_display = ["pk", "title"] list_editable = ["title"] fieldsets = [ (None, {"fields": "title"}), # not a tuple ] errors = NotATupleAdmin(Song, AdminSite()).check() expected = [ checks.Error( "The value of 'fieldsets[0][1]['fields']' must be a list or tuple.", obj=NotATupleAdmin, id="admin.E008", ) ] self.assertEqual(errors, expected) def test_nonfirst_fieldset(self): """ The second fieldset's fields must be a list/tuple. """ class NotATupleAdmin(admin.ModelAdmin): fieldsets = [ (None, {"fields": ("title",)}), ("foo", {"fields": "author"}), # not a tuple ] errors = NotATupleAdmin(Song, AdminSite()).check() expected = [ checks.Error( "The value of 'fieldsets[1][1]['fields']' must be a list or tuple.", obj=NotATupleAdmin, id="admin.E008", ) ] self.assertEqual(errors, expected) def test_exclude_values(self): """ Tests for basic system checks of 'exclude' option values (#12689) """ class ExcludedFields1(admin.ModelAdmin): exclude = "foo" errors = ExcludedFields1(Book, AdminSite()).check() expected = [ checks.Error( "The value of 'exclude' must be a list or tuple.", obj=ExcludedFields1, id="admin.E014", ) ] self.assertEqual(errors, expected) def test_exclude_duplicate_values(self): class ExcludedFields2(admin.ModelAdmin): exclude = ("name", "name") errors = ExcludedFields2(Book, AdminSite()).check() expected = [ checks.Error( "The value of 'exclude' contains duplicate field(s).", hint="Remove duplicates of 'name'.", obj=ExcludedFields2, id="admin.E015", ) ] self.assertEqual(errors, expected) def test_exclude_in_inline(self): class ExcludedFieldsInline(admin.TabularInline): model = Song exclude = "foo" class ExcludedFieldsAlbumAdmin(admin.ModelAdmin): model = Album inlines = [ExcludedFieldsInline] errors = ExcludedFieldsAlbumAdmin(Album, AdminSite()).check() expected = [ checks.Error( "The value of 'exclude' must be a list or tuple.", obj=ExcludedFieldsInline, id="admin.E014", ) ] self.assertEqual(errors, expected) def test_exclude_inline_model_admin(self): """ Regression test for #9932 - exclude in InlineModelAdmin should not contain the ForeignKey field used in ModelAdmin.model """ class SongInline(admin.StackedInline): model = Song exclude = ["album"] class AlbumAdmin(admin.ModelAdmin): model = Album inlines = [SongInline] errors = AlbumAdmin(Album, AdminSite()).check() expected = [ checks.Error( "Cannot exclude the field 'album', because it is the foreign key " "to the parent model 'admin_checks.Album'.", obj=SongInline, id="admin.E201", ) ] self.assertEqual(errors, expected) def test_valid_generic_inline_model_admin(self): """ Regression test for #22034 - check that generic inlines don't look for normal ForeignKey relations. """ class InfluenceInline(GenericStackedInline): model = Influence class SongAdmin(admin.ModelAdmin): inlines = [InfluenceInline] errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_generic_inline_model_admin_non_generic_model(self): """ A model without a GenericForeignKey raises problems if it's included in a GenericInlineModelAdmin definition. """ class BookInline(GenericStackedInline): model = Book class SongAdmin(admin.ModelAdmin): inlines = [BookInline] errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "'admin_checks.Book' has no GenericForeignKey.", obj=BookInline, id="admin.E301", ) ] self.assertEqual(errors, expected) def test_generic_inline_model_admin_bad_ct_field(self): """ A GenericInlineModelAdmin errors if the ct_field points to a nonexistent field. """ class InfluenceInline(GenericStackedInline): model = Influence ct_field = "nonexistent" class SongAdmin(admin.ModelAdmin): inlines = [InfluenceInline] errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "'ct_field' references 'nonexistent', which is not a field on " "'admin_checks.Influence'.", obj=InfluenceInline, id="admin.E302", ) ] self.assertEqual(errors, expected) def test_generic_inline_model_admin_bad_fk_field(self): """ A GenericInlineModelAdmin errors if the ct_fk_field points to a nonexistent field. """ class InfluenceInline(GenericStackedInline): model = Influence ct_fk_field = "nonexistent" class SongAdmin(admin.ModelAdmin): inlines = [InfluenceInline] errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "'ct_fk_field' references 'nonexistent', which is not a field on " "'admin_checks.Influence'.", obj=InfluenceInline, id="admin.E303", ) ] self.assertEqual(errors, expected) def test_generic_inline_model_admin_non_gfk_ct_field(self): """ A GenericInlineModelAdmin raises problems if the ct_field points to a field that isn't part of a GenericForeignKey. """ class InfluenceInline(GenericStackedInline): model = Influence ct_field = "name" class SongAdmin(admin.ModelAdmin): inlines = [InfluenceInline] errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "'admin_checks.Influence' has no GenericForeignKey using " "content type field 'name' and object ID field 'object_id'.", obj=InfluenceInline, id="admin.E304", ) ] self.assertEqual(errors, expected) def test_generic_inline_model_admin_non_gfk_fk_field(self): """ A GenericInlineModelAdmin raises problems if the ct_fk_field points to a field that isn't part of a GenericForeignKey. """ class InfluenceInline(GenericStackedInline): model = Influence ct_fk_field = "name" class SongAdmin(admin.ModelAdmin): inlines = [InfluenceInline] errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "'admin_checks.Influence' has no GenericForeignKey using " "content type field 'content_type' and object ID field 'name'.", obj=InfluenceInline, id="admin.E304", ) ] self.assertEqual(errors, expected) def test_app_label_in_admin_checks(self): class RawIdNonexistentAdmin(admin.ModelAdmin): raw_id_fields = ("nonexistent",) errors = RawIdNonexistentAdmin(Album, AdminSite()).check() expected = [ checks.Error( "The value of 'raw_id_fields[0]' refers to 'nonexistent', " "which is not a field of 'admin_checks.Album'.", obj=RawIdNonexistentAdmin, id="admin.E002", ) ] self.assertEqual(errors, expected) def test_fk_exclusion(self): """ Regression test for #11709 - when testing for fk excluding (when exclude is given) make sure fk_name is honored or things blow up when there is more than one fk to the parent model. """ class TwoAlbumFKAndAnEInline(admin.TabularInline): model = TwoAlbumFKAndAnE exclude = ("e",) fk_name = "album1" class MyAdmin(admin.ModelAdmin): inlines = [TwoAlbumFKAndAnEInline] errors = MyAdmin(Album, AdminSite()).check() self.assertEqual(errors, []) def test_inline_self_check(self): class TwoAlbumFKAndAnEInline(admin.TabularInline): model = TwoAlbumFKAndAnE class MyAdmin(admin.ModelAdmin): inlines = [TwoAlbumFKAndAnEInline] errors = MyAdmin(Album, AdminSite()).check() expected = [ checks.Error( "'admin_checks.TwoAlbumFKAndAnE' has more than one ForeignKey " "to 'admin_checks.Album'. You must specify a 'fk_name' " "attribute.", obj=TwoAlbumFKAndAnEInline, id="admin.E202", ) ] self.assertEqual(errors, expected) def test_inline_with_specified(self): class TwoAlbumFKAndAnEInline(admin.TabularInline): model = TwoAlbumFKAndAnE fk_name = "album1" class MyAdmin(admin.ModelAdmin): inlines = [TwoAlbumFKAndAnEInline] errors = MyAdmin(Album, AdminSite()).check() self.assertEqual(errors, []) def test_inlines_property(self): class CitiesInline(admin.TabularInline): model = City class StateAdmin(admin.ModelAdmin): @property def inlines(self): return [CitiesInline] errors = StateAdmin(State, AdminSite()).check() self.assertEqual(errors, []) def test_readonly(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("title",) errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_readonly_on_method(self): @admin.display def my_function(obj): pass class SongAdmin(admin.ModelAdmin): readonly_fields = (my_function,) errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_readonly_on_modeladmin(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("readonly_method_on_modeladmin",) @admin.display def readonly_method_on_modeladmin(self, obj): pass errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_readonly_dynamic_attribute_on_modeladmin(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("dynamic_method",) def __getattr__(self, item): if item == "dynamic_method": @admin.display def method(obj): pass return method raise AttributeError errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_readonly_method_on_model(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("readonly_method_on_model",) errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_nonexistent_field(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("title", "nonexistent") errors = SongAdmin(Song, AdminSite()).check() expected = [ checks.Error( "The value of 'readonly_fields[1]' refers to 'nonexistent', which is " "not a callable, an attribute of 'SongAdmin', or an attribute of " "'admin_checks.Song'.", obj=SongAdmin, id="admin.E035", ) ] self.assertEqual(errors, expected) def test_nonexistent_field_on_inline(self): class CityInline(admin.TabularInline): model = City readonly_fields = ["i_dont_exist"] # Missing attribute errors = CityInline(State, AdminSite()).check() expected = [ checks.Error( "The value of 'readonly_fields[0]' refers to 'i_dont_exist', which is " "not a callable, an attribute of 'CityInline', or an attribute of " "'admin_checks.City'.", obj=CityInline, id="admin.E035", ) ] self.assertEqual(errors, expected) def test_readonly_fields_not_list_or_tuple(self): class SongAdmin(admin.ModelAdmin): readonly_fields = "test" self.assertEqual( SongAdmin(Song, AdminSite()).check(), [ checks.Error( "The value of 'readonly_fields' must be a list or tuple.", obj=SongAdmin, id="admin.E034", ) ], ) def test_extra(self): class SongAdmin(admin.ModelAdmin): @admin.display def awesome_song(self, instance): if instance.title == "Born to Run": return "Best Ever!" return "Status unknown." errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_readonly_lambda(self): class SongAdmin(admin.ModelAdmin): readonly_fields = (lambda obj: "test",) errors = SongAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_graceful_m2m_fail(self): """ Regression test for #12203/#12237 - Fail more gracefully when a M2M field that specifies the 'through' option is included in the 'fields' or the 'fieldsets' ModelAdmin options. """ class BookAdmin(admin.ModelAdmin): fields = ["authors"] errors = BookAdmin(Book, AdminSite()).check() expected = [ checks.Error( "The value of 'fields' cannot include the ManyToManyField 'authors', " "because that field manually specifies a relationship model.", obj=BookAdmin, id="admin.E013", ) ] self.assertEqual(errors, expected) def test_cannot_include_through(self): class FieldsetBookAdmin(admin.ModelAdmin): fieldsets = ( ("Header 1", {"fields": ("name",)}), ("Header 2", {"fields": ("authors",)}), ) errors = FieldsetBookAdmin(Book, AdminSite()).check() expected = [ checks.Error( "The value of 'fieldsets[1][1][\"fields\"]' cannot include the " "ManyToManyField 'authors', because that field manually specifies a " "relationship model.", obj=FieldsetBookAdmin, id="admin.E013", ) ] self.assertEqual(errors, expected) def test_nested_fields(self): class NestedFieldsAdmin(admin.ModelAdmin): fields = ("price", ("name", "subtitle")) errors = NestedFieldsAdmin(Book, AdminSite()).check() self.assertEqual(errors, []) def test_nested_fieldsets(self): class NestedFieldsetAdmin(admin.ModelAdmin): fieldsets = (("Main", {"fields": ("price", ("name", "subtitle"))}),) errors = NestedFieldsetAdmin(Book, AdminSite()).check() self.assertEqual(errors, []) def test_explicit_through_override(self): """ Regression test for #12209 -- If the explicitly provided through model is specified as a string, the admin should still be able use Model.m2m_field.through """ class AuthorsInline(admin.TabularInline): model = Book.authors.through class BookAdmin(admin.ModelAdmin): inlines = [AuthorsInline] errors = BookAdmin(Book, AdminSite()).check() self.assertEqual(errors, []) def test_non_model_fields(self): """ Regression for ensuring ModelAdmin.fields can contain non-model fields that broke with r11737 """ class SongForm(forms.ModelForm): extra_data = forms.CharField() class FieldsOnFormOnlyAdmin(admin.ModelAdmin): form = SongForm fields = ["title", "extra_data"] errors = FieldsOnFormOnlyAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_non_model_first_field(self): """ Regression for ensuring ModelAdmin.field can handle first elem being a non-model field (test fix for UnboundLocalError introduced with r16225). """ class SongForm(forms.ModelForm): extra_data = forms.CharField() class Meta: model = Song fields = "__all__" class FieldsOnFormOnlyAdmin(admin.ModelAdmin): form = SongForm fields = ["extra_data", "title"] errors = FieldsOnFormOnlyAdmin(Song, AdminSite()).check() self.assertEqual(errors, []) def test_check_sublists_for_duplicates(self): class MyModelAdmin(admin.ModelAdmin): fields = ["state", ["state"]] errors = MyModelAdmin(Song, AdminSite()).check() expected = [ checks.Error( "The value of 'fields' contains duplicate field(s).", hint="Remove duplicates of 'state'.", obj=MyModelAdmin, id="admin.E006", ) ] self.assertEqual(errors, expected) def test_check_fieldset_sublists_for_duplicates(self): class MyModelAdmin(admin.ModelAdmin): fieldsets = [ (None, {"fields": ["title", "album", ("title", "album")]}), ] errors = MyModelAdmin(Song, AdminSite()).check() expected = [ checks.Error( "There are duplicate field(s) in 'fieldsets[0][1]'.", hint="Remove duplicates of 'title', 'album'.", obj=MyModelAdmin, id="admin.E012",
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/custom_pk/models.py
tests/custom_pk/models.py
""" Using a custom primary key By default, Django adds an ``"id"`` field to each model. But you can override this behavior by explicitly adding ``primary_key=True`` to a field. """ from django.db import models from .fields import MyAutoField, MyWrapperField class Employee(models.Model): employee_code = models.IntegerField(primary_key=True, db_column="code") first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) class Meta: ordering = ("last_name", "first_name") def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Business(models.Model): name = models.CharField(max_length=20, primary_key=True) employees = models.ManyToManyField(Employee) class Meta: verbose_name_plural = "businesses" class Bar(models.Model): id = MyWrapperField(primary_key=True, db_index=True) class Foo(models.Model): bar = models.ForeignKey(Bar, models.CASCADE) class CustomAutoFieldModel(models.Model): id = MyAutoField(primary_key=True)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/custom_pk/fields.py
tests/custom_pk/fields.py
import random import string from django.db import models class MyWrapper: def __init__(self, value): self.value = value def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self.value) def __str__(self): return self.value def __eq__(self, other): if isinstance(other, self.__class__): return self.value == other.value return self.value == other def __hash__(self): return hash(self.value) class MyWrapperField(models.CharField): def __init__(self, *args, **kwargs): kwargs["max_length"] = 10 super().__init__(*args, **kwargs) def pre_save(self, instance, add): value = getattr(instance, self.attname, None) if not value: value = MyWrapper("".join(random.sample(string.ascii_lowercase, 10))) setattr(instance, self.attname, value) return value def to_python(self, value): if not value: return if not isinstance(value, MyWrapper): value = MyWrapper(value) return value def from_db_value(self, value, expression, connection): if not value: return return MyWrapper(value) def get_db_prep_save(self, value, connection): if not value: return if isinstance(value, MyWrapper): return str(value) return value def get_db_prep_value(self, value, connection, prepared=False): if not value: return if isinstance(value, MyWrapper): return str(value) return value class MyAutoField(models.BigAutoField): def from_db_value(self, value, expression, connection): if value is None: return None return MyWrapper(value) def get_prep_value(self, value): if value is None: return None return int(value)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/custom_pk/__init__.py
tests/custom_pk/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/custom_pk/tests.py
tests/custom_pk/tests.py
from django.db import IntegrityError, transaction from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from .fields import MyWrapper from .models import Bar, Business, CustomAutoFieldModel, Employee, Foo class BasicCustomPKTests(TestCase): @classmethod def setUpTestData(cls): cls.dan = Employee.objects.create( employee_code=123, first_name="Dan", last_name="Jones", ) cls.fran = Employee.objects.create( employee_code=456, first_name="Fran", last_name="Bones", ) cls.business = Business.objects.create(name="Sears") cls.business.employees.add(cls.dan, cls.fran) def test_querysets(self): """ Both pk and custom attribute_name can be used in filter and friends """ self.assertSequenceEqual(Employee.objects.filter(pk=123), [self.dan]) self.assertSequenceEqual(Employee.objects.filter(employee_code=123), [self.dan]) self.assertSequenceEqual( Employee.objects.filter(pk__in=[123, 456]), [self.fran, self.dan], ) self.assertSequenceEqual(Employee.objects.all(), [self.fran, self.dan]) self.assertQuerySetEqual( Business.objects.filter(name="Sears"), ["Sears"], lambda b: b.name ) self.assertQuerySetEqual( Business.objects.filter(pk="Sears"), [ "Sears", ], lambda b: b.name, ) def test_querysets_related_name(self): """ Custom pk doesn't affect related_name based lookups """ self.assertSequenceEqual( self.business.employees.all(), [self.fran, self.dan], ) self.assertQuerySetEqual( self.fran.business_set.all(), [ "Sears", ], lambda b: b.name, ) def test_querysets_relational(self): """ Queries across tables, involving primary key """ self.assertSequenceEqual( Employee.objects.filter(business__name="Sears"), [self.fran, self.dan], ) self.assertSequenceEqual( Employee.objects.filter(business__pk="Sears"), [self.fran, self.dan], ) self.assertQuerySetEqual( Business.objects.filter(employees__employee_code=123), [ "Sears", ], lambda b: b.name, ) self.assertQuerySetEqual( Business.objects.filter(employees__pk=123), [ "Sears", ], lambda b: b.name, ) self.assertQuerySetEqual( Business.objects.filter(employees__first_name__startswith="Fran"), [ "Sears", ], lambda b: b.name, ) def test_get(self): """ Get can accept pk or the real attribute name """ self.assertEqual(Employee.objects.get(pk=123), self.dan) self.assertEqual(Employee.objects.get(pk=456), self.fran) with self.assertRaises(Employee.DoesNotExist): Employee.objects.get(pk=42) # Use the name of the primary key, rather than pk. self.assertEqual(Employee.objects.get(employee_code=123), self.dan) def test_pk_attributes(self): """ pk and attribute name are available on the model No default id attribute is added """ # pk can be used as a substitute for the primary key. # The primary key can be accessed via the pk property on the model. e = Employee.objects.get(pk=123) self.assertEqual(e.pk, 123) # Or we can use the real attribute name for the primary key: self.assertEqual(e.employee_code, 123) with self.assertRaisesMessage( AttributeError, "'Employee' object has no attribute 'id'" ): e.id def test_in_bulk(self): """ Custom pks work with in_bulk, both for integer and non-integer types """ emps = Employee.objects.in_bulk([123, 456]) self.assertEqual(emps[123], self.dan) self.assertEqual( Business.objects.in_bulk(["Sears"]), { "Sears": self.business, }, ) def test_save(self): """ custom pks do not affect save """ fran = Employee.objects.get(pk=456) fran.last_name = "Jones" fran.save() self.assertSequenceEqual( Employee.objects.filter(last_name="Jones"), [self.dan, fran], ) class CustomPKTests(TestCase): def test_custom_pk_create(self): """ New objects can be created both with pk and the custom name """ Employee.objects.create(employee_code=1234, first_name="Foo", last_name="Bar") Employee.objects.create(pk=1235, first_name="Foo", last_name="Baz") Business.objects.create(name="Bears") Business.objects.create(pk="Tears") def test_unicode_pk(self): # Primary key may be Unicode string. Business.objects.create(name="jaźń") def test_unique_pk(self): # The primary key must also be unique, so trying to create a new object # with the same primary key will fail. Employee.objects.create( employee_code=123, first_name="Frank", last_name="Jones" ) with self.assertRaises(IntegrityError): with transaction.atomic(): Employee.objects.create( employee_code=123, first_name="Fred", last_name="Jones" ) def test_zero_non_autoincrement_pk(self): Employee.objects.create(employee_code=0, first_name="Frank", last_name="Jones") employee = Employee.objects.get(pk=0) self.assertEqual(employee.employee_code, 0) def test_custom_field_pk(self): # Regression for #10785 -- Custom fields can be used for primary keys. new_bar = Bar.objects.create() new_foo = Foo.objects.create(bar=new_bar) f = Foo.objects.get(bar=new_bar.pk) self.assertEqual(f, new_foo) self.assertEqual(f.bar, new_bar) f = Foo.objects.get(bar=new_bar) self.assertEqual(f, new_foo) self.assertEqual(f.bar, new_bar) # SQLite lets objects be saved with an empty primary key, even though an # integer is expected. So we can't check for an error being raised in that # case for SQLite. Remove it from the suite for this next bit. @skipIfDBFeature("supports_unspecified_pk") def test_required_pk(self): # The primary key must be specified, so an error is raised if you # try to create an object without it. with self.assertRaises(IntegrityError): with transaction.atomic(): Employee.objects.create(first_name="Tom", last_name="Smith") def test_auto_field_subclass_create(self): obj = CustomAutoFieldModel.objects.create() self.assertIsInstance(obj.id, MyWrapper) @skipUnlessDBFeature("can_return_rows_from_bulk_insert") def test_auto_field_subclass_bulk_create(self): obj = CustomAutoFieldModel() CustomAutoFieldModel.objects.bulk_create([obj]) self.assertIsInstance(obj.id, MyWrapper)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_package/__init__.py
tests/model_package/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_package/tests.py
tests/model_package/tests.py
from django.db import connection, models from django.db.backends.utils import truncate_name from django.test import TestCase from .models.article import Article, Site from .models.publication import Publication class Advertisement(models.Model): customer = models.CharField(max_length=100) publications = models.ManyToManyField("model_package.Publication", blank=True) class ModelPackageTests(TestCase): def test_m2m_tables_in_subpackage_models(self): """ Regression for #12168: models split into subpackages still get M2M tables. """ p = Publication.objects.create(title="FooBar") site = Site.objects.create(name="example.com") a = Article.objects.create(headline="a foo headline") a.publications.add(p) a.sites.add(site) a = Article.objects.get(id=a.pk) self.assertEqual(a.id, a.pk) self.assertEqual(a.sites.count(), 1) def test_models_in_the_test_package(self): """ Regression for #12245 - Models can exist in the test package, too. """ p = Publication.objects.create(title="FooBar") ad = Advertisement.objects.create(customer="Lawrence Journal-World") ad.publications.add(p) ad = Advertisement.objects.get(id=ad.pk) self.assertEqual(ad.publications.count(), 1) def test_automatic_m2m_column_names(self): """ Regression for #12386 - field names on the autogenerated intermediate class that are specified as dotted strings don't retain any path component for the field or column name. """ self.assertEqual(Article.publications.through._meta.fields[1].name, "article") self.assertEqual( Article.publications.through._meta.fields[1].get_attname_column(), ("article_id", "article_id"), ) self.assertEqual( Article.publications.through._meta.fields[2].name, "publication" ) self.assertEqual( Article.publications.through._meta.fields[2].get_attname_column(), ("publication_id", "publication_id"), ) self.assertEqual( Article._meta.get_field("publications").m2m_db_table(), truncate_name( "model_package_article_publications", connection.ops.max_name_length() ), ) self.assertEqual( Article._meta.get_field("publications").m2m_column_name(), "article_id" ) self.assertEqual( Article._meta.get_field("publications").m2m_reverse_name(), "publication_id" )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_package/models/publication.py
tests/model_package/models/publication.py
from django.db import models class Publication(models.Model): title = models.CharField(max_length=30)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_package/models/article.py
tests/model_package/models/article.py
from django.db import models class Site(models.Model): name = models.CharField(max_length=100) class Article(models.Model): sites = models.ManyToManyField(Site) headline = models.CharField(max_length=100) publications = models.ManyToManyField("model_package.Publication", blank=True)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_package/models/__init__.py
tests/model_package/models/__init__.py
# Import all the models from subpackages from .article import Article from .publication import Publication __all__ = ["Article", "Publication"]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/queryset_pickle/models.py
tests/queryset_pickle/models.py
import datetime from django.db import DJANGO_VERSION_PICKLE_KEY, models from django.utils.translation import gettext_lazy as _ def standalone_number(): return 1 class Numbers: @staticmethod def get_static_number(): return 2 class PreviousDjangoVersionQuerySet(models.QuerySet): def __getstate__(self): state = super().__getstate__() state[DJANGO_VERSION_PICKLE_KEY] = "1.0" return state class MissingDjangoVersionQuerySet(models.QuerySet): def __getstate__(self): state = super().__getstate__() del state[DJANGO_VERSION_PICKLE_KEY] return state class Group(models.Model): name = models.CharField(_("name"), max_length=100) objects = models.Manager() previous_django_version_objects = PreviousDjangoVersionQuerySet.as_manager() missing_django_version_objects = MissingDjangoVersionQuerySet.as_manager() class Event(models.Model): title = models.CharField(max_length=100) group = models.ForeignKey(Group, models.CASCADE, limit_choices_to=models.Q()) class Happening(models.Model): when = models.DateTimeField(blank=True, default=datetime.datetime.now) name = models.CharField(blank=True, max_length=100, default="test") number1 = models.IntegerField(blank=True, default=standalone_number) number2 = models.IntegerField(blank=True, default=Numbers.get_static_number) event = models.OneToOneField(Event, models.CASCADE, null=True) class BinaryFieldModel(models.Model): data = models.BinaryField(null=True) class Container: # To test pickling we need a class that isn't defined on module, but # is still available from app-cache. So, the Container class moves # SomeModel outside of module level class SomeModel(models.Model): somefield = models.IntegerField() class M2MModel(models.Model): added = models.DateField(default=datetime.date.today) groups = models.ManyToManyField(Group) class AbstractEvent(Event): class Meta: abstract = True ordering = ["title"] class MyEvent(AbstractEvent): pass class Edition(models.Model): event = models.ForeignKey("MyEvent", on_delete=models.CASCADE)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/queryset_pickle/__init__.py
tests/queryset_pickle/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/queryset_pickle/tests.py
tests/queryset_pickle/tests.py
import datetime import pickle import django from django.db import models from django.test import TestCase from .models import ( BinaryFieldModel, Container, Event, Group, Happening, M2MModel, MyEvent, ) class PickleabilityTestCase(TestCase): @classmethod def setUpTestData(cls): cls.happening = ( Happening.objects.create() ) # make sure the defaults are working (#20158) def assert_pickles(self, qs): self.assertEqual(list(pickle.loads(pickle.dumps(qs))), list(qs)) def test_binaryfield(self): BinaryFieldModel.objects.create(data=b"binary data") self.assert_pickles(BinaryFieldModel.objects.all()) def test_related_field(self): g = Group.objects.create(name="Ponies Who Own Maybachs") self.assert_pickles(Event.objects.filter(group=g.id)) def test_datetime_callable_default_all(self): self.assert_pickles(Happening.objects.all()) def test_datetime_callable_default_filter(self): self.assert_pickles(Happening.objects.filter(when=datetime.datetime.now())) def test_string_as_default(self): self.assert_pickles(Happening.objects.filter(name="test")) def test_standalone_method_as_default(self): self.assert_pickles(Happening.objects.filter(number1=1)) def test_staticmethod_as_default(self): self.assert_pickles(Happening.objects.filter(number2=1)) def test_filter_reverse_fk(self): self.assert_pickles(Group.objects.filter(event=1)) def test_doesnotexist_exception(self): # Ticket #17776 original = Event.DoesNotExist("Doesn't exist") unpickled = pickle.loads(pickle.dumps(original)) # Exceptions are not equal to equivalent instances of themselves, so # can't just use assertEqual(original, unpickled) self.assertEqual(original.__class__, unpickled.__class__) self.assertEqual(original.args, unpickled.args) def test_doesnotexist_class(self): klass = Event.DoesNotExist self.assertIs(pickle.loads(pickle.dumps(klass)), klass) def test_multipleobjectsreturned_class(self): klass = Event.MultipleObjectsReturned self.assertIs(pickle.loads(pickle.dumps(klass)), klass) def test_forward_relatedobjectdoesnotexist_class(self): # ForwardManyToOneDescriptor klass = Event.group.RelatedObjectDoesNotExist self.assertIs(pickle.loads(pickle.dumps(klass)), klass) # ForwardOneToOneDescriptor klass = Happening.event.RelatedObjectDoesNotExist self.assertIs(pickle.loads(pickle.dumps(klass)), klass) def test_reverse_one_to_one_relatedobjectdoesnotexist_class(self): klass = Event.happening.RelatedObjectDoesNotExist self.assertIs(pickle.loads(pickle.dumps(klass)), klass) def test_manager_pickle(self): pickle.loads(pickle.dumps(Happening.objects)) def test_model_pickle(self): """ A model not defined on module level is picklable. """ original = Container.SomeModel(pk=1) dumped = pickle.dumps(original) reloaded = pickle.loads(dumped) self.assertEqual(original, reloaded) # Also, deferred dynamic model works Container.SomeModel.objects.create(somefield=1) original = Container.SomeModel.objects.defer("somefield")[0] dumped = pickle.dumps(original) reloaded = pickle.loads(dumped) self.assertEqual(original, reloaded) self.assertEqual(original.somefield, reloaded.somefield) def test_model_pickle_m2m(self): """ Test intentionally the automatically created through model. """ m1 = M2MModel.objects.create() g1 = Group.objects.create(name="foof") m1.groups.add(g1) m2m_through = M2MModel._meta.get_field("groups").remote_field.through original = m2m_through.objects.get() dumped = pickle.dumps(original) reloaded = pickle.loads(dumped) self.assertEqual(original, reloaded) def test_model_pickle_dynamic(self): class Meta: proxy = True dynclass = type( "DynamicEventSubclass", (Event,), {"Meta": Meta, "__module__": Event.__module__}, ) original = dynclass(pk=1) dumped = pickle.dumps(original) reloaded = pickle.loads(dumped) self.assertEqual(original, reloaded) self.assertIs(reloaded.__class__, dynclass) def test_specialized_queryset(self): self.assert_pickles(Happening.objects.values("name")) self.assert_pickles(Happening.objects.values("name").dates("when", "year")) # With related field (#14515) self.assert_pickles( Event.objects.select_related("group") .order_by("title") .values_list("title", "group__name") ) def test_pickle_prefetch_related_idempotence(self): g = Group.objects.create(name="foo") groups = Group.objects.prefetch_related("event_set") # First pickling groups = pickle.loads(pickle.dumps(groups)) self.assertSequenceEqual(groups, [g]) # Second pickling groups = pickle.loads(pickle.dumps(groups)) self.assertSequenceEqual(groups, [g]) def test_pickle_prefetch_queryset_usable_outside_of_prefetch(self): # Prefetch shouldn't affect the fetch-on-pickle behavior of the # queryset passed to it. Group.objects.create(name="foo") events = Event.objects.order_by("id") Group.objects.prefetch_related(models.Prefetch("event_set", queryset=events)) with self.assertNumQueries(1): events2 = pickle.loads(pickle.dumps(events)) with self.assertNumQueries(0): list(events2) def test_pickle_prefetch_queryset_still_usable(self): g = Group.objects.create(name="foo") groups = Group.objects.prefetch_related( models.Prefetch("event_set", queryset=Event.objects.order_by("id")) ) groups2 = pickle.loads(pickle.dumps(groups)) self.assertSequenceEqual(groups2.filter(id__gte=0), [g]) def test_pickle_prefetch_queryset_not_evaluated(self): Group.objects.create(name="foo") groups = Group.objects.prefetch_related( models.Prefetch("event_set", queryset=Event.objects.order_by("id")) ) list(groups) # evaluate QuerySet with self.assertNumQueries(0): pickle.loads(pickle.dumps(groups)) def test_pickle_prefetch_related_with_m2m_and_objects_deletion(self): """ #24831 -- Cached properties on ManyToOneRel created in QuerySet.delete() caused subsequent QuerySet pickling to fail. """ g = Group.objects.create(name="foo") m2m = M2MModel.objects.create() m2m.groups.add(g) Group.objects.all().delete() m2ms = M2MModel.objects.prefetch_related("groups") m2ms = pickle.loads(pickle.dumps(m2ms)) self.assertSequenceEqual(m2ms, [m2m]) def test_pickle_boolean_expression_in_Q__queryset(self): group = Group.objects.create(name="group") Event.objects.create(title="event", group=group) groups = Group.objects.filter( models.Q( models.Exists( Event.objects.filter(group_id=models.OuterRef("id")), ) ), ) groups2 = pickle.loads(pickle.dumps(groups)) self.assertSequenceEqual(groups2, [group]) def test_pickle_exists_queryset_still_usable(self): group = Group.objects.create(name="group") Event.objects.create(title="event", group=group) groups = Group.objects.annotate( has_event=models.Exists( Event.objects.filter(group_id=models.OuterRef("id")), ), ) groups2 = pickle.loads(pickle.dumps(groups)) self.assertSequenceEqual(groups2.filter(has_event=True), [group]) def test_pickle_exists_queryset_not_evaluated(self): group = Group.objects.create(name="group") Event.objects.create(title="event", group=group) groups = Group.objects.annotate( has_event=models.Exists( Event.objects.filter(group_id=models.OuterRef("id")), ), ) list(groups) # evaluate QuerySet. with self.assertNumQueries(0): self.assert_pickles(groups) def test_pickle_exists_kwargs_queryset_not_evaluated(self): group = Group.objects.create(name="group") Event.objects.create(title="event", group=group) groups = Group.objects.annotate( has_event=models.Exists( queryset=Event.objects.filter(group_id=models.OuterRef("id")), ), ) list(groups) # evaluate QuerySet. with self.assertNumQueries(0): self.assert_pickles(groups) def test_pickle_subquery_queryset_not_evaluated(self): group = Group.objects.create(name="group") Event.objects.create(title="event", group=group) groups = Group.objects.annotate( event_title=models.Subquery( Event.objects.filter(group_id=models.OuterRef("id")).values("title"), ), ) list(groups) # evaluate QuerySet. with self.assertNumQueries(0): self.assert_pickles(groups) def test_pickle_filteredrelation(self): group = Group.objects.create(name="group") event_1 = Event.objects.create(title="Big event", group=group) event_2 = Event.objects.create(title="Small event", group=group) Happening.objects.bulk_create( [ Happening(event=event_1, number1=5), Happening(event=event_2, number1=3), ] ) groups = Group.objects.annotate( big_events=models.FilteredRelation( "event", condition=models.Q(event__title__startswith="Big"), ), ).annotate(sum_number=models.Sum("big_events__happening__number1")) groups_query = pickle.loads(pickle.dumps(groups.query)) groups = Group.objects.all() groups.query = groups_query self.assertEqual(groups.get().sum_number, 5) def test_pickle_filteredrelation_m2m(self): group = Group.objects.create(name="group") m2mmodel = M2MModel.objects.create(added=datetime.date(2020, 1, 1)) m2mmodel.groups.add(group) groups = Group.objects.annotate( first_m2mmodels=models.FilteredRelation( "m2mmodel", condition=models.Q(m2mmodel__added__year=2020), ), ).annotate(count_groups=models.Count("first_m2mmodels__groups")) groups_query = pickle.loads(pickle.dumps(groups.query)) groups = Group.objects.all() groups.query = groups_query self.assertEqual(groups.get().count_groups, 1) def test_annotation_with_callable_default(self): # Happening.when has a callable default of datetime.datetime.now. qs = Happening.objects.annotate(latest_time=models.Max("when")) self.assert_pickles(qs) def test_annotation_values(self): qs = Happening.objects.values("name").annotate(latest_time=models.Max("when")) reloaded = Happening.objects.all() reloaded.query = pickle.loads(pickle.dumps(qs.query)) self.assertEqual( reloaded.get(), {"name": "test", "latest_time": self.happening.when}, ) def test_annotation_values_list(self): # values_list() is reloaded to values() when using a pickled query. tests = [ Happening.objects.values_list("name"), Happening.objects.values_list("name", flat=True), Happening.objects.values_list("name", named=True), ] for qs in tests: with self.subTest(qs._iterable_class.__name__): reloaded = Happening.objects.all() reloaded.query = pickle.loads(pickle.dumps(qs.query)) self.assertEqual(reloaded.get(), {"name": "test"}) def test_filter_deferred(self): qs = Happening.objects.all() qs._defer_next_filter = True qs = qs.filter(id=0) self.assert_pickles(qs) def test_missing_django_version_unpickling(self): """ #21430 -- Verifies a warning is raised for querysets that are unpickled without a Django version """ qs = Group.missing_django_version_objects.all() msg = "Pickled queryset instance's Django version is not specified." with self.assertRaisesMessage(RuntimeWarning, msg): pickle.loads(pickle.dumps(qs)) def test_unsupported_unpickle(self): """ #21430 -- Verifies a warning is raised for querysets that are unpickled with a different Django version than the current """ qs = Group.previous_django_version_objects.all() msg = ( "Pickled queryset instance's Django version 1.0 does not match " "the current version %s." % django.__version__ ) with self.assertRaisesMessage(RuntimeWarning, msg): pickle.loads(pickle.dumps(qs)) def test_order_by_model_with_abstract_inheritance_and_meta_ordering(self): group = Group.objects.create(name="test") event = MyEvent.objects.create(title="test event", group=group) event.edition_set.create() self.assert_pickles(event.edition_set.order_by("event")) def test_fetch_mode_fetch_one(self): restored = pickle.loads(pickle.dumps(self.happening)) self.assertIs(restored._state.fetch_mode, models.FETCH_ONE) def test_fetch_mode_fetch_peers(self): Happening.objects.create() objs = list(Happening.objects.fetch_mode(models.FETCH_PEERS)) self.assertEqual(objs[0]._state.fetch_mode, models.FETCH_PEERS) self.assertEqual(len(objs[0]._state.peers), 2) restored = pickle.loads(pickle.dumps(objs)) self.assertIs(restored[0]._state.fetch_mode, models.FETCH_PEERS) # Peers not restored because weak references are not picklable. self.assertEqual(restored[0]._state.peers, ()) def test_fetch_mode_raise(self): objs = list(Happening.objects.fetch_mode(models.RAISE)) self.assertEqual(objs[0]._state.fetch_mode, models.RAISE) restored = pickle.loads(pickle.dumps(objs)) self.assertIs(restored[0]._state.fetch_mode, models.RAISE) class InLookupTests(TestCase): @classmethod def setUpTestData(cls): for i in range(1, 3): group = Group.objects.create(name="Group {}".format(i)) cls.e1 = Event.objects.create(title="Event 1", group=group) def test_in_lookup_queryset_evaluation(self): """ Neither pickling nor unpickling a QuerySet.query with an __in=inner_qs lookup should evaluate inner_qs. """ events = Event.objects.filter(group__in=Group.objects.all()) with self.assertNumQueries(0): dumped = pickle.dumps(events.query) with self.assertNumQueries(0): reloaded = pickle.loads(dumped) reloaded_events = Event.objects.none() reloaded_events.query = reloaded self.assertSequenceEqual(reloaded_events, [self.e1]) def test_in_lookup_query_evaluation(self): events = Event.objects.filter(group__in=Group.objects.values("id").query) with self.assertNumQueries(0): dumped = pickle.dumps(events.query) with self.assertNumQueries(0): reloaded = pickle.loads(dumped) reloaded_events = Event.objects.none() reloaded_events.query = reloaded self.assertSequenceEqual(reloaded_events, [self.e1])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/max_lengths/models.py
tests/max_lengths/models.py
from django.db import models class PersonWithDefaultMaxLengths(models.Model): email = models.EmailField() vcard = models.FileField() homepage = models.URLField() avatar = models.FilePathField() class PersonWithCustomMaxLengths(models.Model): email = models.EmailField(max_length=250) vcard = models.FileField(max_length=250) homepage = models.URLField(max_length=250) avatar = models.FilePathField(max_length=250)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/max_lengths/__init__.py
tests/max_lengths/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/max_lengths/tests.py
tests/max_lengths/tests.py
import unittest from django.test import TestCase from .models import PersonWithCustomMaxLengths, PersonWithDefaultMaxLengths class MaxLengthArgumentsTests(unittest.TestCase): def verify_max_length(self, model, field, length): self.assertEqual(model._meta.get_field(field).max_length, length) def test_default_max_lengths(self): self.verify_max_length(PersonWithDefaultMaxLengths, "email", 254) self.verify_max_length(PersonWithDefaultMaxLengths, "vcard", 100) self.verify_max_length(PersonWithDefaultMaxLengths, "homepage", 200) self.verify_max_length(PersonWithDefaultMaxLengths, "avatar", 100) def test_custom_max_lengths(self): self.verify_max_length(PersonWithCustomMaxLengths, "email", 250) self.verify_max_length(PersonWithCustomMaxLengths, "vcard", 250) self.verify_max_length(PersonWithCustomMaxLengths, "homepage", 250) self.verify_max_length(PersonWithCustomMaxLengths, "avatar", 250) class MaxLengthORMTests(TestCase): def test_custom_max_lengths(self): args = { "email": "someone@example.com", "vcard": "vcard", "homepage": "http://example.com/", "avatar": "me.jpg", } for field in ("email", "vcard", "homepage", "avatar"): new_args = args.copy() new_args[field] = ( "X" * 250 ) # a value longer than any of the default fields could hold. p = PersonWithCustomMaxLengths.objects.create(**new_args) self.assertEqual(getattr(p, field), ("X" * 250))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/conditional_processing/views.py
tests/conditional_processing/views.py
from django.http import HttpResponse from django.views.decorators.http import condition, etag, last_modified from .tests import ETAG, FULL_RESPONSE, LAST_MODIFIED, WEAK_ETAG @condition(lambda r: ETAG, lambda r: LAST_MODIFIED) def index(request): return HttpResponse(FULL_RESPONSE) @condition(last_modified_func=lambda r: LAST_MODIFIED) def last_modified_view1(request): return HttpResponse(FULL_RESPONSE) @last_modified(lambda r: LAST_MODIFIED) def last_modified_view2(request): return HttpResponse(FULL_RESPONSE) @condition(etag_func=lambda r: ETAG) def etag_view1(request): return HttpResponse(FULL_RESPONSE) @etag(lambda r: ETAG) def etag_view2(request): return HttpResponse(FULL_RESPONSE) @condition(etag_func=lambda r: ETAG.strip('"')) def etag_view_unquoted(request): """ Use an etag_func() that returns an unquoted ETag. """ return HttpResponse(FULL_RESPONSE) @condition(etag_func=lambda r: WEAK_ETAG) def etag_view_weak(request): """ Use an etag_func() that returns a weak ETag. """ return HttpResponse(FULL_RESPONSE) @condition(etag_func=lambda r: None) def etag_view_none(request): """ Use an etag_func() that returns None, as opposed to setting etag_func=None. """ return HttpResponse(FULL_RESPONSE)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/conditional_processing/__init__.py
tests/conditional_processing/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/conditional_processing/tests.py
tests/conditional_processing/tests.py
from datetime import datetime from django.test import SimpleTestCase, override_settings FULL_RESPONSE = "Test conditional get response" LAST_MODIFIED = datetime(2007, 10, 21, 23, 21, 47) LAST_MODIFIED_STR = "Sun, 21 Oct 2007 23:21:47 GMT" LAST_MODIFIED_NEWER_STR = "Mon, 18 Oct 2010 16:56:23 GMT" LAST_MODIFIED_INVALID_STR = "Mon, 32 Oct 2010 16:56:23 GMT" EXPIRED_LAST_MODIFIED_STR = "Sat, 20 Oct 2007 23:21:47 GMT" ETAG = '"b4246ffc4f62314ca13147c9d4f76974"' WEAK_ETAG = 'W/"b4246ffc4f62314ca13147c9d4f76974"' # weak match to ETAG EXPIRED_ETAG = '"7fae4cd4b0f81e7d2914700043aa8ed6"' @override_settings(ROOT_URLCONF="conditional_processing.urls") class ConditionalGet(SimpleTestCase): def assertFullResponse(self, response, check_last_modified=True, check_etag=True): self.assertEqual(response.status_code, 200) self.assertEqual(response.content, FULL_RESPONSE.encode()) if response.request["REQUEST_METHOD"] in ("GET", "HEAD"): if check_last_modified: self.assertEqual(response.headers["Last-Modified"], LAST_MODIFIED_STR) if check_etag: self.assertEqual(response.headers["ETag"], ETAG) else: self.assertNotIn("Last-Modified", response.headers) self.assertNotIn("ETag", response.headers) def assertNotModified(self, response): self.assertEqual(response.status_code, 304) self.assertEqual(response.content, b"") def test_without_conditions(self): response = self.client.get("/condition/") self.assertFullResponse(response) def test_if_modified_since(self): self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = LAST_MODIFIED_STR response = self.client.get("/condition/") self.assertNotModified(response) response = self.client.put("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = LAST_MODIFIED_NEWER_STR response = self.client.get("/condition/") self.assertNotModified(response) response = self.client.put("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = LAST_MODIFIED_INVALID_STR response = self.client.get("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR response = self.client.get("/condition/") self.assertFullResponse(response) def test_if_unmodified_since(self): self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = LAST_MODIFIED_STR response = self.client.get("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = LAST_MODIFIED_NEWER_STR response = self.client.get("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = LAST_MODIFIED_INVALID_STR response = self.client.get("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR response = self.client.get("/condition/") self.assertEqual(response.status_code, 412) def test_if_none_match(self): self.client.defaults["HTTP_IF_NONE_MATCH"] = ETAG response = self.client.get("/condition/") self.assertNotModified(response) response = self.client.put("/condition/") self.assertEqual(response.status_code, 412) self.client.defaults["HTTP_IF_NONE_MATCH"] = EXPIRED_ETAG response = self.client.get("/condition/") self.assertFullResponse(response) # Several etags in If-None-Match is a bit exotic but why not? self.client.defaults["HTTP_IF_NONE_MATCH"] = "%s, %s" % (ETAG, EXPIRED_ETAG) response = self.client.get("/condition/") self.assertNotModified(response) def test_weak_if_none_match(self): """ If-None-Match comparisons use weak matching, so weak and strong ETags with the same value result in a 304 response. """ self.client.defaults["HTTP_IF_NONE_MATCH"] = ETAG response = self.client.get("/condition/weak_etag/") self.assertNotModified(response) response = self.client.put("/condition/weak_etag/") self.assertEqual(response.status_code, 412) self.client.defaults["HTTP_IF_NONE_MATCH"] = WEAK_ETAG response = self.client.get("/condition/weak_etag/") self.assertNotModified(response) response = self.client.put("/condition/weak_etag/") self.assertEqual(response.status_code, 412) response = self.client.get("/condition/") self.assertNotModified(response) response = self.client.put("/condition/") self.assertEqual(response.status_code, 412) def test_all_if_none_match(self): self.client.defaults["HTTP_IF_NONE_MATCH"] = "*" response = self.client.get("/condition/") self.assertNotModified(response) response = self.client.put("/condition/") self.assertEqual(response.status_code, 412) response = self.client.get("/condition/no_etag/") self.assertFullResponse(response, check_last_modified=False, check_etag=False) def test_if_match(self): self.client.defaults["HTTP_IF_MATCH"] = ETAG response = self.client.put("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_MATCH"] = EXPIRED_ETAG response = self.client.put("/condition/") self.assertEqual(response.status_code, 412) def test_weak_if_match(self): """ If-Match comparisons use strong matching, so any comparison involving a weak ETag return a 412 response. """ self.client.defaults["HTTP_IF_MATCH"] = ETAG response = self.client.get("/condition/weak_etag/") self.assertEqual(response.status_code, 412) self.client.defaults["HTTP_IF_MATCH"] = WEAK_ETAG response = self.client.get("/condition/weak_etag/") self.assertEqual(response.status_code, 412) response = self.client.get("/condition/") self.assertEqual(response.status_code, 412) def test_all_if_match(self): self.client.defaults["HTTP_IF_MATCH"] = "*" response = self.client.get("/condition/") self.assertFullResponse(response) response = self.client.get("/condition/no_etag/") self.assertEqual(response.status_code, 412) def test_both_headers(self): # See RFC 9110 Section 13.2.2. self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = LAST_MODIFIED_STR self.client.defaults["HTTP_IF_NONE_MATCH"] = ETAG response = self.client.get("/condition/") self.assertNotModified(response) self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR self.client.defaults["HTTP_IF_NONE_MATCH"] = ETAG response = self.client.get("/condition/") self.assertNotModified(response) self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = LAST_MODIFIED_STR self.client.defaults["HTTP_IF_NONE_MATCH"] = EXPIRED_ETAG response = self.client.get("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR self.client.defaults["HTTP_IF_NONE_MATCH"] = EXPIRED_ETAG response = self.client.get("/condition/") self.assertFullResponse(response) def test_both_headers_2(self): self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = LAST_MODIFIED_STR self.client.defaults["HTTP_IF_MATCH"] = ETAG response = self.client.get("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR self.client.defaults["HTTP_IF_MATCH"] = ETAG response = self.client.get("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR self.client.defaults["HTTP_IF_MATCH"] = EXPIRED_ETAG response = self.client.get("/condition/") self.assertEqual(response.status_code, 412) self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = LAST_MODIFIED_STR self.client.defaults["HTTP_IF_MATCH"] = EXPIRED_ETAG response = self.client.get("/condition/") self.assertEqual(response.status_code, 412) def test_single_condition_1(self): self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = LAST_MODIFIED_STR response = self.client.get("/condition/last_modified/") self.assertNotModified(response) response = self.client.get("/condition/etag/") self.assertFullResponse(response, check_last_modified=False) def test_single_condition_2(self): self.client.defaults["HTTP_IF_NONE_MATCH"] = ETAG response = self.client.get("/condition/etag/") self.assertNotModified(response) response = self.client.get("/condition/last_modified/") self.assertFullResponse(response, check_etag=False) def test_single_condition_3(self): self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR response = self.client.get("/condition/last_modified/") self.assertFullResponse(response, check_etag=False) def test_single_condition_4(self): self.client.defaults["HTTP_IF_NONE_MATCH"] = EXPIRED_ETAG response = self.client.get("/condition/etag/") self.assertFullResponse(response, check_last_modified=False) def test_single_condition_5(self): self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = LAST_MODIFIED_STR response = self.client.get("/condition/last_modified2/") self.assertNotModified(response) response = self.client.get("/condition/etag2/") self.assertFullResponse(response, check_last_modified=False) def test_single_condition_6(self): self.client.defaults["HTTP_IF_NONE_MATCH"] = ETAG response = self.client.get("/condition/etag2/") self.assertNotModified(response) response = self.client.get("/condition/last_modified2/") self.assertFullResponse(response, check_etag=False) def test_single_condition_7(self): self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR response = self.client.get("/condition/last_modified/") self.assertEqual(response.status_code, 412) response = self.client.get("/condition/etag/") self.assertEqual(response.status_code, 412) def test_single_condition_8(self): self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = LAST_MODIFIED_STR response = self.client.get("/condition/last_modified/") self.assertFullResponse(response, check_etag=False) def test_single_condition_9(self): self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR response = self.client.get("/condition/last_modified2/") self.assertEqual(response.status_code, 412) response = self.client.get("/condition/etag2/") self.assertEqual(response.status_code, 412) def test_single_condition_head(self): self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = LAST_MODIFIED_STR response = self.client.head("/condition/") self.assertNotModified(response) def test_unquoted(self): """ The same quoted ETag should be set on the header regardless of whether etag_func() in condition() returns a quoted or an unquoted ETag. """ response_quoted = self.client.get("/condition/etag/") response_unquoted = self.client.get("/condition/unquoted_etag/") self.assertEqual(response_quoted["ETag"], response_unquoted["ETag"]) # It's possible that the matching algorithm could use the wrong value even # if the ETag header is set correctly correctly (as tested by # test_unquoted()), so check that the unquoted value is matched. def test_unquoted_if_none_match(self): self.client.defaults["HTTP_IF_NONE_MATCH"] = ETAG response = self.client.get("/condition/unquoted_etag/") self.assertNotModified(response) response = self.client.put("/condition/unquoted_etag/") self.assertEqual(response.status_code, 412) self.client.defaults["HTTP_IF_NONE_MATCH"] = EXPIRED_ETAG response = self.client.get("/condition/unquoted_etag/") self.assertFullResponse(response, check_last_modified=False) def test_invalid_etag(self): self.client.defaults["HTTP_IF_NONE_MATCH"] = '"""' response = self.client.get("/condition/etag/") self.assertFullResponse(response, check_last_modified=False)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/conditional_processing/urls.py
tests/conditional_processing/urls.py
from django.urls import path from . import views urlpatterns = [ path("condition/", views.index), path("condition/last_modified/", views.last_modified_view1), path("condition/last_modified2/", views.last_modified_view2), path("condition/etag/", views.etag_view1), path("condition/etag2/", views.etag_view2), path("condition/unquoted_etag/", views.etag_view_unquoted), path("condition/weak_etag/", views.etag_view_weak), path("condition/no_etag/", views.etag_view_none), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/custom_managers/models.py
tests/custom_managers/models.py
""" Giving models a custom manager You can use a custom ``Manager`` in a particular model by extending the base ``Manager`` class and instantiating your custom ``Manager`` in your model. There are two reasons you might want to customize a ``Manager``: to add extra ``Manager`` methods, and/or to modify the initial ``QuerySet`` the ``Manager`` returns. """ from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.db import models class PersonManager(models.Manager): def get_fun_people(self): return self.filter(fun=True) class PublishedBookManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_published=True) class AnnotatedBookManager(models.Manager): def get_queryset(self): return ( super() .get_queryset() .annotate(favorite_avg=models.Avg("favorite_books__favorite_thing_id")) ) class CustomQuerySet(models.QuerySet): def filter(self, *args, **kwargs): queryset = super().filter(fun=True) queryset._filter_CustomQuerySet = True return queryset def public_method(self, *args, **kwargs): return self.all() def _private_method(self, *args, **kwargs): return self.all() def optout_public_method(self, *args, **kwargs): return self.all() optout_public_method.queryset_only = True def _optin_private_method(self, *args, **kwargs): return self.all() _optin_private_method.queryset_only = False class BaseCustomManager(models.Manager): def __init__(self, arg): super().__init__() self.init_arg = arg def filter(self, *args, **kwargs): queryset = super().filter(fun=True) queryset._filter_CustomManager = True return queryset def manager_only(self): return self.all() CustomManager = BaseCustomManager.from_queryset(CustomQuerySet) class CustomInitQuerySet(models.QuerySet): # QuerySet with an __init__() method that takes an additional argument. def __init__( self, custom_optional_arg=None, model=None, query=None, using=None, hints=None ): super().__init__(model=model, query=query, using=using, hints=hints) class DeconstructibleCustomManager(BaseCustomManager.from_queryset(CustomQuerySet)): def __init__(self, a, b, c=1, d=2): super().__init__(a) class FunPeopleManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(fun=True) class BoringPeopleManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(fun=False) class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) fun = models.BooleanField(default=False) favorite_book = models.ForeignKey( "Book", models.SET_NULL, null=True, related_name="favorite_books" ) favorite_thing_type = models.ForeignKey( "contenttypes.ContentType", models.SET_NULL, null=True ) favorite_thing_id = models.IntegerField(null=True) favorite_thing = GenericForeignKey("favorite_thing_type", "favorite_thing_id") objects = PersonManager() fun_people = FunPeopleManager() boring_people = BoringPeopleManager() custom_queryset_default_manager = CustomQuerySet.as_manager() custom_queryset_custom_manager = CustomManager("hello") custom_init_queryset_manager = CustomInitQuerySet.as_manager() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class FunPerson(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) fun = models.BooleanField(default=True) favorite_book = models.ForeignKey( "Book", models.SET_NULL, null=True, related_name="fun_people_favorite_books", ) favorite_thing_type = models.ForeignKey( "contenttypes.ContentType", models.SET_NULL, null=True ) favorite_thing_id = models.IntegerField(null=True) favorite_thing = GenericForeignKey("favorite_thing_type", "favorite_thing_id") objects = FunPeopleManager() class Book(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=30) is_published = models.BooleanField(default=False) authors = models.ManyToManyField(Person, related_name="books") fun_authors = models.ManyToManyField(FunPerson, related_name="books") favorite_things = GenericRelation( Person, content_type_field="favorite_thing_type", object_id_field="favorite_thing_id", ) fun_people_favorite_things = GenericRelation( FunPerson, content_type_field="favorite_thing_type", object_id_field="favorite_thing_id", ) published_objects = PublishedBookManager() annotated_objects = AnnotatedBookManager() class Meta: base_manager_name = "annotated_objects" class FastCarManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(top_speed__gt=150) class Car(models.Model): name = models.CharField(max_length=10) mileage = models.IntegerField() top_speed = models.IntegerField(help_text="In miles per hour.") cars = models.Manager() fast_cars = FastCarManager() class FastCarAsBase(Car): class Meta: proxy = True base_manager_name = "fast_cars" class FastCarAsDefault(Car): class Meta: proxy = True default_manager_name = "fast_cars" class RestrictedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_public=True) class RelatedModel(models.Model): name = models.CharField(max_length=50) class RestrictedModel(models.Model): name = models.CharField(max_length=50) is_public = models.BooleanField(default=False) related = models.ForeignKey(RelatedModel, models.CASCADE) objects = RestrictedManager() plain_manager = models.Manager() class OneToOneRestrictedModel(models.Model): name = models.CharField(max_length=50) is_public = models.BooleanField(default=False) related = models.OneToOneField(RelatedModel, models.CASCADE) objects = RestrictedManager() plain_manager = models.Manager() class AbstractPerson(models.Model): abstract_persons = models.Manager() objects = models.CharField(max_length=30) class Meta: abstract = True class PersonFromAbstract(AbstractPerson): pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/custom_managers/__init__.py
tests/custom_managers/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/custom_managers/tests.py
tests/custom_managers/tests.py
from django.db import models from django.test import TestCase from .models import ( Book, Car, CustomManager, CustomQuerySet, DeconstructibleCustomManager, FastCarAsBase, FastCarAsDefault, FunPerson, OneToOneRestrictedModel, Person, PersonFromAbstract, PersonManager, PublishedBookManager, RelatedModel, RestrictedModel, ) class CustomManagerTests(TestCase): custom_manager_names = [ "custom_queryset_default_manager", "custom_queryset_custom_manager", ] @classmethod def setUpTestData(cls): cls.b1 = Book.published_objects.create( title="How to program", author="Rodney Dangerfield", is_published=True ) cls.b2 = Book.published_objects.create( title="How to be smart", author="Albert Einstein", is_published=False ) cls.p1 = Person.objects.create(first_name="Bugs", last_name="Bunny", fun=True) cls.droopy = Person.objects.create( first_name="Droopy", last_name="Dog", fun=False ) def test_custom_manager_basic(self): """ Test a custom Manager method. """ self.assertQuerySetEqual(Person.objects.get_fun_people(), ["Bugs Bunny"], str) def test_queryset_copied_to_default(self): """ The methods of a custom QuerySet are properly copied onto the default Manager. """ for manager_name in self.custom_manager_names: with self.subTest(manager_name=manager_name): manager = getattr(Person, manager_name) # Public methods are copied manager.public_method() # Private methods are not copied with self.assertRaises(AttributeError): manager._private_method() def test_manager_honors_queryset_only(self): for manager_name in self.custom_manager_names: with self.subTest(manager_name=manager_name): manager = getattr(Person, manager_name) # Methods with queryset_only=False are copied even if they are # private. manager._optin_private_method() # Methods with queryset_only=True aren't copied even if they # are public. msg = ( "%r object has no attribute 'optout_public_method'" % manager.__class__.__name__ ) with self.assertRaisesMessage(AttributeError, msg): manager.optout_public_method() def test_manager_use_queryset_methods(self): """ Custom manager will use the queryset methods """ for manager_name in self.custom_manager_names: with self.subTest(manager_name=manager_name): manager = getattr(Person, manager_name) queryset = manager.filter() self.assertQuerySetEqual(queryset, ["Bugs Bunny"], str) self.assertIs(queryset._filter_CustomQuerySet, True) # Specialized querysets inherit from our custom queryset. queryset = manager.values_list("first_name", flat=True).filter() self.assertEqual(list(queryset), ["Bugs"]) self.assertIs(queryset._filter_CustomQuerySet, True) self.assertIsInstance(queryset.values(), CustomQuerySet) self.assertIsInstance(queryset.values().values(), CustomQuerySet) self.assertIsInstance(queryset.values_list().values(), CustomQuerySet) def test_init_args(self): """ The custom manager __init__() argument has been set. """ self.assertEqual(Person.custom_queryset_custom_manager.init_arg, "hello") def test_manager_attributes(self): """ Custom manager method is only available on the manager and not on querysets. """ Person.custom_queryset_custom_manager.manager_only() msg = "'CustomQuerySet' object has no attribute 'manager_only'" with self.assertRaisesMessage(AttributeError, msg): Person.custom_queryset_custom_manager.all().manager_only() def test_queryset_and_manager(self): """ Queryset method doesn't override the custom manager method. """ queryset = Person.custom_queryset_custom_manager.filter() self.assertQuerySetEqual(queryset, ["Bugs Bunny"], str) self.assertIs(queryset._filter_CustomManager, True) def test_related_manager(self): """ The related managers extend the default manager. """ self.assertIsInstance(self.droopy.books, PublishedBookManager) self.assertIsInstance(self.b2.authors, PersonManager) def test_no_objects(self): """ The default manager, "objects", doesn't exist, because a custom one was provided. """ msg = "type object 'Book' has no attribute 'objects'" with self.assertRaisesMessage(AttributeError, msg): Book.objects def test_filtering(self): """ Custom managers respond to usual filtering methods """ self.assertQuerySetEqual( Book.published_objects.all(), [ "How to program", ], lambda b: b.title, ) def test_fk_related_manager(self): Person.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_book=self.b1 ) Person.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_book=self.b1 ) FunPerson.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_book=self.b1 ) FunPerson.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_book=self.b1 ) self.assertQuerySetEqual( self.b1.favorite_books.order_by("first_name").all(), [ "Bugs", "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerySetEqual( self.b1.fun_people_favorite_books.all(), [ "Bugs", ], lambda c: c.first_name, ordered=False, ) self.assertQuerySetEqual( self.b1.favorite_books(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerySetEqual( self.b1.favorite_books(manager="fun_people").all(), [ "Bugs", ], lambda c: c.first_name, ordered=False, ) def test_gfk_related_manager(self): Person.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_thing=self.b1 ) Person.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_thing=self.b1 ) FunPerson.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_thing=self.b1 ) FunPerson.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_thing=self.b1 ) self.assertQuerySetEqual( self.b1.favorite_things.all(), [ "Bugs", "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerySetEqual( self.b1.fun_people_favorite_things.all(), [ "Bugs", ], lambda c: c.first_name, ordered=False, ) self.assertQuerySetEqual( self.b1.favorite_things(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerySetEqual( self.b1.favorite_things(manager="fun_people").all(), [ "Bugs", ], lambda c: c.first_name, ordered=False, ) def test_m2m_related_manager(self): bugs = Person.objects.create(first_name="Bugs", last_name="Bunny", fun=True) self.b1.authors.add(bugs) droopy = Person.objects.create(first_name="Droopy", last_name="Dog", fun=False) self.b1.authors.add(droopy) bugs = FunPerson.objects.create(first_name="Bugs", last_name="Bunny", fun=True) self.b1.fun_authors.add(bugs) droopy = FunPerson.objects.create( first_name="Droopy", last_name="Dog", fun=False ) self.b1.fun_authors.add(droopy) self.assertQuerySetEqual( self.b1.authors.order_by("first_name").all(), [ "Bugs", "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerySetEqual( self.b1.fun_authors.order_by("first_name").all(), [ "Bugs", ], lambda c: c.first_name, ordered=False, ) self.assertQuerySetEqual( self.b1.authors(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerySetEqual( self.b1.authors(manager="fun_people").all(), [ "Bugs", ], lambda c: c.first_name, ordered=False, ) def test_removal_through_default_fk_related_manager(self, bulk=True): bugs = FunPerson.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_book=self.b1 ) droopy = FunPerson.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_book=self.b1 ) self.b1.fun_people_favorite_books.remove(droopy, bulk=bulk) self.assertQuerySetEqual( FunPerson._base_manager.filter(favorite_book=self.b1), [ "Bugs", "Droopy", ], lambda c: c.first_name, ordered=False, ) self.b1.fun_people_favorite_books.remove(bugs, bulk=bulk) self.assertQuerySetEqual( FunPerson._base_manager.filter(favorite_book=self.b1), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) bugs.favorite_book = self.b1 bugs.save() self.b1.fun_people_favorite_books.clear(bulk=bulk) self.assertQuerySetEqual( FunPerson._base_manager.filter(favorite_book=self.b1), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) def test_slow_removal_through_default_fk_related_manager(self): self.test_removal_through_default_fk_related_manager(bulk=False) def test_removal_through_specified_fk_related_manager(self, bulk=True): Person.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_book=self.b1 ) droopy = Person.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_book=self.b1 ) # The fun manager DOESN'T remove boring people. self.b1.favorite_books(manager="fun_people").remove(droopy, bulk=bulk) self.assertQuerySetEqual( self.b1.favorite_books(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) # The boring manager DOES remove boring people. self.b1.favorite_books(manager="boring_people").remove(droopy, bulk=bulk) self.assertQuerySetEqual( self.b1.favorite_books(manager="boring_people").all(), [], lambda c: c.first_name, ordered=False, ) droopy.favorite_book = self.b1 droopy.save() # The fun manager ONLY clears fun people. self.b1.favorite_books(manager="fun_people").clear(bulk=bulk) self.assertQuerySetEqual( self.b1.favorite_books(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerySetEqual( self.b1.favorite_books(manager="fun_people").all(), [], lambda c: c.first_name, ordered=False, ) def test_slow_removal_through_specified_fk_related_manager(self): self.test_removal_through_specified_fk_related_manager(bulk=False) def test_removal_through_default_gfk_related_manager(self, bulk=True): bugs = FunPerson.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_thing=self.b1 ) droopy = FunPerson.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_thing=self.b1 ) self.b1.fun_people_favorite_things.remove(droopy, bulk=bulk) self.assertQuerySetEqual( FunPerson._base_manager.order_by("first_name").filter( favorite_thing_id=self.b1.pk ), [ "Bugs", "Droopy", ], lambda c: c.first_name, ordered=False, ) self.b1.fun_people_favorite_things.remove(bugs, bulk=bulk) self.assertQuerySetEqual( FunPerson._base_manager.order_by("first_name").filter( favorite_thing_id=self.b1.pk ), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) bugs.favorite_book = self.b1 bugs.save() self.b1.fun_people_favorite_things.clear(bulk=bulk) self.assertQuerySetEqual( FunPerson._base_manager.order_by("first_name").filter( favorite_thing_id=self.b1.pk ), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) def test_slow_removal_through_default_gfk_related_manager(self): self.test_removal_through_default_gfk_related_manager(bulk=False) def test_removal_through_specified_gfk_related_manager(self, bulk=True): Person.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_thing=self.b1 ) droopy = Person.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_thing=self.b1 ) # The fun manager DOESN'T remove boring people. self.b1.favorite_things(manager="fun_people").remove(droopy, bulk=bulk) self.assertQuerySetEqual( self.b1.favorite_things(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) # The boring manager DOES remove boring people. self.b1.favorite_things(manager="boring_people").remove(droopy, bulk=bulk) self.assertQuerySetEqual( self.b1.favorite_things(manager="boring_people").all(), [], lambda c: c.first_name, ordered=False, ) droopy.favorite_thing = self.b1 droopy.save() # The fun manager ONLY clears fun people. self.b1.favorite_things(manager="fun_people").clear(bulk=bulk) self.assertQuerySetEqual( self.b1.favorite_things(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerySetEqual( self.b1.favorite_things(manager="fun_people").all(), [], lambda c: c.first_name, ordered=False, ) def test_slow_removal_through_specified_gfk_related_manager(self): self.test_removal_through_specified_gfk_related_manager(bulk=False) def test_removal_through_default_m2m_related_manager(self): bugs = FunPerson.objects.create(first_name="Bugs", last_name="Bunny", fun=True) self.b1.fun_authors.add(bugs) droopy = FunPerson.objects.create( first_name="Droopy", last_name="Dog", fun=False ) self.b1.fun_authors.add(droopy) self.b1.fun_authors.remove(droopy) self.assertQuerySetEqual( self.b1.fun_authors.through._default_manager.all(), [ "Bugs", "Droopy", ], lambda c: c.funperson.first_name, ordered=False, ) self.b1.fun_authors.remove(bugs) self.assertQuerySetEqual( self.b1.fun_authors.through._default_manager.all(), [ "Droopy", ], lambda c: c.funperson.first_name, ordered=False, ) self.b1.fun_authors.add(bugs) self.b1.fun_authors.clear() self.assertQuerySetEqual( self.b1.fun_authors.through._default_manager.all(), [ "Droopy", ], lambda c: c.funperson.first_name, ordered=False, ) def test_removal_through_specified_m2m_related_manager(self): bugs = Person.objects.create(first_name="Bugs", last_name="Bunny", fun=True) self.b1.authors.add(bugs) droopy = Person.objects.create(first_name="Droopy", last_name="Dog", fun=False) self.b1.authors.add(droopy) # The fun manager DOESN'T remove boring people. self.b1.authors(manager="fun_people").remove(droopy) self.assertQuerySetEqual( self.b1.authors(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) # The boring manager DOES remove boring people. self.b1.authors(manager="boring_people").remove(droopy) self.assertQuerySetEqual( self.b1.authors(manager="boring_people").all(), [], lambda c: c.first_name, ordered=False, ) self.b1.authors.add(droopy) # The fun manager ONLY clears fun people. self.b1.authors(manager="fun_people").clear() self.assertQuerySetEqual( self.b1.authors(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerySetEqual( self.b1.authors(manager="fun_people").all(), [], lambda c: c.first_name, ordered=False, ) def test_deconstruct_default(self): mgr = models.Manager() as_manager, mgr_path, qs_path, args, kwargs = mgr.deconstruct() self.assertFalse(as_manager) self.assertEqual(mgr_path, "django.db.models.manager.Manager") self.assertEqual(args, ()) self.assertEqual(kwargs, {}) def test_deconstruct_as_manager(self): mgr = CustomQuerySet.as_manager() as_manager, mgr_path, qs_path, args, kwargs = mgr.deconstruct() self.assertTrue(as_manager) self.assertEqual(qs_path, "custom_managers.models.CustomQuerySet") def test_deconstruct_from_queryset(self): mgr = DeconstructibleCustomManager("a", "b") as_manager, mgr_path, qs_path, args, kwargs = mgr.deconstruct() self.assertFalse(as_manager) self.assertEqual( mgr_path, "custom_managers.models.DeconstructibleCustomManager" ) self.assertEqual( args, ( "a", "b", ), ) self.assertEqual(kwargs, {}) mgr = DeconstructibleCustomManager("x", "y", c=3, d=4) as_manager, mgr_path, qs_path, args, kwargs = mgr.deconstruct() self.assertFalse(as_manager) self.assertEqual( mgr_path, "custom_managers.models.DeconstructibleCustomManager" ) self.assertEqual( args, ( "x", "y", ), ) self.assertEqual(kwargs, {"c": 3, "d": 4}) def test_deconstruct_from_queryset_failing(self): mgr = CustomManager("arg") msg = ( "Could not find manager BaseCustomManagerFromCustomQuerySet in " "django.db.models.manager.\n" "Please note that you need to inherit from managers you " "dynamically generated with 'from_queryset()'." ) with self.assertRaisesMessage(ValueError, msg): mgr.deconstruct() def test_abstract_model_with_custom_manager_name(self): """ A custom manager may be defined on an abstract model. It will be inherited by the abstract model's children. """ PersonFromAbstract.abstract_persons.create(objects="Test") self.assertQuerySetEqual( PersonFromAbstract.abstract_persons.all(), ["Test"], lambda c: c.objects, ) class TestCars(TestCase): def test_managers(self): # Each model class gets a "_default_manager" attribute, which is a # reference to the first manager defined in the class. Car.cars.create(name="Corvette", mileage=21, top_speed=180) Car.cars.create(name="Neon", mileage=31, top_speed=100) self.assertQuerySetEqual( Car._default_manager.order_by("name"), [ "Corvette", "Neon", ], lambda c: c.name, ) self.assertQuerySetEqual( Car.cars.order_by("name"), [ "Corvette", "Neon", ], lambda c: c.name, ) # alternate manager self.assertQuerySetEqual( Car.fast_cars.all(), [ "Corvette", ], lambda c: c.name, ) # explicit default manager self.assertQuerySetEqual( FastCarAsDefault.cars.order_by("name"), [ "Corvette", "Neon", ], lambda c: c.name, ) self.assertQuerySetEqual( FastCarAsDefault._default_manager.all(), [ "Corvette", ], lambda c: c.name, ) # explicit base manager self.assertQuerySetEqual( FastCarAsBase.cars.order_by("name"), [ "Corvette", "Neon", ], lambda c: c.name, ) self.assertQuerySetEqual( FastCarAsBase._base_manager.all(), [ "Corvette", ], lambda c: c.name, ) class CustomManagersRegressTestCase(TestCase): def test_filtered_default_manager(self): """Even though the default manager filters out some records, we must still be able to save (particularly, save by updating existing records) those filtered instances. This is a regression test for #8990, #9527""" related = RelatedModel.objects.create(name="xyzzy") obj = RestrictedModel.objects.create(name="hidden", related=related) obj.name = "still hidden" obj.save() # If the hidden object wasn't seen during the save process, # there would now be two objects in the database. self.assertEqual(RestrictedModel.plain_manager.count(), 1) def test_refresh_from_db_when_default_manager_filters(self): """ Model.refresh_from_db() works for instances hidden by the default manager. """ book = Book._base_manager.create(is_published=False) Book._base_manager.filter(pk=book.pk).update(title="Hi") book.refresh_from_db() self.assertEqual(book.title, "Hi") def test_save_clears_annotations_from_base_manager(self): """Model.save() clears annotations from the base manager.""" self.assertEqual(Book._meta.base_manager.name, "annotated_objects") book = Book.annotated_objects.create(title="Hunting") Person.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_book=book, favorite_thing_id=1, ) book = Book.annotated_objects.first() self.assertEqual(book.favorite_avg, 1) # Annotation from the manager. book.title = "New Hunting" # save() fails if annotations that involve related fields aren't # cleared before the update query. book.save() self.assertEqual(Book.annotated_objects.first().title, "New Hunting") def test_delete_related_on_filtered_manager(self): """Deleting related objects should also not be distracted by a restricted manager on the related object. This is a regression test for #2698.""" related = RelatedModel.objects.create(name="xyzzy") for name, public in (("one", True), ("two", False), ("three", False)): RestrictedModel.objects.create(name=name, is_public=public, related=related) obj = RelatedModel.objects.get(name="xyzzy") obj.delete() # All of the RestrictedModel instances should have been # deleted, since they *all* pointed to the RelatedModel. If # the default manager is used, only the public one will be # deleted. self.assertEqual(len(RestrictedModel.plain_manager.all()), 0) def test_delete_one_to_one_manager(self): # The same test case as the last one, but for one-to-one # models, which are implemented slightly different internally, # so it's a different code path. obj = RelatedModel.objects.create(name="xyzzy") OneToOneRestrictedModel.objects.create(name="foo", is_public=False, related=obj) obj = RelatedModel.objects.get(name="xyzzy") obj.delete() self.assertEqual(len(OneToOneRestrictedModel.plain_manager.all()), 0) def test_queryset_with_custom_init(self): """ BaseManager.get_queryset() should use kwargs rather than args to allow custom kwargs (#24911). """ qs_custom = Person.custom_init_queryset_manager.all() qs_default = Person.objects.all() self.assertQuerySetEqual(qs_custom, qs_default)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/nested_foreign_keys/models.py
tests/nested_foreign_keys/models.py
from django.db import models class Person(models.Model): name = models.CharField(max_length=200) class Movie(models.Model): title = models.CharField(max_length=200) director = models.ForeignKey(Person, models.CASCADE) class Event(models.Model): pass class Screening(Event): movie = models.ForeignKey(Movie, models.CASCADE) class ScreeningNullFK(Event): movie = models.ForeignKey(Movie, models.SET_NULL, null=True) class Package(models.Model): screening = models.ForeignKey(Screening, models.SET_NULL, null=True) class PackageNullFK(models.Model): screening = models.ForeignKey(ScreeningNullFK, models.SET_NULL, null=True)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/nested_foreign_keys/__init__.py
tests/nested_foreign_keys/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/nested_foreign_keys/tests.py
tests/nested_foreign_keys/tests.py
from django.test import TestCase from .models import ( Event, Movie, Package, PackageNullFK, Person, Screening, ScreeningNullFK, ) # These are tests for #16715. The basic scheme is always the same: 3 models # with 2 relations. The first relation may be null, while the second is # non-nullable. In some cases, Django would pick the wrong join type for the # second relation, resulting in missing objects in the queryset. # # Model A # | (Relation A/B : nullable) # Model B # | (Relation B/C : non-nullable) # Model C # # Because of the possibility of NULL rows resulting from the LEFT OUTER JOIN # between Model A and Model B (i.e. instances of A without reference to B), # the second join must also be LEFT OUTER JOIN, so that we do not ignore # instances of A that do not reference B. # # Relation A/B can either be an explicit foreign key or an implicit reverse # relation such as introduced by one-to-one relations (through multi-table # inheritance). class NestedForeignKeysTests(TestCase): @classmethod def setUpTestData(cls): cls.director = Person.objects.create(name="Terry Gilliam / Terry Jones") cls.movie = Movie.objects.create( title="Monty Python and the Holy Grail", director=cls.director ) # This test failed in #16715 because in some cases INNER JOIN was selected # for the second foreign key relation instead of LEFT OUTER JOIN. def test_inheritance(self): Event.objects.create() Screening.objects.create(movie=self.movie) self.assertEqual(len(Event.objects.all()), 2) self.assertEqual(len(Event.objects.select_related("screening")), 2) # This failed. self.assertEqual(len(Event.objects.select_related("screening__movie")), 2) self.assertEqual(len(Event.objects.values()), 2) self.assertEqual(len(Event.objects.values("screening__pk")), 2) self.assertEqual(len(Event.objects.values("screening__movie__pk")), 2) self.assertEqual(len(Event.objects.values("screening__movie__title")), 2) # This failed. self.assertEqual( len( Event.objects.values("screening__movie__pk", "screening__movie__title") ), 2, ) # Simple filter/exclude queries for good measure. self.assertEqual(Event.objects.filter(screening__movie=self.movie).count(), 1) self.assertEqual(Event.objects.exclude(screening__movie=self.movie).count(), 1) # These all work because the second foreign key in the chain has null=True. def test_inheritance_null_FK(self): Event.objects.create() ScreeningNullFK.objects.create(movie=None) ScreeningNullFK.objects.create(movie=self.movie) self.assertEqual(len(Event.objects.all()), 3) self.assertEqual(len(Event.objects.select_related("screeningnullfk")), 3) self.assertEqual(len(Event.objects.select_related("screeningnullfk__movie")), 3) self.assertEqual(len(Event.objects.values()), 3) self.assertEqual(len(Event.objects.values("screeningnullfk__pk")), 3) self.assertEqual(len(Event.objects.values("screeningnullfk__movie__pk")), 3) self.assertEqual(len(Event.objects.values("screeningnullfk__movie__title")), 3) self.assertEqual( len( Event.objects.values( "screeningnullfk__movie__pk", "screeningnullfk__movie__title" ) ), 3, ) self.assertEqual( Event.objects.filter(screeningnullfk__movie=self.movie).count(), 1 ) self.assertEqual( Event.objects.exclude(screeningnullfk__movie=self.movie).count(), 2 ) def test_null_exclude(self): screening = ScreeningNullFK.objects.create(movie=None) ScreeningNullFK.objects.create(movie=self.movie) self.assertEqual( list(ScreeningNullFK.objects.exclude(movie__id=self.movie.pk)), [screening] ) # This test failed in #16715 because in some cases INNER JOIN was selected # for the second foreign key relation instead of LEFT OUTER JOIN. def test_explicit_ForeignKey(self): Package.objects.create() screening = Screening.objects.create(movie=self.movie) Package.objects.create(screening=screening) self.assertEqual(len(Package.objects.all()), 2) self.assertEqual(len(Package.objects.select_related("screening")), 2) self.assertEqual(len(Package.objects.select_related("screening__movie")), 2) self.assertEqual(len(Package.objects.values()), 2) self.assertEqual(len(Package.objects.values("screening__pk")), 2) self.assertEqual(len(Package.objects.values("screening__movie__pk")), 2) self.assertEqual(len(Package.objects.values("screening__movie__title")), 2) # This failed. self.assertEqual( len( Package.objects.values( "screening__movie__pk", "screening__movie__title" ) ), 2, ) self.assertEqual(Package.objects.filter(screening__movie=self.movie).count(), 1) self.assertEqual( Package.objects.exclude(screening__movie=self.movie).count(), 1 ) # These all work because the second foreign key in the chain has null=True. def test_explicit_ForeignKey_NullFK(self): PackageNullFK.objects.create() screening = ScreeningNullFK.objects.create(movie=None) screening_with_movie = ScreeningNullFK.objects.create(movie=self.movie) PackageNullFK.objects.create(screening=screening) PackageNullFK.objects.create(screening=screening_with_movie) self.assertEqual(len(PackageNullFK.objects.all()), 3) self.assertEqual(len(PackageNullFK.objects.select_related("screening")), 3) self.assertEqual( len(PackageNullFK.objects.select_related("screening__movie")), 3 ) self.assertEqual(len(PackageNullFK.objects.values()), 3) self.assertEqual(len(PackageNullFK.objects.values("screening__pk")), 3) self.assertEqual(len(PackageNullFK.objects.values("screening__movie__pk")), 3) self.assertEqual( len(PackageNullFK.objects.values("screening__movie__title")), 3 ) self.assertEqual( len( PackageNullFK.objects.values( "screening__movie__pk", "screening__movie__title" ) ), 3, ) self.assertEqual( PackageNullFK.objects.filter(screening__movie=self.movie).count(), 1 ) self.assertEqual( PackageNullFK.objects.exclude(screening__movie=self.movie).count(), 2 ) # Some additional tests for #16715. The only difference is the depth of the # nesting as we now use 4 models instead of 3 (and thus 3 relations). This # checks if promotion of join types works for deeper nesting too. class DeeplyNestedForeignKeysTests(TestCase): @classmethod def setUpTestData(cls): cls.director = Person.objects.create(name="Terry Gilliam / Terry Jones") cls.movie = Movie.objects.create( title="Monty Python and the Holy Grail", director=cls.director ) def test_inheritance(self): Event.objects.create() Screening.objects.create(movie=self.movie) self.assertEqual(len(Event.objects.all()), 2) self.assertEqual( len(Event.objects.select_related("screening__movie__director")), 2 ) self.assertEqual(len(Event.objects.values()), 2) self.assertEqual(len(Event.objects.values("screening__movie__director__pk")), 2) self.assertEqual( len(Event.objects.values("screening__movie__director__name")), 2 ) self.assertEqual( len( Event.objects.values( "screening__movie__director__pk", "screening__movie__director__name" ) ), 2, ) self.assertEqual( len( Event.objects.values( "screening__movie__pk", "screening__movie__director__pk" ) ), 2, ) self.assertEqual( len( Event.objects.values( "screening__movie__pk", "screening__movie__director__name" ) ), 2, ) self.assertEqual( len( Event.objects.values( "screening__movie__title", "screening__movie__director__pk" ) ), 2, ) self.assertEqual( len( Event.objects.values( "screening__movie__title", "screening__movie__director__name" ) ), 2, ) self.assertEqual( Event.objects.filter(screening__movie__director=self.director).count(), 1 ) self.assertEqual( Event.objects.exclude(screening__movie__director=self.director).count(), 1 ) def test_explicit_ForeignKey(self): Package.objects.create() screening = Screening.objects.create(movie=self.movie) Package.objects.create(screening=screening) self.assertEqual(len(Package.objects.all()), 2) self.assertEqual( len(Package.objects.select_related("screening__movie__director")), 2 ) self.assertEqual(len(Package.objects.values()), 2) self.assertEqual( len(Package.objects.values("screening__movie__director__pk")), 2 ) self.assertEqual( len(Package.objects.values("screening__movie__director__name")), 2 ) self.assertEqual( len( Package.objects.values( "screening__movie__director__pk", "screening__movie__director__name" ) ), 2, ) self.assertEqual( len( Package.objects.values( "screening__movie__pk", "screening__movie__director__pk" ) ), 2, ) self.assertEqual( len( Package.objects.values( "screening__movie__pk", "screening__movie__director__name" ) ), 2, ) self.assertEqual( len( Package.objects.values( "screening__movie__title", "screening__movie__director__pk" ) ), 2, ) self.assertEqual( len( Package.objects.values( "screening__movie__title", "screening__movie__director__name" ) ), 2, ) self.assertEqual( Package.objects.filter(screening__movie__director=self.director).count(), 1 ) self.assertEqual( Package.objects.exclude(screening__movie__director=self.director).count(), 1 )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_lorem_ipsum.py
tests/utils_tests/test_lorem_ipsum.py
import unittest from unittest import mock from django.utils.lorem_ipsum import paragraph, paragraphs, sentence, words class LoremIpsumTests(unittest.TestCase): def test_negative_words(self): """words(n) returns n + 19 words, even if n is negative.""" self.assertEqual( words(-5), "lorem ipsum dolor sit amet consectetur adipisicing elit sed do " "eiusmod tempor incididunt ut", ) def test_same_or_less_common_words(self): """words(n) for n < 19.""" self.assertEqual(words(7), "lorem ipsum dolor sit amet consectetur adipisicing") def test_common_words_in_string(self): """ words(n) starts with the 19 standard lorem ipsum words for n > 19. """ self.assertTrue( words(25).startswith( "lorem ipsum dolor sit amet consectetur adipisicing elit sed " "do eiusmod tempor incididunt ut labore et dolore magna aliqua" ) ) def test_more_words_than_common(self): """words(n) returns n words for n > 19.""" self.assertEqual(len(words(25).split()), 25) def test_common_large_number_of_words(self): """words(n) has n words when n is greater than len(WORDS).""" self.assertEqual(len(words(500).split()), 500) @mock.patch("django.utils.lorem_ipsum.random.sample") def test_not_common_words(self, mock_sample): """words(n, common=False) returns random words.""" mock_sample.return_value = ["exercitationem", "perferendis"] self.assertEqual(words(2, common=False), "exercitationem perferendis") def test_sentence_starts_with_capital(self): """A sentence starts with a capital letter.""" self.assertTrue(sentence()[0].isupper()) @mock.patch("django.utils.lorem_ipsum.random.sample") @mock.patch("django.utils.lorem_ipsum.random.choice") @mock.patch("django.utils.lorem_ipsum.random.randint") def test_sentence(self, mock_randint, mock_choice, mock_sample): """ Sentences are built using some number of phrases and a set of words. """ mock_randint.return_value = 2 # Use two phrases. mock_sample.return_value = ["exercitationem", "perferendis"] mock_choice.return_value = "?" value = sentence() self.assertEqual(mock_randint.call_count, 3) self.assertEqual(mock_sample.call_count, 2) self.assertEqual(mock_choice.call_count, 1) self.assertEqual( value, "Exercitationem perferendis, exercitationem perferendis?" ) @mock.patch("django.utils.lorem_ipsum.random.choice") def test_sentence_ending(self, mock_choice): """Sentences end with a question mark or a period.""" mock_choice.return_value = "?" self.assertIn(sentence()[-1], "?") mock_choice.return_value = "." self.assertIn(sentence()[-1], ".") @mock.patch("django.utils.lorem_ipsum.random.sample") @mock.patch("django.utils.lorem_ipsum.random.choice") @mock.patch("django.utils.lorem_ipsum.random.randint") def test_paragraph(self, mock_paragraph_randint, mock_choice, mock_sample): """paragraph() generates a single paragraph.""" # Make creating 2 sentences use 2 phrases. mock_paragraph_randint.return_value = 2 mock_sample.return_value = ["exercitationem", "perferendis"] mock_choice.return_value = "." value = paragraph() self.assertEqual(mock_paragraph_randint.call_count, 7) self.assertEqual( value, ( "Exercitationem perferendis, exercitationem perferendis. " "Exercitationem perferendis, exercitationem perferendis." ), ) @mock.patch("django.utils.lorem_ipsum.random.sample") @mock.patch("django.utils.lorem_ipsum.random.choice") @mock.patch("django.utils.lorem_ipsum.random.randint") def test_paragraphs_not_common(self, mock_randint, mock_choice, mock_sample): """ paragraphs(1, common=False) generating one paragraph that's not the COMMON_P paragraph. """ # Make creating 2 sentences use 2 phrases. mock_randint.return_value = 2 mock_sample.return_value = ["exercitationem", "perferendis"] mock_choice.return_value = "." self.assertEqual( paragraphs(1, common=False), [ "Exercitationem perferendis, exercitationem perferendis. " "Exercitationem perferendis, exercitationem perferendis." ], ) self.assertEqual(mock_randint.call_count, 7) def test_paragraphs(self): """paragraphs(1) uses the COMMON_P paragraph.""" self.assertEqual( paragraphs(1), [ "Lorem ipsum dolor sit amet, consectetur adipisicing elit, " "sed do eiusmod tempor incididunt ut labore et dolore magna " "aliqua. Ut enim ad minim veniam, quis nostrud exercitation " "ullamco laboris nisi ut aliquip ex ea commodo consequat. " "Duis aute irure dolor in reprehenderit in voluptate velit " "esse cillum dolore eu fugiat nulla pariatur. Excepteur sint " "occaecat cupidatat non proident, sunt in culpa qui officia " "deserunt mollit anim id est laborum." ], )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_lazyobject.py
tests/utils_tests/test_lazyobject.py
import copy import pickle import sys import unittest import warnings from django.test import TestCase from django.utils.functional import LazyObject, SimpleLazyObject, empty from .models import Category, CategoryInfo class Foo: """ A simple class with just one attribute. """ foo = "bar" def __eq__(self, other): return self.foo == other.foo class LazyObjectTestCase(unittest.TestCase): def lazy_wrap(self, wrapped_object): """ Wrap the given object into a LazyObject """ class AdHocLazyObject(LazyObject): def _setup(self): self._wrapped = wrapped_object return AdHocLazyObject() def test_getattribute(self): """ Proxy methods don't exist on wrapped objects unless they're set. """ attrs = [ "__getitem__", "__setitem__", "__delitem__", "__iter__", "__len__", "__contains__", ] foo = Foo() obj = self.lazy_wrap(foo) for attr in attrs: with self.subTest(attr): self.assertFalse(hasattr(obj, attr)) setattr(foo, attr, attr) obj_with_attr = self.lazy_wrap(foo) self.assertTrue(hasattr(obj_with_attr, attr)) self.assertEqual(getattr(obj_with_attr, attr), attr) def test_getattr(self): obj = self.lazy_wrap(Foo()) self.assertEqual(obj.foo, "bar") def test_getattr_falsey(self): class Thing: def __getattr__(self, key): return [] obj = self.lazy_wrap(Thing()) self.assertEqual(obj.main, []) def test_setattr(self): obj = self.lazy_wrap(Foo()) obj.foo = "BAR" obj.bar = "baz" self.assertEqual(obj.foo, "BAR") self.assertEqual(obj.bar, "baz") def test_setattr2(self): # Same as test_setattr but in reversed order obj = self.lazy_wrap(Foo()) obj.bar = "baz" obj.foo = "BAR" self.assertEqual(obj.foo, "BAR") self.assertEqual(obj.bar, "baz") def test_delattr(self): obj = self.lazy_wrap(Foo()) obj.bar = "baz" self.assertEqual(obj.bar, "baz") del obj.bar with self.assertRaises(AttributeError): obj.bar def test_cmp(self): obj1 = self.lazy_wrap("foo") obj2 = self.lazy_wrap("bar") obj3 = self.lazy_wrap("foo") self.assertEqual(obj1, "foo") self.assertEqual(obj1, obj3) self.assertNotEqual(obj1, obj2) self.assertNotEqual(obj1, "bar") def test_lt(self): obj1 = self.lazy_wrap(1) obj2 = self.lazy_wrap(2) self.assertLess(obj1, obj2) def test_gt(self): obj1 = self.lazy_wrap(1) obj2 = self.lazy_wrap(2) self.assertGreater(obj2, obj1) def test_bytes(self): obj = self.lazy_wrap(b"foo") self.assertEqual(bytes(obj), b"foo") def test_text(self): obj = self.lazy_wrap("foo") self.assertEqual(str(obj), "foo") def test_bool(self): # Refs #21840 for f in [False, 0, (), {}, [], None, set()]: self.assertFalse(self.lazy_wrap(f)) for t in [True, 1, (1,), {1: 2}, [1], object(), {1}]: self.assertTrue(t) def test_dir(self): obj = self.lazy_wrap("foo") self.assertEqual(dir(obj), dir("foo")) def test_len(self): for seq in ["asd", [1, 2, 3], {"a": 1, "b": 2, "c": 3}]: obj = self.lazy_wrap(seq) self.assertEqual(len(obj), 3) def test_class(self): self.assertIsInstance(self.lazy_wrap(42), int) class Bar(Foo): pass self.assertIsInstance(self.lazy_wrap(Bar()), Foo) def test_hash(self): obj = self.lazy_wrap("foo") d = {obj: "bar"} self.assertIn("foo", d) self.assertEqual(d["foo"], "bar") def test_contains(self): test_data = [ ("c", "abcde"), (2, [1, 2, 3]), ("a", {"a": 1, "b": 2, "c": 3}), (2, {1, 2, 3}), ] for needle, haystack in test_data: self.assertIn(needle, self.lazy_wrap(haystack)) # __contains__ doesn't work when the haystack is a string and the # needle a LazyObject. for needle_haystack in test_data[1:]: self.assertIn(self.lazy_wrap(needle), haystack) self.assertIn(self.lazy_wrap(needle), self.lazy_wrap(haystack)) def test_getitem(self): obj_list = self.lazy_wrap([1, 2, 3]) obj_dict = self.lazy_wrap({"a": 1, "b": 2, "c": 3}) self.assertEqual(obj_list[0], 1) self.assertEqual(obj_list[-1], 3) self.assertEqual(obj_list[1:2], [2]) self.assertEqual(obj_dict["b"], 2) with self.assertRaises(IndexError): obj_list[3] with self.assertRaises(KeyError): obj_dict["f"] def test_setitem(self): obj_list = self.lazy_wrap([1, 2, 3]) obj_dict = self.lazy_wrap({"a": 1, "b": 2, "c": 3}) obj_list[0] = 100 self.assertEqual(obj_list, [100, 2, 3]) obj_list[1:2] = [200, 300, 400] self.assertEqual(obj_list, [100, 200, 300, 400, 3]) obj_dict["a"] = 100 obj_dict["d"] = 400 self.assertEqual(obj_dict, {"a": 100, "b": 2, "c": 3, "d": 400}) def test_delitem(self): obj_list = self.lazy_wrap([1, 2, 3]) obj_dict = self.lazy_wrap({"a": 1, "b": 2, "c": 3}) del obj_list[-1] del obj_dict["c"] self.assertEqual(obj_list, [1, 2]) self.assertEqual(obj_dict, {"a": 1, "b": 2}) with self.assertRaises(IndexError): del obj_list[3] with self.assertRaises(KeyError): del obj_dict["f"] def test_iter(self): # Tests whether an object's custom `__iter__` method is being # used when iterating over it. class IterObject: def __init__(self, values): self.values = values def __iter__(self): return iter(self.values) original_list = ["test", "123"] self.assertEqual(list(self.lazy_wrap(IterObject(original_list))), original_list) def test_pickle(self): # See ticket #16563 obj = self.lazy_wrap(Foo()) obj.bar = "baz" pickled = pickle.dumps(obj) unpickled = pickle.loads(pickled) self.assertIsInstance(unpickled, Foo) self.assertEqual(unpickled, obj) self.assertEqual(unpickled.foo, obj.foo) self.assertEqual(unpickled.bar, obj.bar) # Test copying lazy objects wrapping both builtin types and user-defined # classes since a lot of the relevant code does __dict__ manipulation and # builtin types don't have __dict__. def test_copy_list(self): # Copying a list works and returns the correct objects. lst = [1, 2, 3] obj = self.lazy_wrap(lst) len(lst) # forces evaluation obj2 = copy.copy(obj) self.assertIsNot(obj, obj2) self.assertIsInstance(obj2, list) self.assertEqual(obj2, [1, 2, 3]) def test_copy_list_no_evaluation(self): # Copying a list doesn't force evaluation. lst = [1, 2, 3] obj = self.lazy_wrap(lst) obj2 = copy.copy(obj) self.assertIsNot(obj, obj2) self.assertIs(obj._wrapped, empty) self.assertIs(obj2._wrapped, empty) def test_copy_class(self): # Copying a class works and returns the correct objects. foo = Foo() obj = self.lazy_wrap(foo) str(foo) # forces evaluation obj2 = copy.copy(obj) self.assertIsNot(obj, obj2) self.assertIsInstance(obj2, Foo) self.assertEqual(obj2, Foo()) def test_copy_class_no_evaluation(self): # Copying a class doesn't force evaluation. foo = Foo() obj = self.lazy_wrap(foo) obj2 = copy.copy(obj) self.assertIsNot(obj, obj2) self.assertIs(obj._wrapped, empty) self.assertIs(obj2._wrapped, empty) def test_deepcopy_list(self): # Deep copying a list works and returns the correct objects. lst = [1, 2, 3] obj = self.lazy_wrap(lst) len(lst) # forces evaluation obj2 = copy.deepcopy(obj) self.assertIsNot(obj, obj2) self.assertIsInstance(obj2, list) self.assertEqual(obj2, [1, 2, 3]) def test_deepcopy_list_no_evaluation(self): # Deep copying doesn't force evaluation. lst = [1, 2, 3] obj = self.lazy_wrap(lst) obj2 = copy.deepcopy(obj) self.assertIsNot(obj, obj2) self.assertIs(obj._wrapped, empty) self.assertIs(obj2._wrapped, empty) def test_deepcopy_class(self): # Deep copying a class works and returns the correct objects. foo = Foo() obj = self.lazy_wrap(foo) str(foo) # forces evaluation obj2 = copy.deepcopy(obj) self.assertIsNot(obj, obj2) self.assertIsInstance(obj2, Foo) self.assertEqual(obj2, Foo()) def test_deepcopy_class_no_evaluation(self): # Deep copying doesn't force evaluation. foo = Foo() obj = self.lazy_wrap(foo) obj2 = copy.deepcopy(obj) self.assertIsNot(obj, obj2) self.assertIs(obj._wrapped, empty) self.assertIs(obj2._wrapped, empty) class SimpleLazyObjectTestCase(LazyObjectTestCase): # By inheriting from LazyObjectTestCase and redefining the lazy_wrap() # method which all testcases use, we get to make sure all behaviors # tested in the parent testcase also apply to SimpleLazyObject. def lazy_wrap(self, wrapped_object): return SimpleLazyObject(lambda: wrapped_object) def test_repr(self): # First, for an unevaluated SimpleLazyObject obj = self.lazy_wrap(42) # __repr__ contains __repr__ of setup function and does not evaluate # the SimpleLazyObject self.assertRegex(repr(obj), "^<SimpleLazyObject:") self.assertIs(obj._wrapped, empty) # make sure evaluation hasn't been triggered self.assertEqual(obj, 42) # evaluate the lazy object self.assertIsInstance(obj._wrapped, int) self.assertEqual(repr(obj), "<SimpleLazyObject: 42>") def test_repr_bound_method(self): class MyLazyGenerator(SimpleLazyObject): def __init__(self): super().__init__(self._generate) def _generate(self): return "test-generated-value" obj = MyLazyGenerator() self.assertEqual(repr(obj), "<MyLazyGenerator: '<bound method _generate>'>") self.assertIs(obj._wrapped, empty) # The evaluation hasn't happened. self.assertEqual(str(obj), "test-generated-value") # Evaluate. self.assertEqual(repr(obj), "<MyLazyGenerator: 'test-generated-value'>") def test_add(self): obj1 = self.lazy_wrap(1) self.assertEqual(obj1 + 1, 2) obj2 = self.lazy_wrap(2) self.assertEqual(obj2 + obj1, 3) self.assertEqual(obj1 + obj2, 3) def test_radd(self): obj1 = self.lazy_wrap(1) self.assertEqual(1 + obj1, 2) def test_trace(self): # See ticket #19456 old_trace_func = sys.gettrace() try: def trace_func(frame, event, arg): frame.f_locals["self"].__class__ if old_trace_func is not None: old_trace_func(frame, event, arg) sys.settrace(trace_func) self.lazy_wrap(None) finally: sys.settrace(old_trace_func) def test_none(self): i = [0] def f(): i[0] += 1 return None x = SimpleLazyObject(f) self.assertEqual(str(x), "None") self.assertEqual(i, [1]) self.assertEqual(str(x), "None") self.assertEqual(i, [1]) def test_dict(self): # See ticket #18447 lazydict = SimpleLazyObject(lambda: {"one": 1}) self.assertEqual(lazydict["one"], 1) lazydict["one"] = -1 self.assertEqual(lazydict["one"], -1) self.assertIn("one", lazydict) self.assertNotIn("two", lazydict) self.assertEqual(len(lazydict), 1) del lazydict["one"] with self.assertRaises(KeyError): lazydict["one"] def test_list_set(self): lazy_list = SimpleLazyObject(lambda: [1, 2, 3, 4, 5]) lazy_set = SimpleLazyObject(lambda: {1, 2, 3, 4}) self.assertIn(1, lazy_list) self.assertIn(1, lazy_set) self.assertNotIn(6, lazy_list) self.assertNotIn(6, lazy_set) self.assertEqual(len(lazy_list), 5) self.assertEqual(len(lazy_set), 4) class BaseBaz: """ A base class with a funky __reduce__ method, meant to simulate the __reduce__ method of Model, which sets self._django_version. """ def __init__(self): self.baz = "wrong" def __reduce__(self): self.baz = "right" return super().__reduce__() def __eq__(self, other): if self.__class__ != other.__class__: return False for attr in ["bar", "baz", "quux"]: if hasattr(self, attr) != hasattr(other, attr): return False elif getattr(self, attr, None) != getattr(other, attr, None): return False return True class Baz(BaseBaz): """ A class that inherits from BaseBaz and has its own __reduce_ex__ method. """ def __init__(self, bar): self.bar = bar super().__init__() def __reduce_ex__(self, proto): self.quux = "quux" return super().__reduce_ex__(proto) class BazProxy(Baz): """ A class that acts as a proxy for Baz. It does some scary mucking about with dicts, which simulates some crazy things that people might do with e.g. proxy models. """ def __init__(self, baz): self.__dict__ = baz.__dict__ self._baz = baz # Grandparent super super(BaseBaz, self).__init__() class SimpleLazyObjectPickleTestCase(TestCase): """ Regression test for pickling a SimpleLazyObject wrapping a model (#25389). Also covers other classes with a custom __reduce__ method. """ def test_pickle_with_reduce(self): """ Test in a fairly synthetic setting. """ # Test every pickle protocol available for protocol in range(pickle.HIGHEST_PROTOCOL + 1): lazy_objs = [ SimpleLazyObject(lambda: BaseBaz()), SimpleLazyObject(lambda: Baz(1)), SimpleLazyObject(lambda: BazProxy(Baz(2))), ] for obj in lazy_objs: pickled = pickle.dumps(obj, protocol) unpickled = pickle.loads(pickled) self.assertEqual(unpickled, obj) self.assertEqual(unpickled.baz, "right") def test_pickle_model(self): """ Test on an actual model, based on the report in #25426. """ category = Category.objects.create(name="thing1") CategoryInfo.objects.create(category=category) # Test every pickle protocol available for protocol in range(pickle.HIGHEST_PROTOCOL + 1): lazy_category = SimpleLazyObject(lambda: category) # Test both if we accessed a field on the model and if we didn't. lazy_category.categoryinfo lazy_category_2 = SimpleLazyObject(lambda: category) with warnings.catch_warnings(record=True) as recorded: self.assertEqual( pickle.loads(pickle.dumps(lazy_category, protocol)), category ) self.assertEqual( pickle.loads(pickle.dumps(lazy_category_2, protocol)), category ) # Assert that there were no warnings. self.assertEqual(len(recorded), 0)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_numberformat.py
tests/utils_tests/test_numberformat.py
from decimal import Decimal from sys import float_info from django.test import SimpleTestCase from django.utils.numberformat import format as nformat class TestNumberFormat(SimpleTestCase): def test_format_number(self): self.assertEqual(nformat(1234, "."), "1234") self.assertEqual(nformat(1234.2, "."), "1234.2") self.assertEqual(nformat(1234, ".", decimal_pos=2), "1234.00") self.assertEqual(nformat(1234, ".", grouping=2, thousand_sep=","), "1234") self.assertEqual( nformat(1234, ".", grouping=2, thousand_sep=",", force_grouping=True), "12,34", ) self.assertEqual(nformat(-1234.33, ".", decimal_pos=1), "-1234.3") # The use_l10n parameter can force thousand grouping behavior. with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual( nformat(1234, ".", grouping=3, thousand_sep=",", use_l10n=False), "1234" ) self.assertEqual( nformat(1234, ".", grouping=3, thousand_sep=",", use_l10n=True), "1,234" ) def test_format_string(self): self.assertEqual(nformat("1234", "."), "1234") self.assertEqual(nformat("1234.2", "."), "1234.2") self.assertEqual(nformat("1234", ".", decimal_pos=2), "1234.00") self.assertEqual(nformat("1234", ".", grouping=2, thousand_sep=","), "1234") self.assertEqual( nformat("1234", ".", grouping=2, thousand_sep=",", force_grouping=True), "12,34", ) self.assertEqual(nformat("-1234.33", ".", decimal_pos=1), "-1234.3") self.assertEqual( nformat( "10000", ".", grouping=3, thousand_sep="comma", force_grouping=True ), "10comma000", ) def test_large_number(self): most_max = ( "{}179769313486231570814527423731704356798070567525844996" "598917476803157260780028538760589558632766878171540458953" "514382464234321326889464182768467546703537516986049910576" "551282076245490090389328944075868508455133942304583236903" "222948165808559332123348274797826204144723168738177180919" "29988125040402618412485836{}" ) most_max2 = ( "{}35953862697246314162905484746340871359614113505168999" "31978349536063145215600570775211791172655337563430809179" "07028764928468642653778928365536935093407075033972099821" "15310256415249098018077865788815173701691026788460916647" "38064458963316171186642466965495956524082894463374763543" "61838599762500808052368249716736" ) int_max = int(float_info.max) self.assertEqual(nformat(int_max, "."), most_max.format("", "8")) self.assertEqual(nformat(int_max + 1, "."), most_max.format("", "9")) self.assertEqual(nformat(int_max * 2, "."), most_max2.format("")) self.assertEqual(nformat(0 - int_max, "."), most_max.format("-", "8")) self.assertEqual(nformat(-1 - int_max, "."), most_max.format("-", "9")) self.assertEqual(nformat(-2 * int_max, "."), most_max2.format("-")) def test_float_numbers(self): tests = [ (9e-10, 10, "0.0000000009"), (9e-19, 2, "0.00"), (0.00000000000099, 0, "0"), (0.00000000000099, 13, "0.0000000000009"), (1e16, None, "10000000000000000"), (1e16, 2, "10000000000000000.00"), # A float without a fractional part (3.) results in a ".0" when no # decimal_pos is given. Contrast that with the Decimal('3.') case # in test_decimal_numbers which doesn't return a fractional part. (3.0, None, "3.0"), ] for value, decimal_pos, expected_value in tests: with self.subTest(value=value, decimal_pos=decimal_pos): self.assertEqual(nformat(value, ".", decimal_pos), expected_value) # Thousand grouping behavior. self.assertEqual( nformat(1e16, ".", thousand_sep=",", grouping=3, force_grouping=True), "10,000,000,000,000,000", ) self.assertEqual( nformat( 1e16, ".", decimal_pos=2, thousand_sep=",", grouping=3, force_grouping=True, ), "10,000,000,000,000,000.00", ) def test_decimal_numbers(self): self.assertEqual(nformat(Decimal("1234"), "."), "1234") self.assertEqual(nformat(Decimal("1234.2"), "."), "1234.2") self.assertEqual(nformat(Decimal("1234"), ".", decimal_pos=2), "1234.00") self.assertEqual( nformat(Decimal("1234"), ".", grouping=2, thousand_sep=","), "1234" ) self.assertEqual( nformat( Decimal("1234"), ".", grouping=2, thousand_sep=",", force_grouping=True ), "12,34", ) self.assertEqual(nformat(Decimal("-1234.33"), ".", decimal_pos=1), "-1234.3") self.assertEqual( nformat(Decimal("0.00000001"), ".", decimal_pos=8), "0.00000001" ) self.assertEqual(nformat(Decimal("9e-19"), ".", decimal_pos=2), "0.00") self.assertEqual(nformat(Decimal(".00000000000099"), ".", decimal_pos=0), "0") self.assertEqual( nformat( Decimal("1e16"), ".", thousand_sep=",", grouping=3, force_grouping=True ), "10,000,000,000,000,000", ) self.assertEqual( nformat( Decimal("1e16"), ".", decimal_pos=2, thousand_sep=",", grouping=3, force_grouping=True, ), "10,000,000,000,000,000.00", ) self.assertEqual(nformat(Decimal("3."), "."), "3") self.assertEqual(nformat(Decimal("3.0"), "."), "3.0") # Very large & small numbers. tests = [ ("9e9999", None, "9e+9999"), ("9e9999", 3, "9.000e+9999"), ("9e201", None, "9e+201"), ("9e200", None, "9e+200"), ("1.2345e999", 2, "1.23e+999"), ("9e-999", None, "9e-999"), ("1e-7", 8, "0.00000010"), ("1e-8", 8, "0.00000001"), ("1e-9", 8, "0.00000000"), ("1e-10", 8, "0.00000000"), ("1e-11", 8, "0.00000000"), ("1" + ("0" * 300), 3, "1.000e+300"), ("0.{}1234".format("0" * 299), 3, "0.000"), ] for value, decimal_pos, expected_value in tests: with self.subTest(value=value): self.assertEqual( nformat(Decimal(value), ".", decimal_pos), expected_value ) def test_decimal_subclass(self): class EuroDecimal(Decimal): """ Wrapper for Decimal which prefixes each amount with the € symbol. """ def __format__(self, specifier, **kwargs): amount = super().__format__(specifier, **kwargs) return "€ {}".format(amount) price = EuroDecimal("1.23") self.assertEqual(nformat(price, ","), "€ 1,23") def test_empty(self): self.assertEqual(nformat("", "."), "") self.assertEqual(nformat(None, "."), "None")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_functional.py
tests/utils_tests/test_functional.py
from django.test import SimpleTestCase from django.utils.functional import cached_property, classproperty, lazy class FunctionalTests(SimpleTestCase): def test_lazy(self): t = lazy(lambda: tuple(range(3)), list, tuple) for a, b in zip(t(), range(3)): self.assertEqual(a, b) def test_lazy_base_class(self): """lazy also finds base class methods in the proxy object""" class Base: def base_method(self): pass class Klazz(Base): pass t = lazy(lambda: Klazz(), Klazz)() self.assertIn("base_method", dir(t)) def test_lazy_base_class_override(self): """lazy finds the correct (overridden) method implementation""" class Base: def method(self): return "Base" class Klazz(Base): def method(self): return "Klazz" t = lazy(lambda: Klazz(), Base)() self.assertEqual(t.method(), "Klazz") def test_lazy_object_to_string(self): class Klazz: def __str__(self): return "Î am ā Ǩlâzz." def __bytes__(self): return b"\xc3\x8e am \xc4\x81 binary \xc7\xa8l\xc3\xa2zz." t = lazy(lambda: Klazz(), Klazz)() self.assertEqual(str(t), "Î am ā Ǩlâzz.") self.assertEqual(bytes(t), b"\xc3\x8e am \xc4\x81 binary \xc7\xa8l\xc3\xa2zz.") def assertCachedPropertyWorks(self, attr, Class): with self.subTest(attr=attr): def get(source): return getattr(source, attr) obj = Class() class SubClass(Class): pass subobj = SubClass() # Docstring is preserved. self.assertEqual(get(Class).__doc__, "Here is the docstring...") self.assertEqual(get(SubClass).__doc__, "Here is the docstring...") # It's cached. self.assertEqual(get(obj), get(obj)) self.assertEqual(get(subobj), get(subobj)) # The correct value is returned. self.assertEqual(get(obj)[0], 1) self.assertEqual(get(subobj)[0], 1) # State isn't shared between instances. obj2 = Class() subobj2 = SubClass() self.assertNotEqual(get(obj), get(obj2)) self.assertNotEqual(get(subobj), get(subobj2)) # It behaves like a property when there's no instance. self.assertIsInstance(get(Class), cached_property) self.assertIsInstance(get(SubClass), cached_property) # 'other_value' doesn't become a property. self.assertTrue(callable(obj.other_value)) self.assertTrue(callable(subobj.other_value)) def test_cached_property(self): """cached_property caches its value and behaves like a property.""" class Class: @cached_property def value(self): """Here is the docstring...""" return 1, object() @cached_property def __foo__(self): """Here is the docstring...""" return 1, object() def other_value(self): """Here is the docstring...""" return 1, object() other = cached_property(other_value) attrs = ["value", "other", "__foo__"] for attr in attrs: self.assertCachedPropertyWorks(attr, Class) def test_cached_property_auto_name(self): """ cached_property caches its value and behaves like a property on mangled methods or when the name kwarg isn't set. """ class Class: @cached_property def __value(self): """Here is the docstring...""" return 1, object() def other_value(self): """Here is the docstring...""" return 1, object() other = cached_property(other_value) attrs = ["_Class__value", "other"] for attr in attrs: self.assertCachedPropertyWorks(attr, Class) def test_cached_property_reuse_different_names(self): """ Disallow this case because the decorated function wouldn't be cached. """ type_msg = ( "Cannot assign the same cached_property to two different names ('a' and " "'b')." ) error_type = TypeError msg = type_msg with self.assertRaisesMessage(error_type, msg): class ReusedCachedProperty: @cached_property def a(self): pass b = a def test_cached_property_reuse_same_name(self): """ Reusing a cached_property on different classes under the same name is allowed. """ counter = 0 @cached_property def _cp(_self): nonlocal counter counter += 1 return counter class A: cp = _cp class B: cp = _cp a = A() b = B() self.assertEqual(a.cp, 1) self.assertEqual(b.cp, 2) self.assertEqual(a.cp, 1) def test_cached_property_set_name_not_called(self): cp = cached_property(lambda s: None) class Foo: pass Foo.cp = cp msg = ( "Cannot use cached_property instance without calling __set_name__() on it." ) with self.assertRaisesMessage(TypeError, msg): Foo().cp def test_lazy_add_int(self): lazy_4 = lazy(lambda: 4, int) lazy_5 = lazy(lambda: 5, int) self.assertEqual(4 + lazy_5(), 9) self.assertEqual(lazy_4() + 5, 9) self.assertEqual(lazy_4() + lazy_5(), 9) def test_lazy_add_list(self): lazy_4 = lazy(lambda: [4], list) lazy_5 = lazy(lambda: [5], list) self.assertEqual([4] + lazy_5(), [4, 5]) self.assertEqual(lazy_4() + [5], [4, 5]) self.assertEqual(lazy_4() + lazy_5(), [4, 5]) def test_lazy_add_str(self): lazy_a = lazy(lambda: "a", str) lazy_b = lazy(lambda: "b", str) self.assertEqual("a" + lazy_b(), "ab") self.assertEqual(lazy_a() + "b", "ab") self.assertEqual(lazy_a() + lazy_b(), "ab") def test_lazy_mod_int(self): lazy_4 = lazy(lambda: 4, int) lazy_5 = lazy(lambda: 5, int) self.assertEqual(4 % lazy_5(), 4) self.assertEqual(lazy_4() % 5, 4) self.assertEqual(lazy_4() % lazy_5(), 4) def test_lazy_mod_str(self): lazy_a = lazy(lambda: "a%s", str) lazy_b = lazy(lambda: "b", str) self.assertEqual("a%s" % lazy_b(), "ab") self.assertEqual(lazy_a() % "b", "ab") self.assertEqual(lazy_a() % lazy_b(), "ab") def test_lazy_mul_int(self): lazy_4 = lazy(lambda: 4, int) lazy_5 = lazy(lambda: 5, int) self.assertEqual(4 * lazy_5(), 20) self.assertEqual(lazy_4() * 5, 20) self.assertEqual(lazy_4() * lazy_5(), 20) def test_lazy_mul_list(self): lazy_4 = lazy(lambda: [4], list) lazy_5 = lazy(lambda: 5, int) self.assertEqual([4] * lazy_5(), [4, 4, 4, 4, 4]) self.assertEqual(lazy_4() * 5, [4, 4, 4, 4, 4]) self.assertEqual(lazy_4() * lazy_5(), [4, 4, 4, 4, 4]) def test_lazy_mul_str(self): lazy_a = lazy(lambda: "a", str) lazy_5 = lazy(lambda: 5, int) self.assertEqual("a" * lazy_5(), "aaaaa") self.assertEqual(lazy_a() * 5, "aaaaa") self.assertEqual(lazy_a() * lazy_5(), "aaaaa") def test_lazy_format(self): class QuotedString(str): def __format__(self, format_spec): value = super().__format__(format_spec) return f"“{value}”" lazy_f = lazy(lambda: QuotedString("Hello!"), QuotedString) self.assertEqual(format(lazy_f(), ""), "“Hello!”") f = lazy_f() self.assertEqual(f"I said, {f}", "I said, “Hello!”") def test_lazy_equality(self): """ == and != work correctly for Promises. """ lazy_a = lazy(lambda: 4, int) lazy_b = lazy(lambda: 4, int) lazy_c = lazy(lambda: 5, int) self.assertEqual(lazy_a(), lazy_b()) self.assertNotEqual(lazy_b(), lazy_c()) def test_lazy_repr_text(self): original_object = "Lazy translation text" lazy_obj = lazy(lambda: original_object, str) self.assertEqual(repr(original_object), repr(lazy_obj())) def test_lazy_repr_int(self): original_object = 15 lazy_obj = lazy(lambda: original_object, int) self.assertEqual(repr(original_object), repr(lazy_obj())) def test_lazy_repr_bytes(self): original_object = b"J\xc3\xbcst a str\xc3\xadng" lazy_obj = lazy(lambda: original_object, bytes) self.assertEqual(repr(original_object), repr(lazy_obj())) def test_lazy_regular_method(self): original_object = 15 lazy_obj = lazy(lambda: original_object, int) self.assertEqual(original_object.bit_length(), lazy_obj().bit_length()) def test_lazy_bytes_and_str_result_classes(self): lazy_obj = lazy(lambda: "test", str, bytes) self.assertEqual(str(lazy_obj()), "test") def test_lazy_str_cast_mixed_result_types(self): lazy_value = lazy(lambda: [1], str, list)() self.assertEqual(str(lazy_value), "[1]") def test_lazy_str_cast_mixed_bytes_result_types(self): lazy_value = lazy(lambda: [1], bytes, list)() self.assertEqual(str(lazy_value), "[1]") def test_classproperty_getter(self): class Foo: foo_attr = 123 def __init__(self): self.foo_attr = 456 @classproperty def foo(cls): return cls.foo_attr class Bar: bar = classproperty() @bar.getter def bar(cls): return 123 self.assertEqual(Foo.foo, 123) self.assertEqual(Foo().foo, 123) self.assertEqual(Bar.bar, 123) self.assertEqual(Bar().bar, 123) def test_classproperty_override_getter(self): class Foo: @classproperty def foo(cls): return 123 @foo.getter def foo(cls): return 456 self.assertEqual(Foo.foo, 456) self.assertEqual(Foo().foo, 456)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_termcolors.py
tests/utils_tests/test_termcolors.py
import unittest from django.utils.termcolors import ( DARK_PALETTE, DEFAULT_PALETTE, LIGHT_PALETTE, NOCOLOR_PALETTE, PALETTES, colorize, parse_color_setting, ) class TermColorTests(unittest.TestCase): def test_empty_string(self): self.assertEqual(parse_color_setting(""), PALETTES[DEFAULT_PALETTE]) def test_simple_palette(self): self.assertEqual(parse_color_setting("light"), PALETTES[LIGHT_PALETTE]) self.assertEqual(parse_color_setting("dark"), PALETTES[DARK_PALETTE]) self.assertIsNone(parse_color_setting("nocolor")) def test_fg(self): self.assertEqual( parse_color_setting("error=green"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) def test_fg_bg(self): self.assertEqual( parse_color_setting("error=green/blue"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue"}), ) def test_fg_opts(self): self.assertEqual( parse_color_setting("error=green,blink"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) self.assertEqual( parse_color_setting("error=green,bold,blink"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink", "bold")}, ), ) def test_fg_bg_opts(self): self.assertEqual( parse_color_setting("error=green/blue,blink"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue", "opts": ("blink",)}, ), ) self.assertEqual( parse_color_setting("error=green/blue,bold,blink"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue", "opts": ("blink", "bold")}, ), ) def test_override_palette(self): self.assertEqual( parse_color_setting("light;error=green"), dict(PALETTES[LIGHT_PALETTE], ERROR={"fg": "green"}), ) def test_override_nocolor(self): self.assertEqual( parse_color_setting("nocolor;error=green"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) def test_reverse_override(self): self.assertEqual( parse_color_setting("error=green;light"), PALETTES[LIGHT_PALETTE] ) def test_multiple_roles(self): self.assertEqual( parse_color_setting("error=green;sql_field=blue"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}, SQL_FIELD={"fg": "blue"}, ), ) def test_override_with_multiple_roles(self): self.assertEqual( parse_color_setting("light;error=green;sql_field=blue"), dict( PALETTES[LIGHT_PALETTE], ERROR={"fg": "green"}, SQL_FIELD={"fg": "blue"} ), ) def test_empty_definition(self): self.assertIsNone(parse_color_setting(";")) self.assertEqual(parse_color_setting("light;"), PALETTES[LIGHT_PALETTE]) self.assertIsNone(parse_color_setting(";;;")) def test_empty_options(self): self.assertEqual( parse_color_setting("error=green,"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=green,,,"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=green,,blink,,"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) def test_bad_palette(self): self.assertIsNone(parse_color_setting("unknown")) def test_bad_role(self): self.assertIsNone(parse_color_setting("unknown=")) self.assertIsNone(parse_color_setting("unknown=green")) self.assertEqual( parse_color_setting("unknown=green;sql_field=blue"), dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={"fg": "blue"}), ) def test_bad_color(self): self.assertIsNone(parse_color_setting("error=")) self.assertEqual( parse_color_setting("error=;sql_field=blue"), dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={"fg": "blue"}), ) self.assertIsNone(parse_color_setting("error=unknown")) self.assertEqual( parse_color_setting("error=unknown;sql_field=blue"), dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={"fg": "blue"}), ) self.assertEqual( parse_color_setting("error=green/unknown"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=green/blue/something"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue"}), ) self.assertEqual( parse_color_setting("error=green/blue/something,blink"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue", "opts": ("blink",)}, ), ) def test_bad_option(self): self.assertEqual( parse_color_setting("error=green,unknown"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=green,unknown,blink"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) def test_role_case(self): self.assertEqual( parse_color_setting("ERROR=green"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("eRrOr=green"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) def test_color_case(self): self.assertEqual( parse_color_setting("error=GREEN"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=GREEN/BLUE"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue"}), ) self.assertEqual( parse_color_setting("error=gReEn"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=gReEn/bLuE"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue"}), ) def test_opts_case(self): self.assertEqual( parse_color_setting("error=green,BLINK"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) self.assertEqual( parse_color_setting("error=green,bLiNk"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) def test_colorize_empty_text(self): self.assertEqual(colorize(text=None), "\x1b[m\x1b[0m") self.assertEqual(colorize(text=""), "\x1b[m\x1b[0m") self.assertEqual(colorize(text=None, opts=("noreset",)), "\x1b[m") self.assertEqual(colorize(text="", opts=("noreset",)), "\x1b[m") def test_colorize_reset(self): self.assertEqual(colorize(text="", opts=("reset",)), "\x1b[0m") def test_colorize_fg_bg(self): self.assertEqual(colorize(text="Test", fg="red"), "\x1b[31mTest\x1b[0m") self.assertEqual(colorize(text="Test", bg="red"), "\x1b[41mTest\x1b[0m") # Ignored kwarg. self.assertEqual(colorize(text="Test", other="red"), "\x1b[mTest\x1b[0m") def test_colorize_opts(self): self.assertEqual( colorize(text="Test", opts=("bold", "underscore")), "\x1b[1;4mTest\x1b[0m", ) self.assertEqual( colorize(text="Test", opts=("blink",)), "\x1b[5mTest\x1b[0m", ) # Ignored opts. self.assertEqual( colorize(text="Test", opts=("not_an_option",)), "\x1b[mTest\x1b[0m", )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_archive.py
tests/utils_tests/test_archive.py
import os import stat import sys import tempfile import unittest import zipfile from django.core.exceptions import SuspiciousOperation from django.test import SimpleTestCase from django.utils import archive try: import bz2 # NOQA HAS_BZ2 = True except ImportError: HAS_BZ2 = False try: import lzma # NOQA HAS_LZMA = True except ImportError: HAS_LZMA = False class TestArchive(unittest.TestCase): def setUp(self): self.testdir = os.path.join(os.path.dirname(__file__), "archives") old_cwd = os.getcwd() os.chdir(self.testdir) self.addCleanup(os.chdir, old_cwd) def test_extract_function(self): with os.scandir(self.testdir) as entries: for entry in entries: with self.subTest(entry.name), tempfile.TemporaryDirectory() as tmpdir: if (entry.name.endswith(".bz2") and not HAS_BZ2) or ( entry.name.endswith((".lzma", ".xz")) and not HAS_LZMA ): continue archive.extract(entry.path, tmpdir) self.assertTrue(os.path.isfile(os.path.join(tmpdir, "1"))) self.assertTrue(os.path.isfile(os.path.join(tmpdir, "2"))) self.assertTrue(os.path.isfile(os.path.join(tmpdir, "foo", "1"))) self.assertTrue(os.path.isfile(os.path.join(tmpdir, "foo", "2"))) self.assertTrue( os.path.isfile(os.path.join(tmpdir, "foo", "bar", "1")) ) self.assertTrue( os.path.isfile(os.path.join(tmpdir, "foo", "bar", "2")) ) @unittest.skipIf( sys.platform == "win32", "Python on Windows has a limited os.chmod()." ) def test_extract_file_permissions(self): """archive.extract() preserves file permissions.""" mask = stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO umask = os.umask(0) os.umask(umask) # Restore the original umask. with os.scandir(self.testdir) as entries: for entry in entries: if ( entry.name.startswith("leadpath_") or (entry.name.endswith(".bz2") and not HAS_BZ2) or (entry.name.endswith((".lzma", ".xz")) and not HAS_LZMA) ): continue with self.subTest(entry.name), tempfile.TemporaryDirectory() as tmpdir: archive.extract(entry.path, tmpdir) # An executable file in the archive has executable # permissions. filepath = os.path.join(tmpdir, "executable") self.assertEqual(os.stat(filepath).st_mode & mask, 0o775) # A file is readable even if permission data is missing. filepath = os.path.join(tmpdir, "no_permissions") self.assertEqual(os.stat(filepath).st_mode & mask, 0o666 & ~umask) class TestArchiveInvalid(SimpleTestCase): def test_extract_function_traversal(self): archives_dir = os.path.join(os.path.dirname(__file__), "traversal_archives") tests = [ ("traversal.tar", ".."), ("traversal_absolute.tar", "/tmp/evil.py"), ] if sys.platform == "win32": tests += [ ("traversal_disk_win.tar", "d:evil.py"), ("traversal_disk_win.zip", "d:evil.py"), ] msg = "Archive contains invalid path: '%s'" for entry, invalid_path in tests: with self.subTest(entry), tempfile.TemporaryDirectory() as tmpdir: with self.assertRaisesMessage(SuspiciousOperation, msg % invalid_path): archive.extract(os.path.join(archives_dir, entry), tmpdir) def test_extract_function_traversal_startswith(self): with tempfile.TemporaryDirectory() as tmpdir: base = os.path.abspath(tmpdir) tarfile_handle = tempfile.NamedTemporaryFile(suffix=".zip", delete=False) tar_path = tarfile_handle.name tarfile_handle.close() self.addCleanup(os.remove, tar_path) malicious_member = os.path.join(base + "abc", "evil.txt") with zipfile.ZipFile(tar_path, "w") as zf: zf.writestr(malicious_member, "evil\n") zf.writestr("test.txt", "data\n") with self.assertRaisesMessage( SuspiciousOperation, "Archive contains invalid path" ): archive.extract(tar_path, base)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_html.py
tests/utils_tests/test_html.py
import math import os import sys from datetime import datetime from django.core.exceptions import SuspiciousOperation from django.core.serializers.json import DjangoJSONEncoder from django.test import SimpleTestCase from django.test.utils import override_settings from django.utils.deprecation import RemovedInDjango70Warning from django.utils.functional import lazystr from django.utils.html import ( conditional_escape, escape, escapejs, format_html, format_html_join, html_safe, json_script, linebreaks, smart_urlquote, strip_spaces_between_tags, strip_tags, urlize, ) from django.utils.safestring import mark_safe @override_settings(URLIZE_ASSUME_HTTPS=True) class TestUtilsHtml(SimpleTestCase): def check_output(self, function, value, output=None): """ function(value) equals output. If output is None, function(value) equals value. """ if output is None: output = value self.assertEqual(function(value), output) def test_escape(self): items = ( ("&", "&amp;"), ("<", "&lt;"), (">", "&gt;"), ('"', "&quot;"), ("'", "&#x27;"), ) # Substitution patterns for testing the above items. patterns = ("%s", "asdf%sfdsa", "%s1", "1%sb") for value, output in items: with self.subTest(value=value, output=output): for pattern in patterns: with self.subTest(value=value, output=output, pattern=pattern): self.check_output(escape, pattern % value, pattern % output) self.check_output( escape, lazystr(pattern % value), pattern % output ) # Check repeated values. self.check_output(escape, value * 2, output * 2) # Verify it doesn't double replace &. self.check_output(escape, "<&", "&lt;&amp;") def test_format_html(self): self.assertEqual( format_html( "{} {} {third} {fourth}", "< Dangerous >", mark_safe("<b>safe</b>"), third="< dangerous again", fourth=mark_safe("<i>safe again</i>"), ), "&lt; Dangerous &gt; <b>safe</b> &lt; dangerous again <i>safe again</i>", ) def test_format_html_no_params(self): msg = "args or kwargs must be provided." with self.assertRaisesMessage(TypeError, msg): name = "Adam" self.assertEqual(format_html(f"<i>{name}</i>"), "<i>Adam</i>") def test_format_html_join_with_positional_arguments(self): self.assertEqual( format_html_join( "\n", "<li>{}) {}</li>", [(1, "Emma"), (2, "Matilda")], ), "<li>1) Emma</li>\n<li>2) Matilda</li>", ) def test_format_html_join_with_keyword_arguments(self): self.assertEqual( format_html_join( "\n", "<li>{id}) {text}</li>", [{"id": 1, "text": "Emma"}, {"id": 2, "text": "Matilda"}], ), "<li>1) Emma</li>\n<li>2) Matilda</li>", ) def test_linebreaks(self): items = ( ("para1\n\npara2\r\rpara3", "<p>para1</p>\n\n<p>para2</p>\n\n<p>para3</p>"), ( "para1\nsub1\rsub2\n\npara2", "<p>para1<br>sub1<br>sub2</p>\n\n<p>para2</p>", ), ( "para1\r\n\r\npara2\rsub1\r\rpara4", "<p>para1</p>\n\n<p>para2<br>sub1</p>\n\n<p>para4</p>", ), ("para1\tmore\n\npara2", "<p>para1\tmore</p>\n\n<p>para2</p>"), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(linebreaks, value, output) self.check_output(linebreaks, lazystr(value), output) def test_strip_tags(self): # Python fixed a quadratic-time issue in HTMLParser in 3.13.6, 3.12.12. # The fix slightly changes HTMLParser's output, so tests for # particularly malformed input must handle both old and new results. # The check below is temporary until all supported Python versions and # CI workers include the fix. See: # https://github.com/python/cpython/commit/6eb6c5db min_fixed_security = { (3, 13): (3, 13, 6), (3, 12): (3, 12, 12), } # Similarly, there was a fix for terminating incomplete entities. See: # https://github.com/python/cpython/commit/95296a9d min_fixed_incomplete_entities = { (3, 14): (3, 14, 1), (3, 13): (3, 13, 10), (3, 12): (3, 12, math.inf), # not fixed in 3.12. } major_version = sys.version_info[:2] htmlparser_fixed_security = sys.version_info >= min_fixed_security.get( major_version, major_version ) htmlparser_fixed_incomplete_entities = ( sys.version_info >= min_fixed_incomplete_entities.get(major_version, major_version) ) items = ( ( "<p>See: &#39;&eacute; is an apostrophe followed by e acute</p>", "See: &#39;&eacute; is an apostrophe followed by e acute", ), ( "<p>See: &#x27;&eacute; is an apostrophe followed by e acute</p>", "See: &#x27;&eacute; is an apostrophe followed by e acute", ), ("<adf>a", "a"), ("</adf>a", "a"), ("<asdf><asdf>e", "e"), ("hi, <f x", "hi, <f x"), ("234<235, right?", "234<235, right?"), ("a4<a5 right?", "a4<a5 right?"), ("b7>b2!", "b7>b2!"), ("</fe", "</fe"), ("<x>b<y>", "b"), ("a<p onclick=\"alert('<test>')\">b</p>c", "abc"), ("a<p a >b</p>c", "abc"), ("d<a:b c:d>e</p>f", "def"), ('<strong>foo</strong><a href="http://example.com">bar</a>', "foobar"), # caused infinite loop on Pythons not patched with # https://bugs.python.org/issue20288 ("&gotcha&#;<>", "&gotcha&#;<>"), ("<sc<!-- -->ript>test<<!-- -->/script>", "ript>test"), ( "<script>alert()</script>&h", "alert()&h;" if htmlparser_fixed_incomplete_entities else "alert()h", ), ( "><!" + ("&" * 16000) + "D", ">" if htmlparser_fixed_security else "><!" + ("&" * 16000) + "D", ), ("X<<<<br>br>br>br>X", "XX"), ("<" * 50 + "a>" * 50, ""), ( ">" + "<a" * 500 + "a", ">" if htmlparser_fixed_security else ">" + "<a" * 500 + "a", ), ("<a" * 49 + "a" * 951, "<a" * 49 + "a" * 951), ("<" + "a" * 1_002, "<" + "a" * 1_002), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(strip_tags, value, output) self.check_output(strip_tags, lazystr(value), output) def test_strip_tags_suspicious_operation_max_depth(self): value = "<" * 51 + "a>" * 51, "<a>" with self.assertRaises(SuspiciousOperation): strip_tags(value) def test_strip_tags_suspicious_operation_large_open_tags(self): items = [ ">" + "<a" * 501, "<a" * 50 + "a" * 950, ] for value in items: with self.subTest(value=value): with self.assertRaises(SuspiciousOperation): strip_tags(value) def test_strip_tags_files(self): # Test with more lengthy content (also catching performance # regressions) for filename in ("strip_tags1.html", "strip_tags2.txt"): with self.subTest(filename=filename): path = os.path.join(os.path.dirname(__file__), "files", filename) with open(path) as fp: content = fp.read() start = datetime.now() stripped = strip_tags(content) elapsed = datetime.now() - start self.assertEqual(elapsed.seconds, 0) self.assertIn("Test string that has not been stripped.", stripped) self.assertNotIn("<", stripped) def test_strip_spaces_between_tags(self): # Strings that should come out untouched. items = (" <adf>", "<adf> ", " </adf> ", " <f> x</f>") for value in items: with self.subTest(value=value): self.check_output(strip_spaces_between_tags, value) self.check_output(strip_spaces_between_tags, lazystr(value)) # Strings that have spaces to strip. items = ( ("<d> </d>", "<d></d>"), ("<p>hello </p>\n<p> world</p>", "<p>hello </p><p> world</p>"), ("\n<p>\t</p>\n<p> </p>\n", "\n<p></p><p></p>\n"), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(strip_spaces_between_tags, value, output) self.check_output(strip_spaces_between_tags, lazystr(value), output) def test_escapejs(self): items = ( ( "\"double quotes\" and 'single quotes'", "\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027", ), (r"\ : backslashes, too", "\\u005C : backslashes, too"), ( "and lots of whitespace: \r\n\t\v\f\b", "and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008", ), ( r"<script>and this</script>", "\\u003Cscript\\u003Eand this\\u003C/script\\u003E", ), ( "paragraph separator:\u2029and line separator:\u2028", "paragraph separator:\\u2029and line separator:\\u2028", ), ("`", "\\u0060"), ("\u007f", "\\u007F"), ("\u0080", "\\u0080"), ("\u009f", "\\u009F"), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(escapejs, value, output) self.check_output(escapejs, lazystr(value), output) def test_json_script(self): tests = ( # "<", ">" and "&" are quoted inside JSON strings ( ( "&<>", '<script id="test_id" type="application/json">' '"\\u0026\\u003C\\u003E"</script>', ) ), # "<", ">" and "&" are quoted inside JSON objects ( {"a": "<script>test&ing</script>"}, '<script id="test_id" type="application/json">' '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}' "</script>", ), # Lazy strings are quoted ( lazystr("&<>"), '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"' "</script>", ), ( {"a": lazystr("<script>test&ing</script>")}, '<script id="test_id" type="application/json">' '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}' "</script>", ), ) for arg, expected in tests: with self.subTest(arg=arg): self.assertEqual(json_script(arg, "test_id"), expected) def test_json_script_custom_encoder(self): class CustomDjangoJSONEncoder(DjangoJSONEncoder): def encode(self, o): return '{"hello": "world"}' self.assertHTMLEqual( json_script({}, encoder=CustomDjangoJSONEncoder), '<script type="application/json">{"hello": "world"}</script>', ) def test_json_script_without_id(self): self.assertHTMLEqual( json_script({"key": "value"}), '<script type="application/json">{"key": "value"}</script>', ) def test_smart_urlquote(self): items = ( # IDN is encoded as percent-encoded ("quoted") UTF-8 (#36013). ("http://öäü.com/", "http://%C3%B6%C3%A4%C3%BC.com/"), ("https://faß.example.com", "https://fa%C3%9F.example.com"), ( "http://öäü.com/öäü/", "http://%C3%B6%C3%A4%C3%BC.com/%C3%B6%C3%A4%C3%BC/", ), ( # Valid under IDNA 2008, but was invalid in IDNA 2003. "https://މިހާރު.com", "https://%DE%89%DE%A8%DE%80%DE%A7%DE%83%DE%AA.com", ), ( # Valid under WHATWG URL Specification but not IDNA 2008. "http://👓.ws", "http://%F0%9F%91%93.ws", ), # Pre-encoded IDNA is left unchanged. ("http://xn--iny-zx5a.com/idna2003", "http://xn--iny-zx5a.com/idna2003"), ("http://xn--fa-hia.com/idna2008", "http://xn--fa-hia.com/idna2008"), # Everything unsafe is quoted, !*'();:@&=+$,/?#[]~ is considered # safe as per RFC. ( "http://example.com/path/öäü/", "http://example.com/path/%C3%B6%C3%A4%C3%BC/", ), ("http://example.com/%C3%B6/ä/", "http://example.com/%C3%B6/%C3%A4/"), ("http://example.com/?x=1&y=2+3&z=", "http://example.com/?x=1&y=2+3&z="), ("http://example.com/?x=<>\"'", "http://example.com/?x=%3C%3E%22%27"), ( "http://example.com/?q=http://example.com/?x=1%26q=django", "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3D" "django", ), ( "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3D" "django", "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3D" "django", ), ("http://.www.f oo.bar/", "http://.www.f%20oo.bar/"), ('http://example.com">', "http://example.com%22%3E"), ("http://10.22.1.1/", "http://10.22.1.1/"), ("http://[fd00::1]/", "http://[fd00::1]/"), ) for value, output in items: with self.subTest(value=value, output=output): self.assertEqual(smart_urlquote(value), output) def test_conditional_escape(self): s = "<h1>interop</h1>" self.assertEqual(conditional_escape(s), "&lt;h1&gt;interop&lt;/h1&gt;") self.assertEqual(conditional_escape(mark_safe(s)), s) self.assertEqual(conditional_escape(lazystr(mark_safe(s))), s) def test_html_safe(self): @html_safe class HtmlClass: def __str__(self): return "<h1>I'm a html class!</h1>" html_obj = HtmlClass() self.assertTrue(hasattr(HtmlClass, "__html__")) self.assertTrue(hasattr(html_obj, "__html__")) self.assertEqual(str(html_obj), html_obj.__html__()) def test_html_safe_subclass(self): class BaseClass: def __html__(self): # defines __html__ on its own return "some html content" def __str__(self): return "some non html content" @html_safe class Subclass(BaseClass): def __str__(self): # overrides __str__ and is marked as html_safe return "some html safe content" subclass_obj = Subclass() self.assertEqual(str(subclass_obj), subclass_obj.__html__()) def test_html_safe_defines_html_error(self): msg = "can't apply @html_safe to HtmlClass because it defines __html__()." with self.assertRaisesMessage(ValueError, msg): @html_safe class HtmlClass: def __html__(self): return "<h1>I'm a html class!</h1>" def test_html_safe_doesnt_define_str(self): msg = "can't apply @html_safe to HtmlClass because it doesn't define __str__()." with self.assertRaisesMessage(ValueError, msg): @html_safe class HtmlClass: pass def test_urlize(self): tests = ( ( "Search for google.com/?q=! and see.", 'Search for <a href="https://google.com/?q=">google.com/?q=</a>! and ' "see.", ), ( "Search for google.com/?q=1&lt! and see.", 'Search for <a href="https://google.com/?q=1%3C">google.com/?q=1&lt' "</a>! and see.", ), ( lazystr("Search for google.com/?q=!"), 'Search for <a href="https://google.com/?q=">google.com/?q=</a>!', ), ( "http://www.foo.bar/", '<a href="http://www.foo.bar/">http://www.foo.bar/</a>', ), ( "Look on www.نامه‌ای.com.", "Look on <a " 'href="https://www.%D9%86%D8%A7%D9%85%D9%87%E2%80%8C%D8%A7%DB%8C.com"' ">www.نامه‌ای.com</a>.", ), ("foo@example.com", '<a href="mailto:foo@example.com">foo@example.com</a>'), ( "test@" + "한.글." * 15 + "aaa", '<a href="mailto:test@' + "%ED%95%9C.%EA%B8%80." * 15 + 'aaa">' + "test@" + "한.글." * 15 + "aaa</a>", ), ( # RFC 6068 requires a mailto URI to percent-encode a number of # characters that can appear in <addr-spec>. "yes+this=is&a%valid!email@example.com", '<a href="mailto:yes%2Bthis%3Dis%26a%25valid%21email@example.com"' ">yes+this=is&a%valid!email@example.com</a>", ), ( "foo@faß.example.com", '<a href="mailto:foo@fa%C3%9F.example.com">foo@faß.example.com</a>', ), ( "idna-2008@މިހާރު.example.mv", '<a href="mailto:idna-2008@%DE%89%DE%A8%DE%80%DE%A7%DE%83%DE%AA.ex' 'ample.mv">idna-2008@މިހާރު.example.mv</a>', ), ( "host.djangoproject.com", '<a href="https://host.djangoproject.com">host.djangoproject.com</a>', ), ) for value, output in tests: with self.subTest(value=value): self.assertEqual(urlize(value), output) @override_settings(URLIZE_ASSUME_HTTPS=False) def test_urlize_http_default_warning(self): msg = ( "The default protocol will be changed from HTTP to HTTPS in Django 7.0. " "Set the URLIZE_ASSUME_HTTPS transitional setting to True to opt into " "using HTTPS as the new default protocol." ) with self.assertWarnsMessage(RemovedInDjango70Warning, msg): self.assertEqual( urlize("Visit example.com"), 'Visit <a href="http://example.com">example.com</a>', ) def test_urlize_unchanged_inputs(self): tests = ( ("a" + "@a" * 50000) + "a", # simple_email_re catastrophic test # Unicode domain catastrophic tests. "a@" + "한.글." * 1_000_000 + "a", "http://" + "한.글." * 1_000_000 + "com", "www." + "한.글." * 1_000_000 + "com", ("a" + "." * 1000000) + "a", # trailing_punctuation catastrophic test "foo@", "@foo.com", "foo@.example.com", "foo@localhost", "foo@localhost.", "test@example?;+!.com", "email me@example.com,then I'll respond", "[a link](https://www.djangoproject.com/)", # trim_punctuation catastrophic tests "(" * 100_000 + ":" + ")" * 100_000, "(" * 100_000 + "&:" + ")" * 100_000, "([" * 100_000 + ":" + "])" * 100_000, "[(" * 100_000 + ":" + ")]" * 100_000, "([[" * 100_000 + ":" + "]])" * 100_000, "&:" + ";" * 100_000, "&.;" * 100_000, ".;" * 100_000, "&" + ";:" * 100_000, ) for value in tests: with self.subTest(value=value): self.assertEqual(urlize(value), value)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_module_loading.py
tests/utils_tests/test_module_loading.py
import os import sys import unittest from importlib import import_module from zipimport import zipimporter from django.test import SimpleTestCase, modify_settings from django.test.utils import extend_sys_path from django.utils.module_loading import ( autodiscover_modules, import_string, module_has_submodule, ) class DefaultLoader(unittest.TestCase): def test_loader(self): "Normal module existence can be tested" test_module = import_module("utils_tests.test_module") test_no_submodule = import_module("utils_tests.test_no_submodule") # An importable child self.assertTrue(module_has_submodule(test_module, "good_module")) mod = import_module("utils_tests.test_module.good_module") self.assertEqual(mod.content, "Good Module") # A child that exists, but will generate an import error if loaded self.assertTrue(module_has_submodule(test_module, "bad_module")) with self.assertRaises(ImportError): import_module("utils_tests.test_module.bad_module") # A child that doesn't exist self.assertFalse(module_has_submodule(test_module, "no_such_module")) with self.assertRaises(ImportError): import_module("utils_tests.test_module.no_such_module") # A child that doesn't exist, but is the name of a package on the path self.assertFalse(module_has_submodule(test_module, "django")) with self.assertRaises(ImportError): import_module("utils_tests.test_module.django") # Don't be confused by caching of import misses import types # NOQA: causes attempted import of utils_tests.types self.assertFalse(module_has_submodule(sys.modules["utils_tests"], "types")) # A module which doesn't have a __path__ (so no submodules) self.assertFalse(module_has_submodule(test_no_submodule, "anything")) with self.assertRaises(ImportError): import_module("utils_tests.test_no_submodule.anything") def test_has_sumbodule_with_dotted_path(self): """Nested module existence can be tested.""" test_module = import_module("utils_tests.test_module") # A grandchild that exists. self.assertIs( module_has_submodule(test_module, "child_module.grandchild_module"), True ) # A grandchild that doesn't exist. self.assertIs( module_has_submodule(test_module, "child_module.no_such_module"), False ) # A grandchild whose parent doesn't exist. self.assertIs( module_has_submodule(test_module, "no_such_module.grandchild_module"), False ) # A grandchild whose parent is not a package. self.assertIs( module_has_submodule(test_module, "good_module.no_such_module"), False ) class EggLoader(unittest.TestCase): def setUp(self): self.egg_dir = "%s/eggs" % os.path.dirname(__file__) def tearDown(self): sys.path_importer_cache.clear() sys.modules.pop("egg_module.sub1.sub2.bad_module", None) sys.modules.pop("egg_module.sub1.sub2.good_module", None) sys.modules.pop("egg_module.sub1.sub2", None) sys.modules.pop("egg_module.sub1", None) sys.modules.pop("egg_module.bad_module", None) sys.modules.pop("egg_module.good_module", None) sys.modules.pop("egg_module", None) def test_shallow_loader(self): "Module existence can be tested inside eggs" egg_name = "%s/test_egg.egg" % self.egg_dir with extend_sys_path(egg_name): egg_module = import_module("egg_module") # An importable child self.assertTrue(module_has_submodule(egg_module, "good_module")) mod = import_module("egg_module.good_module") self.assertEqual(mod.content, "Good Module") # A child that exists, but will generate an import error if loaded self.assertTrue(module_has_submodule(egg_module, "bad_module")) with self.assertRaises(ImportError): import_module("egg_module.bad_module") # A child that doesn't exist self.assertFalse(module_has_submodule(egg_module, "no_such_module")) with self.assertRaises(ImportError): import_module("egg_module.no_such_module") def test_deep_loader(self): "Modules deep inside an egg can still be tested for existence" egg_name = "%s/test_egg.egg" % self.egg_dir with extend_sys_path(egg_name): egg_module = import_module("egg_module.sub1.sub2") # An importable child self.assertTrue(module_has_submodule(egg_module, "good_module")) mod = import_module("egg_module.sub1.sub2.good_module") self.assertEqual(mod.content, "Deep Good Module") # A child that exists, but will generate an import error if loaded self.assertTrue(module_has_submodule(egg_module, "bad_module")) with self.assertRaises(ImportError): import_module("egg_module.sub1.sub2.bad_module") # A child that doesn't exist self.assertFalse(module_has_submodule(egg_module, "no_such_module")) with self.assertRaises(ImportError): import_module("egg_module.sub1.sub2.no_such_module") class ModuleImportTests(SimpleTestCase): def test_import_string(self): cls = import_string("django.utils.module_loading.import_string") self.assertEqual(cls, import_string) # Test exceptions raised with self.assertRaises(ImportError): import_string("no_dots_in_path") msg = 'Module "utils_tests" does not define a "unexistent" attribute' with self.assertRaisesMessage(ImportError, msg): import_string("utils_tests.unexistent") @modify_settings(INSTALLED_APPS={"append": "utils_tests.test_module"}) class AutodiscoverModulesTestCase(SimpleTestCase): def tearDown(self): sys.path_importer_cache.clear() sys.modules.pop("utils_tests.test_module.another_bad_module", None) sys.modules.pop("utils_tests.test_module.another_good_module", None) sys.modules.pop("utils_tests.test_module.bad_module", None) sys.modules.pop("utils_tests.test_module.good_module", None) sys.modules.pop("utils_tests.test_module", None) def test_autodiscover_modules_found(self): autodiscover_modules("good_module") def test_autodiscover_modules_not_found(self): autodiscover_modules("missing_module") def test_autodiscover_modules_found_but_bad_module(self): with self.assertRaisesMessage( ImportError, "No module named 'a_package_name_that_does_not_exist'" ): autodiscover_modules("bad_module") def test_autodiscover_modules_several_one_bad_module(self): with self.assertRaisesMessage( ImportError, "No module named 'a_package_name_that_does_not_exist'" ): autodiscover_modules("good_module", "bad_module") def test_autodiscover_modules_several_found(self): autodiscover_modules("good_module", "another_good_module") def test_autodiscover_modules_several_found_with_registry(self): from .test_module import site autodiscover_modules("good_module", "another_good_module", register_to=site) self.assertEqual(site._registry, {"lorem": "ipsum"}) def test_validate_registry_keeps_intact(self): from .test_module import site with self.assertRaisesMessage(Exception, "Some random exception."): autodiscover_modules("another_bad_module", register_to=site) self.assertEqual(site._registry, {}) def test_validate_registry_resets_after_erroneous_module(self): from .test_module import site with self.assertRaisesMessage(Exception, "Some random exception."): autodiscover_modules( "another_good_module", "another_bad_module", register_to=site ) self.assertEqual(site._registry, {"lorem": "ipsum"}) def test_validate_registry_resets_after_missing_module(self): from .test_module import site autodiscover_modules( "does_not_exist", "another_good_module", "does_not_exist2", register_to=site ) self.assertEqual(site._registry, {"lorem": "ipsum"}) class TestFinder: def __init__(self, *args, **kwargs): self.importer = zipimporter(*args, **kwargs) def find_spec(self, path, target=None): return self.importer.find_spec(path, target) class CustomLoader(EggLoader): """The Custom Loader test is exactly the same as the EggLoader, but it uses a custom defined Loader class. Although the EggLoader combines both functions into one class, this isn't required. """ def setUp(self): super().setUp() sys.path_hooks.insert(0, TestFinder) sys.path_importer_cache.clear() def tearDown(self): super().tearDown() sys.path_hooks.pop(0)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_autoreload.py
tests/utils_tests/test_autoreload.py
import contextlib import os import py_compile import shutil import sys import tempfile import threading import time import types import weakref import zipfile import zoneinfo from importlib import import_module from pathlib import Path from subprocess import CompletedProcess from unittest import mock, skip, skipIf import django.__main__ from django.apps.registry import Apps from django.test import SimpleTestCase from django.test.utils import extend_sys_path from django.utils import autoreload from django.utils.autoreload import WatchmanUnavailable from .test_module import __main__ as test_main from .test_module import main_module as test_main_module from .utils import on_macos_with_hfs class TestIterModulesAndFiles(SimpleTestCase): def import_and_cleanup(self, name): import_module(name) self.addCleanup(lambda: sys.path_importer_cache.clear()) self.addCleanup(lambda: sys.modules.pop(name, None)) def clear_autoreload_caches(self): autoreload.iter_modules_and_files.cache_clear() def assertFileFound(self, filename): # Some temp directories are symlinks. Python resolves these fully while # importing. resolved_filename = filename.resolve(strict=True) self.clear_autoreload_caches() # Test uncached access self.assertIn( resolved_filename, list(autoreload.iter_all_python_module_files()) ) # Test cached access self.assertIn( resolved_filename, list(autoreload.iter_all_python_module_files()) ) self.assertEqual(autoreload.iter_modules_and_files.cache_info().hits, 1) def assertFileNotFound(self, filename): resolved_filename = filename.resolve(strict=True) self.clear_autoreload_caches() # Test uncached access self.assertNotIn( resolved_filename, list(autoreload.iter_all_python_module_files()) ) # Test cached access self.assertNotIn( resolved_filename, list(autoreload.iter_all_python_module_files()) ) self.assertEqual(autoreload.iter_modules_and_files.cache_info().hits, 1) def temporary_file(self, filename): dirname = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, dirname) return Path(dirname) / filename def test_paths_are_pathlib_instances(self): for filename in autoreload.iter_all_python_module_files(): self.assertIsInstance(filename, Path) def test_file_added(self): """ When a file is added, it's returned by iter_all_python_module_files(). """ filename = self.temporary_file("test_deleted_removed_module.py") filename.touch() with extend_sys_path(str(filename.parent)): self.import_and_cleanup("test_deleted_removed_module") self.assertFileFound(filename.absolute()) def test_check_errors(self): """ When a file containing an error is imported in a function wrapped by check_errors(), gen_filenames() returns it. """ filename = self.temporary_file("test_syntax_error.py") filename.write_text("Ceci n'est pas du Python.") with extend_sys_path(str(filename.parent)): try: with self.assertRaises(SyntaxError): autoreload.check_errors(import_module)("test_syntax_error") finally: autoreload._exception = None self.assertFileFound(filename) def test_check_errors_catches_all_exceptions(self): """ Since Python may raise arbitrary exceptions when importing code, check_errors() must catch Exception, not just some subclasses. """ filename = self.temporary_file("test_exception.py") filename.write_text("raise Exception") with extend_sys_path(str(filename.parent)): try: with self.assertRaises(Exception): autoreload.check_errors(import_module)("test_exception") finally: autoreload._exception = None self.assertFileFound(filename) def test_zip_reload(self): """ Modules imported from zipped files have their archive location included in the result. """ zip_file = self.temporary_file("zip_import.zip") with zipfile.ZipFile(str(zip_file), "w", zipfile.ZIP_DEFLATED) as zipf: zipf.writestr("test_zipped_file.py", "") with extend_sys_path(str(zip_file)): self.import_and_cleanup("test_zipped_file") self.assertFileFound(zip_file) def test_bytecode_conversion_to_source(self): """.pyc and .pyo files are included in the files list.""" filename = self.temporary_file("test_compiled.py") filename.touch() compiled_file = Path( py_compile.compile(str(filename), str(filename.with_suffix(".pyc"))) ) filename.unlink() with extend_sys_path(str(compiled_file.parent)): self.import_and_cleanup("test_compiled") self.assertFileFound(compiled_file) def test_weakref_in_sys_module(self): """iter_all_python_module_file() ignores weakref modules.""" time_proxy = weakref.proxy(time) sys.modules["time_proxy"] = time_proxy self.addCleanup(lambda: sys.modules.pop("time_proxy", None)) list(autoreload.iter_all_python_module_files()) # No crash. def test_module_without_spec(self): module = types.ModuleType("test_module") del module.__spec__ self.assertEqual( autoreload.iter_modules_and_files((module,), frozenset()), frozenset() ) def test_main_module_is_resolved(self): main_module = sys.modules["__main__"] self.assertFileFound(Path(main_module.__file__)) def test_main_module_without_file_is_not_resolved(self): fake_main = types.ModuleType("__main__") self.assertEqual( autoreload.iter_modules_and_files((fake_main,), frozenset()), frozenset() ) def test_path_with_embedded_null_bytes(self): for path in ( "embedded_null_byte\x00.py", "di\x00rectory/embedded_null_byte.py", ): with self.subTest(path=path): self.assertEqual( autoreload.iter_modules_and_files((), frozenset([path])), frozenset(), ) class TestChildArguments(SimpleTestCase): @mock.patch.dict(sys.modules, {"__main__": django.__main__}) @mock.patch("sys.argv", [django.__main__.__file__, "runserver"]) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {}) def test_run_as_module(self): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, "-m", "django", "runserver"], ) @mock.patch.dict(sys.modules, {"__main__": test_main}) @mock.patch("sys.argv", [test_main.__file__, "runserver"]) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {}) def test_run_as_non_django_module(self): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, "-m", "utils_tests.test_module", "runserver"], ) @mock.patch.dict(sys.modules, {"__main__": test_main_module}) @mock.patch("sys.argv", [test_main.__file__, "runserver"]) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {}) def test_run_as_non_django_module_non_package(self): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, "-m", "utils_tests.test_module.main_module", "runserver"], ) @mock.patch("__main__.__spec__", None) @mock.patch("sys.argv", [__file__, "runserver"]) @mock.patch("sys.warnoptions", ["error"]) @mock.patch("sys._xoptions", {}) def test_warnoptions(self): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, "-Werror", __file__, "runserver"], ) @mock.patch("sys.argv", [__file__, "runserver"]) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {"utf8": True, "a": "b"}) def test_xoptions(self): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, "-Xutf8", "-Xa=b", __file__, "runserver"], ) @mock.patch("__main__.__spec__", None) @mock.patch("sys.warnoptions", []) def test_exe_fallback(self): with tempfile.TemporaryDirectory() as tmpdir: exe_path = Path(tmpdir) / "django-admin.exe" exe_path.touch() with mock.patch("sys.argv", [exe_path.with_suffix(""), "runserver"]): self.assertEqual( autoreload.get_child_arguments(), [exe_path, "runserver"] ) @mock.patch("sys.warnoptions", []) @mock.patch.dict(sys.modules, {"__main__": django.__main__}) def test_use_exe_when_main_spec(self): with tempfile.TemporaryDirectory() as tmpdir: exe_path = Path(tmpdir) / "django-admin.exe" exe_path.touch() with mock.patch("sys.argv", [exe_path.with_suffix(""), "runserver"]): self.assertEqual( autoreload.get_child_arguments(), [exe_path, "runserver"] ) @mock.patch("__main__.__spec__", None) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {}) def test_entrypoint_fallback(self): with tempfile.TemporaryDirectory() as tmpdir: script_path = Path(tmpdir) / "django-admin-script.py" script_path.touch() with mock.patch( "sys.argv", [script_path.with_name("django-admin"), "runserver"] ): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, script_path, "runserver"], ) @mock.patch("__main__.__spec__", None) @mock.patch("sys.argv", ["does-not-exist", "runserver"]) @mock.patch("sys.warnoptions", []) def test_raises_runtimeerror(self): msg = "Script does-not-exist does not exist." with self.assertRaisesMessage(RuntimeError, msg): autoreload.get_child_arguments() @mock.patch("sys.argv", [__file__, "runserver"]) @mock.patch("sys.warnoptions", []) @mock.patch("sys._xoptions", {}) def test_module_no_spec(self): module = types.ModuleType("test_module") del module.__spec__ with mock.patch.dict(sys.modules, {"__main__": module}): self.assertEqual( autoreload.get_child_arguments(), [sys.executable, __file__, "runserver"], ) class TestUtilities(SimpleTestCase): def test_is_django_module(self): for module, expected in ((zoneinfo, False), (sys, False), (autoreload, True)): with self.subTest(module=module): self.assertIs(autoreload.is_django_module(module), expected) def test_is_django_path(self): for module, expected in ( (zoneinfo.__file__, False), (contextlib.__file__, False), (autoreload.__file__, True), ): with self.subTest(module=module): self.assertIs(autoreload.is_django_path(module), expected) class TestCommonRoots(SimpleTestCase): def test_common_roots(self): paths = ( Path("/first/second"), Path("/first/second/third"), Path("/first/"), Path("/root/first/"), ) results = autoreload.common_roots(paths) self.assertCountEqual(results, [Path("/first/"), Path("/root/first/")]) class TestSysPathDirectories(SimpleTestCase): def setUp(self): _directory = tempfile.TemporaryDirectory() self.addCleanup(_directory.cleanup) self.directory = Path(_directory.name).resolve(strict=True).absolute() self.file = self.directory / "test" self.file.touch() def test_sys_paths_with_directories(self): with extend_sys_path(str(self.file)): paths = list(autoreload.sys_path_directories()) self.assertIn(self.file.parent, paths) def test_sys_paths_non_existing(self): nonexistent_file = Path(self.directory.name) / "does_not_exist" with extend_sys_path(str(nonexistent_file)): paths = list(autoreload.sys_path_directories()) self.assertNotIn(nonexistent_file, paths) self.assertNotIn(nonexistent_file.parent, paths) def test_sys_paths_absolute(self): paths = list(autoreload.sys_path_directories()) self.assertTrue(all(p.is_absolute() for p in paths)) def test_sys_paths_directories(self): with extend_sys_path(str(self.directory)): paths = list(autoreload.sys_path_directories()) self.assertIn(self.directory, paths) class GetReloaderTests(SimpleTestCase): @mock.patch("django.utils.autoreload.WatchmanReloader") def test_watchman_unavailable(self, mocked_watchman): mocked_watchman.check_availability.side_effect = WatchmanUnavailable self.assertIsInstance(autoreload.get_reloader(), autoreload.StatReloader) @mock.patch.object(autoreload.WatchmanReloader, "check_availability") def test_watchman_available(self, mocked_available): # If WatchmanUnavailable isn't raised, Watchman will be chosen. mocked_available.return_value = None result = autoreload.get_reloader() self.assertIsInstance(result, autoreload.WatchmanReloader) class RunWithReloaderTests(SimpleTestCase): @mock.patch.dict(os.environ, {autoreload.DJANGO_AUTORELOAD_ENV: "true"}) @mock.patch("django.utils.autoreload.get_reloader") def test_swallows_keyboard_interrupt(self, mocked_get_reloader): mocked_get_reloader.side_effect = KeyboardInterrupt() autoreload.run_with_reloader(lambda: None) # No exception @mock.patch.dict(os.environ, {autoreload.DJANGO_AUTORELOAD_ENV: "false"}) @mock.patch("django.utils.autoreload.restart_with_reloader") def test_calls_sys_exit(self, mocked_restart_reloader): mocked_restart_reloader.return_value = 1 with self.assertRaises(SystemExit) as exc: autoreload.run_with_reloader(lambda: None) self.assertEqual(exc.exception.code, 1) @mock.patch.dict(os.environ, {autoreload.DJANGO_AUTORELOAD_ENV: "true"}) @mock.patch("django.utils.autoreload.start_django") @mock.patch("django.utils.autoreload.get_reloader") def test_calls_start_django(self, mocked_reloader, mocked_start_django): mocked_reloader.return_value = mock.sentinel.RELOADER autoreload.run_with_reloader(mock.sentinel.METHOD) self.assertEqual(mocked_start_django.call_count, 1) self.assertSequenceEqual( mocked_start_django.call_args[0], [mock.sentinel.RELOADER, mock.sentinel.METHOD], ) class StartDjangoTests(SimpleTestCase): @mock.patch("django.utils.autoreload.ensure_echo_on") def test_echo_on_called(self, mocked_echo): fake_reloader = mock.MagicMock() autoreload.start_django(fake_reloader, lambda: None) self.assertEqual(mocked_echo.call_count, 1) @mock.patch("django.utils.autoreload.check_errors") def test_check_errors_called(self, mocked_check_errors): fake_method = mock.MagicMock(return_value=None) fake_reloader = mock.MagicMock() autoreload.start_django(fake_reloader, fake_method) self.assertCountEqual(mocked_check_errors.call_args[0], [fake_method]) @mock.patch("threading.Thread") @mock.patch("django.utils.autoreload.check_errors") def test_starts_thread_with_args(self, mocked_check_errors, mocked_thread): fake_reloader = mock.MagicMock() fake_main_func = mock.MagicMock() fake_thread = mock.MagicMock() mocked_check_errors.return_value = fake_main_func mocked_thread.return_value = fake_thread autoreload.start_django(fake_reloader, fake_main_func, 123, abc=123) self.assertEqual(mocked_thread.call_count, 1) self.assertEqual( mocked_thread.call_args[1], { "target": fake_main_func, "args": (123,), "kwargs": {"abc": 123}, "name": "django-main-thread", }, ) self.assertIs(fake_thread.daemon, True) self.assertTrue(fake_thread.start.called) class TestCheckErrors(SimpleTestCase): def test_mutates_error_files(self): fake_method = mock.MagicMock(side_effect=RuntimeError()) wrapped = autoreload.check_errors(fake_method) with mock.patch.object(autoreload, "_error_files") as mocked_error_files: try: with self.assertRaises(RuntimeError): wrapped() finally: autoreload._exception = None self.assertEqual(mocked_error_files.append.call_count, 1) class TestRaiseLastException(SimpleTestCase): @mock.patch("django.utils.autoreload._exception", None) def test_no_exception(self): # Should raise no exception if _exception is None autoreload.raise_last_exception() def test_raises_exception(self): class MyException(Exception): pass # Create an exception try: raise MyException("Test Message") except MyException: exc_info = sys.exc_info() with mock.patch("django.utils.autoreload._exception", exc_info): with self.assertRaisesMessage(MyException, "Test Message"): autoreload.raise_last_exception() def test_raises_custom_exception(self): class MyException(Exception): def __init__(self, msg, extra_context): super().__init__(msg) self.extra_context = extra_context # Create an exception. try: raise MyException("Test Message", "extra context") except MyException: exc_info = sys.exc_info() with mock.patch("django.utils.autoreload._exception", exc_info): with self.assertRaisesMessage(MyException, "Test Message"): autoreload.raise_last_exception() def test_raises_exception_with_context(self): try: raise Exception(2) except Exception as e: try: raise Exception(1) from e except Exception: exc_info = sys.exc_info() with mock.patch("django.utils.autoreload._exception", exc_info): with self.assertRaises(Exception) as cm: autoreload.raise_last_exception() self.assertEqual(cm.exception.args[0], 1) self.assertEqual(cm.exception.__cause__.args[0], 2) class RestartWithReloaderTests(SimpleTestCase): executable = "/usr/bin/python" def patch_autoreload(self, argv): patch_call = mock.patch( "django.utils.autoreload.subprocess.run", return_value=CompletedProcess(argv, 0), ) patches = [ mock.patch("django.utils.autoreload.sys.argv", argv), mock.patch("django.utils.autoreload.sys.executable", self.executable), mock.patch("django.utils.autoreload.sys.warnoptions", ["all"]), mock.patch("django.utils.autoreload.sys._xoptions", {}), ] for p in patches: p.start() self.addCleanup(p.stop) mock_call = patch_call.start() self.addCleanup(patch_call.stop) return mock_call def test_manage_py(self): with tempfile.TemporaryDirectory() as temp_dir: script = Path(temp_dir) / "manage.py" script.touch() argv = [str(script), "runserver"] mock_call = self.patch_autoreload(argv) with mock.patch("__main__.__spec__", None): autoreload.restart_with_reloader() self.assertEqual(mock_call.call_count, 1) self.assertEqual( mock_call.call_args[0][0], [self.executable, "-Wall"] + argv, ) def test_python_m_django(self): main = "/usr/lib/pythonX.Y/site-packages/django/__main__.py" argv = [main, "runserver"] mock_call = self.patch_autoreload(argv) with mock.patch("django.__main__.__file__", main): with mock.patch.dict(sys.modules, {"__main__": django.__main__}): autoreload.restart_with_reloader() self.assertEqual(mock_call.call_count, 1) self.assertEqual( mock_call.call_args[0][0], [self.executable, "-Wall", "-m", "django"] + argv[1:], ) def test_propagates_unbuffered_from_parent(self): for args in ("-u", "-Iuv"): with self.subTest(args=args): with mock.patch.dict(os.environ, {}, clear=True): with tempfile.TemporaryDirectory() as d: script = Path(d) / "manage.py" script.touch() mock_call = self.patch_autoreload([str(script), "runserver"]) with ( mock.patch("__main__.__spec__", None), mock.patch.object( autoreload.sys, "orig_argv", [self.executable, args, str(script), "runserver"], ), ): autoreload.restart_with_reloader() env = mock_call.call_args.kwargs["env"] self.assertEqual(env.get("PYTHONUNBUFFERED"), "1") def test_does_not_propagate_unbuffered_from_parent(self): for args in ( "-Xdev", "-Xfaulthandler", "--user", "-Wall", "-Wdefault", "-Wignore::UserWarning", ): with self.subTest(args=args): with mock.patch.dict(os.environ, {}, clear=True): with tempfile.TemporaryDirectory() as d: script = Path(d) / "manage.py" script.touch() mock_call = self.patch_autoreload([str(script), "runserver"]) with ( mock.patch("__main__.__spec__", None), mock.patch.object( autoreload.sys, "orig_argv", [self.executable, args, str(script), "runserver"], ), ): autoreload.restart_with_reloader() env = mock_call.call_args.kwargs["env"] self.assertIsNone(env.get("PYTHONUNBUFFERED")) class ReloaderTests(SimpleTestCase): RELOADER_CLS = None def setUp(self): _tempdir = tempfile.TemporaryDirectory() self.tempdir = Path(_tempdir.name).resolve(strict=True).absolute() self.existing_file = self.ensure_file(self.tempdir / "test.py") self.nonexistent_file = (self.tempdir / "does_not_exist.py").absolute() self.reloader = self.RELOADER_CLS() self.addCleanup(self.reloader.stop) self.addCleanup(_tempdir.cleanup) def ensure_file(self, path): path.parent.mkdir(exist_ok=True, parents=True) path.touch() # On Linux and Windows updating the mtime of a file using touch() will # set a timestamp value that is in the past, as the time value for the # last kernel tick is used rather than getting the correct absolute # time. # To make testing simpler set the mtime to be the observed time when # this function is called. self.set_mtime(path, time.time()) return path.absolute() def set_mtime(self, fp, value): os.utime(str(fp), (value, value)) def increment_mtime(self, fp, by=1): current_time = time.time() self.set_mtime(fp, current_time + by) @contextlib.contextmanager def tick_twice(self): ticker = self.reloader.tick() next(ticker) yield next(ticker) class IntegrationTests: @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_glob(self, mocked_modules, notify_mock): non_py_file = self.ensure_file(self.tempdir / "non_py_file") self.reloader.watch_dir(self.tempdir, "*.py") with self.tick_twice(): self.increment_mtime(non_py_file) self.increment_mtime(self.existing_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [self.existing_file]) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_multiple_globs(self, mocked_modules, notify_mock): self.ensure_file(self.tempdir / "x.test") self.reloader.watch_dir(self.tempdir, "*.py") self.reloader.watch_dir(self.tempdir, "*.test") with self.tick_twice(): self.increment_mtime(self.existing_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [self.existing_file]) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_overlapping_globs(self, mocked_modules, notify_mock): self.reloader.watch_dir(self.tempdir, "*.py") self.reloader.watch_dir(self.tempdir, "*.p*") with self.tick_twice(): self.increment_mtime(self.existing_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [self.existing_file]) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_glob_recursive(self, mocked_modules, notify_mock): non_py_file = self.ensure_file(self.tempdir / "dir" / "non_py_file") py_file = self.ensure_file(self.tempdir / "dir" / "file.py") self.reloader.watch_dir(self.tempdir, "**/*.py") with self.tick_twice(): self.increment_mtime(non_py_file) self.increment_mtime(py_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [py_file]) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_multiple_recursive_globs(self, mocked_modules, notify_mock): non_py_file = self.ensure_file(self.tempdir / "dir" / "test.txt") py_file = self.ensure_file(self.tempdir / "dir" / "file.py") self.reloader.watch_dir(self.tempdir, "**/*.txt") self.reloader.watch_dir(self.tempdir, "**/*.py") with self.tick_twice(): self.increment_mtime(non_py_file) self.increment_mtime(py_file) self.assertEqual(notify_mock.call_count, 2) self.assertCountEqual( notify_mock.call_args_list, [mock.call(py_file), mock.call(non_py_file)] ) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_nested_glob_recursive(self, mocked_modules, notify_mock): inner_py_file = self.ensure_file(self.tempdir / "dir" / "file.py") self.reloader.watch_dir(self.tempdir, "**/*.py") self.reloader.watch_dir(inner_py_file.parent, "**/*.py") with self.tick_twice(): self.increment_mtime(inner_py_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [inner_py_file]) @mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed") @mock.patch( "django.utils.autoreload.iter_all_python_module_files", return_value=frozenset() ) def test_overlapping_glob_recursive(self, mocked_modules, notify_mock): py_file = self.ensure_file(self.tempdir / "dir" / "file.py") self.reloader.watch_dir(self.tempdir, "**/*.p*") self.reloader.watch_dir(self.tempdir, "**/*.py*") with self.tick_twice(): self.increment_mtime(py_file) self.assertEqual(notify_mock.call_count, 1) self.assertCountEqual(notify_mock.call_args[0], [py_file]) class BaseReloaderTests(ReloaderTests): RELOADER_CLS = autoreload.BaseReloader def test_watch_dir_with_unresolvable_path(self): path = Path("unresolvable_directory") with mock.patch.object(Path, "absolute", side_effect=FileNotFoundError): self.reloader.watch_dir(path, "**/*.mo") self.assertEqual(list(self.reloader.directory_globs), []) def test_watch_with_glob(self): self.reloader.watch_dir(self.tempdir, "*.py") watched_files = list(self.reloader.watched_files()) self.assertIn(self.existing_file, watched_files) def test_watch_files_with_recursive_glob(self): inner_file = self.ensure_file(self.tempdir / "test" / "test.py") self.reloader.watch_dir(self.tempdir, "**/*.py") watched_files = list(self.reloader.watched_files()) self.assertIn(self.existing_file, watched_files) self.assertIn(inner_file, watched_files) def test_run_loop_catches_stopiteration(self): def mocked_tick(): yield with mock.patch.object(self.reloader, "tick", side_effect=mocked_tick) as tick: self.reloader.run_loop() self.assertEqual(tick.call_count, 1) def test_run_loop_stop_and_return(self): def mocked_tick(*args): yield self.reloader.stop() return # Raises StopIteration with mock.patch.object(self.reloader, "tick", side_effect=mocked_tick) as tick: self.reloader.run_loop() self.assertEqual(tick.call_count, 1) def test_wait_for_apps_ready_checks_for_exception(self): app_reg = Apps() app_reg.ready_event.set() # thread.is_alive() is False if it's not started. dead_thread = threading.Thread() self.assertFalse(self.reloader.wait_for_apps_ready(app_reg, dead_thread)) def test_wait_for_apps_ready_without_exception(self): app_reg = Apps() app_reg.ready_event.set() thread = mock.MagicMock() thread.is_alive.return_value = True self.assertTrue(self.reloader.wait_for_apps_ready(app_reg, thread)) def skip_unless_watchman_available(): try: autoreload.WatchmanReloader.check_availability() except WatchmanUnavailable as e: return skip("Watchman unavailable: %s" % e) return lambda func: func @skip_unless_watchman_available() class WatchmanReloaderTests(ReloaderTests, IntegrationTests): RELOADER_CLS = autoreload.WatchmanReloader def setUp(self): super().setUp() # Shorten the timeout to speed up tests. self.reloader.client_timeout = int(os.environ.get("DJANGO_WATCHMAN_TIMEOUT", 2)) def test_watch_glob_ignores_non_existing_directories_two_levels(self): with mock.patch.object(self.reloader, "_subscribe") as mocked_subscribe: self.reloader._watch_glob(self.tempdir / "does_not_exist" / "more", ["*"]) self.assertFalse(mocked_subscribe.called) def test_watch_glob_uses_existing_parent_directories(self): with mock.patch.object(self.reloader, "_subscribe") as mocked_subscribe: self.reloader._watch_glob(self.tempdir / "does_not_exist", ["*"]) self.assertSequenceEqual( mocked_subscribe.call_args[0], [ self.tempdir, "glob-parent-does_not_exist:%s" % self.tempdir, ["anyof", ["match", "does_not_exist/*", "wholename"]], ], ) def test_watch_glob_multiple_patterns(self): with mock.patch.object(self.reloader, "_subscribe") as mocked_subscribe:
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_feedgenerator.py
tests/utils_tests/test_feedgenerator.py
import datetime from unittest import mock from django.test import SimpleTestCase from django.utils import feedgenerator from django.utils.functional import SimpleLazyObject from django.utils.timezone import get_fixed_timezone class FeedgeneratorTests(SimpleTestCase): """ Tests for the low-level syndication feed framework. """ def test_get_tag_uri(self): """ get_tag_uri() correctly generates TagURIs. """ self.assertEqual( feedgenerator.get_tag_uri( "http://example.org/foo/bar#headline", datetime.date(2004, 10, 25) ), "tag:example.org,2004-10-25:/foo/bar/headline", ) def test_get_tag_uri_with_port(self): """ get_tag_uri() correctly generates TagURIs from URLs with port numbers. """ self.assertEqual( feedgenerator.get_tag_uri( "http://www.example.org:8000/2008/11/14/django#headline", datetime.datetime(2008, 11, 14, 13, 37, 0), ), "tag:www.example.org,2008-11-14:/2008/11/14/django/headline", ) def test_rfc2822_date(self): """ rfc2822_date() correctly formats datetime objects. """ self.assertEqual( feedgenerator.rfc2822_date(datetime.datetime(2008, 11, 14, 13, 37, 0)), "Fri, 14 Nov 2008 13:37:00 -0000", ) def test_rfc2822_date_with_timezone(self): """ rfc2822_date() correctly formats datetime objects with tzinfo. """ self.assertEqual( feedgenerator.rfc2822_date( datetime.datetime( 2008, 11, 14, 13, 37, 0, tzinfo=get_fixed_timezone(60) ) ), "Fri, 14 Nov 2008 13:37:00 +0100", ) def test_rfc2822_date_without_time(self): """ rfc2822_date() correctly formats date objects. """ self.assertEqual( feedgenerator.rfc2822_date(datetime.date(2008, 11, 14)), "Fri, 14 Nov 2008 00:00:00 -0000", ) def test_rfc3339_date(self): """ rfc3339_date() correctly formats datetime objects. """ self.assertEqual( feedgenerator.rfc3339_date(datetime.datetime(2008, 11, 14, 13, 37, 0)), "2008-11-14T13:37:00Z", ) def test_rfc3339_date_with_timezone(self): """ rfc3339_date() correctly formats datetime objects with tzinfo. """ self.assertEqual( feedgenerator.rfc3339_date( datetime.datetime( 2008, 11, 14, 13, 37, 0, tzinfo=get_fixed_timezone(120) ) ), "2008-11-14T13:37:00+02:00", ) def test_rfc3339_date_without_time(self): """ rfc3339_date() correctly formats date objects. """ self.assertEqual( feedgenerator.rfc3339_date(datetime.date(2008, 11, 14)), "2008-11-14T00:00:00Z", ) def test_atom1_mime_type(self): """ Atom MIME type has UTF8 Charset parameter set """ atom_feed = feedgenerator.Atom1Feed("title", "link", "description") self.assertEqual(atom_feed.content_type, "application/atom+xml; charset=utf-8") def test_rss_mime_type(self): """ RSS MIME type has UTF8 Charset parameter set """ rss_feed = feedgenerator.Rss201rev2Feed("title", "link", "description") self.assertEqual(rss_feed.content_type, "application/rss+xml; charset=utf-8") # Two regression tests for #14202 def test_feed_without_feed_url_gets_rendered_without_atom_link(self): feed = feedgenerator.Rss201rev2Feed("title", "/link/", "descr") self.assertIsNone(feed.feed["feed_url"]) feed_content = feed.writeString("utf-8") self.assertNotIn("<atom:link", feed_content) self.assertNotIn('href="/feed/"', feed_content) self.assertNotIn('rel="self"', feed_content) def test_feed_with_feed_url_gets_rendered_with_atom_link(self): feed = feedgenerator.Rss201rev2Feed( "title", "/link/", "descr", feed_url="/feed/" ) self.assertEqual(feed.feed["feed_url"], "/feed/") feed_content = feed.writeString("utf-8") self.assertIn("<atom:link", feed_content) self.assertIn('href="/feed/"', feed_content) self.assertIn('rel="self"', feed_content) def test_atom_add_item(self): # Not providing any optional arguments to Atom1Feed.add_item() feed = feedgenerator.Atom1Feed("title", "/link/", "descr") feed.add_item("item_title", "item_link", "item_description") feed.writeString("utf-8") def test_deterministic_attribute_order(self): feed = feedgenerator.Atom1Feed("title", "/link/", "desc") feed_content = feed.writeString("utf-8") self.assertIn('href="/link/" rel="alternate"', feed_content) def test_latest_post_date_returns_utc_time(self): for use_tz in (True, False): with self.settings(USE_TZ=use_tz): rss_feed = feedgenerator.Rss201rev2Feed("title", "link", "description") self.assertEqual( rss_feed.latest_post_date().tzinfo, datetime.UTC, ) def test_stylesheet_keeps_lazy_urls(self): m = mock.Mock(return_value="test.css") stylesheet = feedgenerator.Stylesheet(SimpleLazyObject(m)) m.assert_not_called() self.assertEqual( str(stylesheet), 'href="test.css" media="screen" type="text/css"' ) m.assert_called_once() def test_stylesheet_attribute_escaping(self): style = feedgenerator.Stylesheet( url='http://example.com/style.css?foo="bar"&baz=<>', mimetype='text/css; charset="utf-8"', media='screen and (max-width: "600px")', ) self.assertEqual( str(style), 'href="http://example.com/style.css?foo=%22bar%22&amp;baz=%3C%3E" ' 'media="screen and (max-width: &quot;600px&quot;)" ' 'type="text/css; charset=&quot;utf-8&quot;"', )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_timezone.py
tests/utils_tests/test_timezone.py
import datetime import zoneinfo from unittest import mock from django.test import SimpleTestCase, override_settings from django.utils import timezone PARIS_ZI = zoneinfo.ZoneInfo("Europe/Paris") EAT = timezone.get_fixed_timezone(180) # Africa/Nairobi ICT = timezone.get_fixed_timezone(420) # Asia/Bangkok UTC = datetime.UTC class TimezoneTests(SimpleTestCase): def test_default_timezone_is_zoneinfo(self): self.assertIsInstance(timezone.get_default_timezone(), zoneinfo.ZoneInfo) def test_now(self): with override_settings(USE_TZ=True): self.assertTrue(timezone.is_aware(timezone.now())) with override_settings(USE_TZ=False): self.assertTrue(timezone.is_naive(timezone.now())) def test_localdate(self): naive = datetime.datetime(2015, 1, 1, 0, 0, 1) with self.assertRaisesMessage( ValueError, "localtime() cannot be applied to a naive datetime" ): timezone.localdate(naive) with self.assertRaisesMessage( ValueError, "localtime() cannot be applied to a naive datetime" ): timezone.localdate(naive, timezone=EAT) aware = datetime.datetime(2015, 1, 1, 0, 0, 1, tzinfo=ICT) self.assertEqual( timezone.localdate(aware, timezone=EAT), datetime.date(2014, 12, 31) ) with timezone.override(EAT): self.assertEqual(timezone.localdate(aware), datetime.date(2014, 12, 31)) with mock.patch("django.utils.timezone.now", return_value=aware): self.assertEqual( timezone.localdate(timezone=EAT), datetime.date(2014, 12, 31) ) with timezone.override(EAT): self.assertEqual(timezone.localdate(), datetime.date(2014, 12, 31)) def test_override(self): default = timezone.get_default_timezone() try: timezone.activate(ICT) with timezone.override(EAT): self.assertIs(EAT, timezone.get_current_timezone()) self.assertIs(ICT, timezone.get_current_timezone()) with timezone.override(None): self.assertIs(default, timezone.get_current_timezone()) self.assertIs(ICT, timezone.get_current_timezone()) timezone.deactivate() with timezone.override(EAT): self.assertIs(EAT, timezone.get_current_timezone()) self.assertIs(default, timezone.get_current_timezone()) with timezone.override(None): self.assertIs(default, timezone.get_current_timezone()) self.assertIs(default, timezone.get_current_timezone()) finally: timezone.deactivate() def test_override_decorator(self): default = timezone.get_default_timezone() @timezone.override(EAT) def func_tz_eat(): self.assertIs(EAT, timezone.get_current_timezone()) @timezone.override(None) def func_tz_none(): self.assertIs(default, timezone.get_current_timezone()) try: timezone.activate(ICT) func_tz_eat() self.assertIs(ICT, timezone.get_current_timezone()) func_tz_none() self.assertIs(ICT, timezone.get_current_timezone()) timezone.deactivate() func_tz_eat() self.assertIs(default, timezone.get_current_timezone()) func_tz_none() self.assertIs(default, timezone.get_current_timezone()) finally: timezone.deactivate() def test_override_string_tz(self): with timezone.override("Asia/Bangkok"): self.assertEqual(timezone.get_current_timezone_name(), "Asia/Bangkok") def test_override_fixed_offset(self): with timezone.override(datetime.timezone(datetime.timedelta(), "tzname")): self.assertEqual(timezone.get_current_timezone_name(), "tzname") def test_activate_invalid_timezone(self): with self.assertRaisesMessage(ValueError, "Invalid timezone: None"): timezone.activate(None) def test_is_aware(self): self.assertTrue( timezone.is_aware(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)) ) self.assertFalse(timezone.is_aware(datetime.datetime(2011, 9, 1, 13, 20, 30))) def test_is_naive(self): self.assertFalse( timezone.is_naive(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)) ) self.assertTrue(timezone.is_naive(datetime.datetime(2011, 9, 1, 13, 20, 30))) def test_make_aware(self): self.assertEqual( timezone.make_aware(datetime.datetime(2011, 9, 1, 13, 20, 30), EAT), datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), ) with self.assertRaises(ValueError): timezone.make_aware( datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), EAT ) def test_make_naive(self): self.assertEqual( timezone.make_naive( datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), EAT ), datetime.datetime(2011, 9, 1, 13, 20, 30), ) self.assertEqual( timezone.make_naive( datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT), EAT ), datetime.datetime(2011, 9, 1, 13, 20, 30), ) with self.assertRaisesMessage( ValueError, "make_naive() cannot be applied to a naive datetime" ): timezone.make_naive(datetime.datetime(2011, 9, 1, 13, 20, 30), EAT) def test_make_naive_no_tz(self): self.assertEqual( timezone.make_naive(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)), datetime.datetime(2011, 9, 1, 5, 20, 30), ) def test_make_aware_no_tz(self): self.assertEqual( timezone.make_aware(datetime.datetime(2011, 9, 1, 13, 20, 30)), datetime.datetime( 2011, 9, 1, 13, 20, 30, tzinfo=timezone.get_fixed_timezone(-300) ), ) def test_make_aware2(self): CEST = datetime.timezone(datetime.timedelta(hours=2), "CEST") self.assertEqual( timezone.make_aware(datetime.datetime(2011, 9, 1, 12, 20, 30), PARIS_ZI), datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=CEST), ) with self.assertRaises(ValueError): timezone.make_aware( datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=PARIS_ZI), PARIS_ZI ) def test_make_naive_zoneinfo(self): self.assertEqual( timezone.make_naive( datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=PARIS_ZI), PARIS_ZI ), datetime.datetime(2011, 9, 1, 12, 20, 30), ) self.assertEqual( timezone.make_naive( datetime.datetime(2011, 9, 1, 12, 20, 30, fold=1, tzinfo=PARIS_ZI), PARIS_ZI, ), datetime.datetime(2011, 9, 1, 12, 20, 30, fold=1), ) def test_make_aware_zoneinfo_ambiguous(self): # 2:30 happens twice, once before DST ends and once after ambiguous = datetime.datetime(2015, 10, 25, 2, 30) std = timezone.make_aware(ambiguous.replace(fold=1), timezone=PARIS_ZI) dst = timezone.make_aware(ambiguous, timezone=PARIS_ZI) self.assertEqual( std.astimezone(UTC) - dst.astimezone(UTC), datetime.timedelta(hours=1) ) self.assertEqual(std.utcoffset(), datetime.timedelta(hours=1)) self.assertEqual(dst.utcoffset(), datetime.timedelta(hours=2)) def test_make_aware_zoneinfo_non_existent(self): # 2:30 never happened due to DST non_existent = datetime.datetime(2015, 3, 29, 2, 30) std = timezone.make_aware(non_existent, PARIS_ZI) dst = timezone.make_aware(non_existent.replace(fold=1), PARIS_ZI) self.assertEqual( std.astimezone(UTC) - dst.astimezone(UTC), datetime.timedelta(hours=1) ) self.assertEqual(std.utcoffset(), datetime.timedelta(hours=1)) self.assertEqual(dst.utcoffset(), datetime.timedelta(hours=2)) def test_get_timezone_name(self): """ The _get_timezone_name() helper must return the offset for fixed offset timezones, for usage with Trunc DB functions. The datetime.timezone examples show the current behavior. """ tests = [ # datetime.timezone, fixed offset with and without `name`. (datetime.timezone(datetime.timedelta(hours=10)), "UTC+10:00"), ( datetime.timezone(datetime.timedelta(hours=10), name="Etc/GMT-10"), "Etc/GMT-10", ), # zoneinfo, named and fixed offset. (zoneinfo.ZoneInfo("Europe/Madrid"), "Europe/Madrid"), (zoneinfo.ZoneInfo("Etc/GMT-10"), "+10"), ] for tz, expected in tests: with self.subTest(tz=tz, expected=expected): self.assertEqual(timezone._get_timezone_name(tz), expected) def test_get_default_timezone(self): self.assertEqual(timezone.get_default_timezone_name(), "America/Chicago") def test_fixedoffset_timedelta(self): delta = datetime.timedelta(hours=1) self.assertEqual(timezone.get_fixed_timezone(delta).utcoffset(None), delta) def test_fixedoffset_negative_timedelta(self): delta = datetime.timedelta(hours=-2) self.assertEqual(timezone.get_fixed_timezone(delta).utcoffset(None), delta)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_decorators.py
tests/utils_tests/test_decorators.py
from django.http import HttpResponse from django.template import engines from django.template.response import TemplateResponse from django.test import RequestFactory, SimpleTestCase from django.utils.decorators import decorator_from_middleware class ProcessViewMiddleware: def __init__(self, get_response): self.get_response = get_response def process_view(self, request, view_func, view_args, view_kwargs): pass process_view_dec = decorator_from_middleware(ProcessViewMiddleware) @process_view_dec def process_view(request): return HttpResponse() class ClassProcessView: def __call__(self, request): return HttpResponse() class_process_view = process_view_dec(ClassProcessView()) class FullMiddleware: def __init__(self, get_response): self.get_response = get_response def process_request(self, request): request.process_request_reached = True def process_view(self, request, view_func, view_args, view_kwargs): request.process_view_reached = True def process_template_response(self, request, response): request.process_template_response_reached = True return response def process_response(self, request, response): # This should never receive unrendered content. request.process_response_content = response.content request.process_response_reached = True return response full_dec = decorator_from_middleware(FullMiddleware) class DecoratorFromMiddlewareTests(SimpleTestCase): """ Tests for view decorators created using ``django.utils.decorators.decorator_from_middleware``. """ rf = RequestFactory() def test_process_view_middleware(self): """ Test a middleware that implements process_view. """ process_view(self.rf.get("/")) def test_callable_process_view_middleware(self): """ Test a middleware that implements process_view, operating on a callable class. """ class_process_view(self.rf.get("/")) def test_full_dec_normal(self): """ All methods of middleware are called for normal HttpResponses """ @full_dec def normal_view(request): template = engines["django"].from_string("Hello world") return HttpResponse(template.render()) request = self.rf.get("/") normal_view(request) self.assertTrue(getattr(request, "process_request_reached", False)) self.assertTrue(getattr(request, "process_view_reached", False)) # process_template_response must not be called for HttpResponse self.assertFalse(getattr(request, "process_template_response_reached", False)) self.assertTrue(getattr(request, "process_response_reached", False)) def test_full_dec_templateresponse(self): """ All methods of middleware are called for TemplateResponses in the right sequence. """ @full_dec def template_response_view(request): template = engines["django"].from_string("Hello world") return TemplateResponse(request, template) request = self.rf.get("/") response = template_response_view(request) self.assertTrue(getattr(request, "process_request_reached", False)) self.assertTrue(getattr(request, "process_view_reached", False)) self.assertTrue(getattr(request, "process_template_response_reached", False)) # response must not be rendered yet. self.assertFalse(response._is_rendered) # process_response must not be called until after response is rendered, # otherwise some decorators like csrf_protect and gzip_page will not # work correctly. See #16004 self.assertFalse(getattr(request, "process_response_reached", False)) response.render() self.assertTrue(getattr(request, "process_response_reached", False)) # process_response saw the rendered content self.assertEqual(request.process_response_content, b"Hello world")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_csp.py
tests/utils_tests/test_csp.py
from secrets import token_urlsafe from unittest.mock import patch from django.test import SimpleTestCase from django.utils.csp import CSP, LazyNonce, build_policy, generate_nonce from django.utils.functional import empty basic_config = { "default-src": [CSP.SELF], } alt_config = { "default-src": [CSP.SELF, CSP.UNSAFE_INLINE], } basic_policy = "default-src 'self'" class CSPConstantsTests(SimpleTestCase): def test_constants(self): self.assertEqual(CSP.NONE, "'none'") self.assertEqual(CSP.REPORT_SAMPLE, "'report-sample'") self.assertEqual(CSP.SELF, "'self'") self.assertEqual(CSP.STRICT_DYNAMIC, "'strict-dynamic'") self.assertEqual(CSP.UNSAFE_EVAL, "'unsafe-eval'") self.assertEqual(CSP.UNSAFE_HASHES, "'unsafe-hashes'") self.assertEqual(CSP.UNSAFE_INLINE, "'unsafe-inline'") self.assertEqual(CSP.WASM_UNSAFE_EVAL, "'wasm-unsafe-eval'") self.assertEqual(CSP.NONCE, "<CSP_NONCE_SENTINEL>") class CSPBuildPolicyTest(SimpleTestCase): def assertPolicyEqual(self, a, b): parts_a = sorted(a.split("; ")) if a is not None else None parts_b = sorted(b.split("; ")) if b is not None else None self.assertEqual(parts_a, parts_b, f"Policies not equal: {a!r} != {b!r}") def test_config_empty(self): self.assertPolicyEqual(build_policy({}), "") def test_config_basic(self): self.assertPolicyEqual(build_policy(basic_config), basic_policy) def test_config_multiple_directives(self): policy = { "default-src": [CSP.SELF], "script-src": [CSP.NONE], } self.assertPolicyEqual( build_policy(policy), "default-src 'self'; script-src 'none'" ) def test_config_value_as_string(self): """ Test that a single value can be passed as a string. """ policy = {"default-src": CSP.SELF} self.assertPolicyEqual(build_policy(policy), "default-src 'self'") def test_config_value_as_tuple(self): """ Test that a tuple can be passed as a value. """ policy = {"default-src": (CSP.SELF, "foo.com")} self.assertPolicyEqual(build_policy(policy), "default-src 'self' foo.com") def test_config_value_as_set(self): """ Test that a set can be passed as a value. Sets are often used in Django settings to ensure uniqueness, however, sets are unordered. The middleware ensures consistency via sorting if a set is passed. """ policy = {"default-src": {CSP.SELF, "foo.com", "bar.com"}} self.assertPolicyEqual( build_policy(policy), "default-src 'self' bar.com foo.com" ) def test_config_value_none(self): """ Test that `None` removes the directive from the policy. Useful in cases where the CSP config is scripted in some way or explicitly not wanting to set a directive. """ policy = {"default-src": [CSP.SELF], "script-src": None} self.assertPolicyEqual(build_policy(policy), basic_policy) def test_config_value_boolean_true(self): policy = {"default-src": [CSP.SELF], "block-all-mixed-content": True} self.assertPolicyEqual( build_policy(policy), "default-src 'self'; block-all-mixed-content" ) def test_config_value_boolean_false(self): policy = {"default-src": [CSP.SELF], "block-all-mixed-content": False} self.assertPolicyEqual(build_policy(policy), basic_policy) def test_config_value_multiple_boolean(self): policy = { "default-src": [CSP.SELF], "block-all-mixed-content": True, "upgrade-insecure-requests": True, } self.assertPolicyEqual( build_policy(policy), "default-src 'self'; block-all-mixed-content; upgrade-insecure-requests", ) def test_config_with_nonce_arg(self): """ Test when the `CSP.NONCE` is not in the defined policy, the nonce argument has no effect. """ self.assertPolicyEqual(build_policy(basic_config, nonce="abc123"), basic_policy) def test_config_with_nonce(self): policy = {"default-src": [CSP.SELF, CSP.NONCE]} self.assertPolicyEqual( build_policy(policy, nonce="abc123"), "default-src 'self' 'nonce-abc123'", ) def test_config_with_multiple_nonces(self): policy = { "default-src": [CSP.SELF, CSP.NONCE], "script-src": [CSP.SELF, CSP.NONCE], } self.assertPolicyEqual( build_policy(policy, nonce="abc123"), "default-src 'self' 'nonce-abc123'; script-src 'self' 'nonce-abc123'", ) def test_config_with_empty_directive(self): policy = {"default-src": []} self.assertPolicyEqual(build_policy(policy), "") class LazyNonceTests(SimpleTestCase): def test_generates_on_usage(self): generated_tokens = [] nonce = LazyNonce() self.assertFalse(nonce) self.assertIs(nonce._wrapped, empty) def memento_token_urlsafe(size): generated_tokens.append(result := token_urlsafe(size)) return result with patch("django.utils.csp.secrets.token_urlsafe", memento_token_urlsafe): # Force usage, similar to template rendering, to generate the # nonce. val = str(nonce) self.assertTrue(nonce) self.assertEqual(nonce, val) self.assertIsInstance(nonce, str) self.assertEqual(repr(nonce), f"<LazyNonce: '{nonce}'>") self.assertEqual(len(val), 22) # Based on secrets.token_urlsafe of 16 bytes. self.assertEqual(generated_tokens, [nonce]) # Also test the wrapped value. self.assertEqual(nonce._wrapped, val) def test_returns_same_value(self): nonce = LazyNonce() first = str(nonce) second = str(nonce) self.assertEqual(first, second) def test_repr(self): nonce = LazyNonce() self.assertEqual(repr(nonce), f"<LazyNonce: {repr(generate_nonce)}>") str(nonce) # Force nonce generation. self.assertRegex(repr(nonce), r"<LazyNonce: '[^']+'>")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_dateparse.py
tests/utils_tests/test_dateparse.py
import unittest from datetime import date, datetime, time, timedelta from django.utils.dateparse import ( parse_date, parse_datetime, parse_duration, parse_time, ) from django.utils.timezone import get_fixed_timezone class DateParseTests(unittest.TestCase): def test_parse_date(self): # Valid inputs self.assertEqual(parse_date("2012-04-23"), date(2012, 4, 23)) self.assertEqual(parse_date("2012-4-9"), date(2012, 4, 9)) self.assertEqual(parse_date("20120423"), date(2012, 4, 23)) # Invalid inputs self.assertIsNone(parse_date("2012423")) with self.assertRaises(ValueError): parse_date("2012-04-56") def test_parse_time(self): # Valid inputs self.assertEqual(parse_time("09:15:00"), time(9, 15)) self.assertEqual(parse_time("091500"), time(9, 15)) self.assertEqual(parse_time("10:10"), time(10, 10)) self.assertEqual(parse_time("10:20:30.400"), time(10, 20, 30, 400000)) self.assertEqual(parse_time("10:20:30,400"), time(10, 20, 30, 400000)) self.assertEqual(parse_time("4:8:16"), time(4, 8, 16)) # Time zone offset is ignored. self.assertEqual(parse_time("00:05:23+04:00"), time(0, 5, 23)) # Invalid inputs self.assertIsNone(parse_time("00:05:")) self.assertIsNone(parse_time("00:05:23,")) self.assertIsNone(parse_time("00:05:23+")) self.assertIsNone(parse_time("00:05:23+25:00")) self.assertIsNone(parse_time("4:18:101")) self.assertIsNone(parse_time("91500")) with self.assertRaises(ValueError): parse_time("09:15:90") def test_parse_datetime(self): valid_inputs = ( ("2012-04-23", datetime(2012, 4, 23)), ("2012-04-23T09:15:00", datetime(2012, 4, 23, 9, 15)), ("2012-4-9 4:8:16", datetime(2012, 4, 9, 4, 8, 16)), ( "2012-04-23T09:15:00Z", datetime(2012, 4, 23, 9, 15, 0, 0, get_fixed_timezone(0)), ), ( "2012-4-9 4:8:16-0320", datetime(2012, 4, 9, 4, 8, 16, 0, get_fixed_timezone(-200)), ), ( "2012-04-23T10:20:30.400+02:30", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(150)), ), ( "2012-04-23T10:20:30.400+02", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(120)), ), ( "2012-04-23T10:20:30.400-02", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(-120)), ), ( "2012-04-23T10:20:30,400-02", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(-120)), ), ( "2012-04-23T10:20:30.400 +0230", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(150)), ), ( "2012-04-23T10:20:30,400 +00", datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(0)), ), ( "2012-04-23T10:20:30 -02", datetime(2012, 4, 23, 10, 20, 30, 0, get_fixed_timezone(-120)), ), ) for source, expected in valid_inputs: with self.subTest(source=source): self.assertEqual(parse_datetime(source), expected) # Invalid inputs self.assertIsNone(parse_datetime("20120423091500")) with self.assertRaises(ValueError): parse_datetime("2012-04-56T09:15:90") class DurationParseTests(unittest.TestCase): def test_parse_python_format(self): timedeltas = [ timedelta( days=4, minutes=15, seconds=30, milliseconds=100 ), # fractions of seconds timedelta(hours=10, minutes=15, seconds=30), # hours, minutes, seconds timedelta(days=4, minutes=15, seconds=30), # multiple days timedelta(days=1, minutes=00, seconds=00), # single day timedelta(days=-4, minutes=15, seconds=30), # negative durations timedelta(minutes=15, seconds=30), # minute & seconds timedelta(seconds=30), # seconds ] for delta in timedeltas: with self.subTest(delta=delta): self.assertEqual(parse_duration(format(delta)), delta) def test_parse_postgresql_format(self): test_values = ( ("1 day", timedelta(1)), ("-1 day", timedelta(-1)), ("1 day 0:00:01", timedelta(days=1, seconds=1)), ("1 day -0:00:01", timedelta(days=1, seconds=-1)), ("-1 day -0:00:01", timedelta(days=-1, seconds=-1)), ("-1 day +0:00:01", timedelta(days=-1, seconds=1)), ( "4 days 0:15:30.1", timedelta(days=4, minutes=15, seconds=30, milliseconds=100), ), ( "4 days 0:15:30.0001", timedelta(days=4, minutes=15, seconds=30, microseconds=100), ), ("-4 days -15:00:30", timedelta(days=-4, hours=-15, seconds=-30)), ) for source, expected in test_values: with self.subTest(source=source): self.assertEqual(parse_duration(source), expected) def test_seconds(self): self.assertEqual(parse_duration("30"), timedelta(seconds=30)) def test_minutes_seconds(self): self.assertEqual(parse_duration("15:30"), timedelta(minutes=15, seconds=30)) self.assertEqual(parse_duration("5:30"), timedelta(minutes=5, seconds=30)) def test_hours_minutes_seconds(self): self.assertEqual( parse_duration("10:15:30"), timedelta(hours=10, minutes=15, seconds=30) ) self.assertEqual( parse_duration("1:15:30"), timedelta(hours=1, minutes=15, seconds=30) ) self.assertEqual( parse_duration("100:200:300"), timedelta(hours=100, minutes=200, seconds=300), ) def test_days(self): self.assertEqual( parse_duration("4 15:30"), timedelta(days=4, minutes=15, seconds=30) ) self.assertEqual( parse_duration("4 10:15:30"), timedelta(days=4, hours=10, minutes=15, seconds=30), ) def test_fractions_of_seconds(self): test_values = ( ("15:30.1", timedelta(minutes=15, seconds=30, milliseconds=100)), ("15:30.01", timedelta(minutes=15, seconds=30, milliseconds=10)), ("15:30.001", timedelta(minutes=15, seconds=30, milliseconds=1)), ("15:30.0001", timedelta(minutes=15, seconds=30, microseconds=100)), ("15:30.00001", timedelta(minutes=15, seconds=30, microseconds=10)), ("15:30.000001", timedelta(minutes=15, seconds=30, microseconds=1)), ("15:30,000001", timedelta(minutes=15, seconds=30, microseconds=1)), ) for source, expected in test_values: with self.subTest(source=source): self.assertEqual(parse_duration(source), expected) def test_negative(self): test_values = ( ("-4 15:30", timedelta(days=-4, minutes=15, seconds=30)), ("-172800", timedelta(days=-2)), ("-15:30", timedelta(minutes=-15, seconds=-30)), ("-1:15:30", timedelta(hours=-1, minutes=-15, seconds=-30)), ("-30.1", timedelta(seconds=-30, milliseconds=-100)), ("-30,1", timedelta(seconds=-30, milliseconds=-100)), ("-00:01:01", timedelta(minutes=-1, seconds=-1)), ("-01:01", timedelta(seconds=-61)), ("-01:-01", None), ) for source, expected in test_values: with self.subTest(source=source): self.assertEqual(parse_duration(source), expected) def test_iso_8601(self): test_values = ( ("P4Y", None), ("P4M", None), ("P4W", timedelta(weeks=4)), ("P0.5W", timedelta(weeks=0.5)), ("P0,5W", timedelta(weeks=0.5)), ("-P0.5W", timedelta(weeks=-0.5)), ("P1W1D", timedelta(weeks=1, days=1)), ("P4D", timedelta(days=4)), ("-P1D", timedelta(days=-1)), ("P0.5D", timedelta(hours=12)), ("P0,5D", timedelta(hours=12)), ("-P0.5D", timedelta(hours=-12)), ("-P0,5D", timedelta(hours=-12)), ("PT5H", timedelta(hours=5)), ("-PT5H", timedelta(hours=-5)), ("PT5M", timedelta(minutes=5)), ("-PT5M", timedelta(minutes=-5)), ("PT5S", timedelta(seconds=5)), ("-PT5S", timedelta(seconds=-5)), ("PT0.000005S", timedelta(microseconds=5)), ("PT0,000005S", timedelta(microseconds=5)), ("-PT0.000005S", timedelta(microseconds=-5)), ("-PT0,000005S", timedelta(microseconds=-5)), ("-P4DT1H", timedelta(days=-4, hours=-1)), # Invalid separators for decimal fractions. ("P3(3D", None), ("PT3)3H", None), ("PT3|3M", None), ("PT3/3S", None), ) for source, expected in test_values: with self.subTest(source=source): self.assertEqual(parse_duration(source), expected)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_json.py
tests/utils_tests/test_json.py
import json from collections import UserList, defaultdict from datetime import datetime from decimal import Decimal from django.test import SimpleTestCase from django.utils.json import normalize_json class JSONNormalizeTestCase(SimpleTestCase): def test_converts_json_types(self): for test_case, expected in [ (None, "null"), (True, "true"), (False, "false"), (2, "2"), (3.0, "3.0"), (1e23 + 1, "1e+23"), ("1", '"1"'), (b"hello", '"hello"'), ([], "[]"), (UserList([1, 2]), "[1, 2]"), ({}, "{}"), ({1: "a"}, '{"1": "a"}'), ({"foo": (1, 2, 3)}, '{"foo": [1, 2, 3]}'), (defaultdict(list), "{}"), (float("nan"), "NaN"), (float("inf"), "Infinity"), (float("-inf"), "-Infinity"), ]: with self.subTest(test_case): normalized = normalize_json(test_case) # Ensure that the normalized result is serializable. self.assertEqual(json.dumps(normalized), expected) def test_bytes_decode_error(self): with self.assertRaisesMessage(ValueError, "Unsupported value"): normalize_json(b"\xff") def test_encode_error(self): for test_case in [self, any, object(), datetime.now(), set(), Decimal("3.42")]: with ( self.subTest(test_case), self.assertRaisesMessage(TypeError, "Unsupported type"), ): normalize_json(test_case)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_hashable.py
tests/utils_tests/test_hashable.py
from django.test import SimpleTestCase from django.utils.hashable import make_hashable class TestHashable(SimpleTestCase): def test_equal(self): tests = ( ([], ()), (["a", 1], ("a", 1)), ({}, ()), ({"a"}, ("a",)), (frozenset({"a"}), {"a"}), ({"a": 1, "b": 2}, (("a", 1), ("b", 2))), ({"b": 2, "a": 1}, (("a", 1), ("b", 2))), (("a", ["b", 1]), ("a", ("b", 1))), (("a", {"b": 1}), ("a", (("b", 1),))), ) for value, expected in tests: with self.subTest(value=value): self.assertEqual(make_hashable(value), expected) def test_count_equal(self): tests = ( ({"a": 1, "b": ["a", 1]}, (("a", 1), ("b", ("a", 1)))), ({"a": 1, "b": ("a", [1, 2])}, (("a", 1), ("b", ("a", (1, 2))))), ) for value, expected in tests: with self.subTest(value=value): self.assertCountEqual(make_hashable(value), expected) def test_unhashable(self): class Unhashable: __hash__ = None with self.assertRaisesMessage(TypeError, "unhashable type: 'Unhashable'"): make_hashable(Unhashable())
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_http.py
tests/utils_tests/test_http.py
import platform import unittest from datetime import UTC, datetime from unittest import mock from django.test import SimpleTestCase from django.utils.datastructures import MultiValueDict from django.utils.http import ( MAX_HEADER_LENGTH, MAX_URL_LENGTH, 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:pass@example.com", r"http://testserver\@example.com", r"http:\\testserver\confirm\me@example.com", "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/confirm?email=me@example.com", "/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/me@example.com", 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, ) def test_max_url_length(self): allowed_host = "example.com" max_extra_characters = "é" * (MAX_URL_LENGTH - len(allowed_host) - 1) max_length_boundary_url = f"{allowed_host}/{max_extra_characters}" cases = [ (max_length_boundary_url, True), (max_length_boundary_url + "ú", False), ] for url, expected in cases: with self.subTest(url=url): self.assertIs( url_has_allowed_host_and_scheme(url, allowed_hosts={allowed_host}), expected, ) 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, UTC), datetime(1994, 11, 6, 8, 49, 37, tzinfo=UTC), ) @unittest.skipIf(platform.architecture()[0] == "32bit", "The Year 2038 problem.") @mock.patch("django.utils.http.datetime") def test_parsing_rfc850(self, mocked_datetime): mocked_datetime.side_effect = datetime now_1 = datetime(2019, 11, 6, 8, 49, 37, tzinfo=UTC) now_2 = datetime(2020, 11, 6, 8, 49, 37, tzinfo=UTC) now_3 = datetime(2048, 11, 6, 8, 49, 37, tzinfo=UTC) tests = ( ( now_1, "Tuesday, 31-Dec-69 08:49:37 GMT", datetime(2069, 12, 31, 8, 49, 37, tzinfo=UTC), ), ( now_1, "Tuesday, 10-Nov-70 08:49:37 GMT", datetime(1970, 11, 10, 8, 49, 37, tzinfo=UTC), ), ( now_1, "Sunday, 06-Nov-94 08:49:37 GMT", datetime(1994, 11, 6, 8, 49, 37, tzinfo=UTC), ), ( now_2, "Wednesday, 31-Dec-70 08:49:37 GMT", datetime(2070, 12, 31, 8, 49, 37, tzinfo=UTC), ), ( now_2, "Friday, 31-Dec-71 08:49:37 GMT", datetime(1971, 12, 31, 8, 49, 37, tzinfo=UTC), ), ( now_3, "Sunday, 31-Dec-00 08:49:37 GMT", datetime(2000, 12, 31, 8, 49, 37, tzinfo=UTC), ), ( now_3, "Friday, 31-Dec-99 08:49:37 GMT", datetime(1999, 12, 31, 8, 49, 37, tzinfo=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=UTC) self.assertEqual( datetime.fromtimestamp(parsed, 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, UTC), datetime(1994, 11, 6, 8, 49, 37, tzinfo=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, UTC), datetime(2037, 11, 6, 8, 49, 37, tzinfo=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 = [ ("", ("", {})), (None, ("", {})), ("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"}), ), ( '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'}), ), ( 'form-data; name="files"; filename="\\"fo\\"o;b\\\\ar\\""', ("form-data", {"name": "files", "filename": '"fo"o;b\\ar"'}), ), ] 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) def test_header_max_length(self): base_header = "Content-Type: application/x-stuff; title*=" base_header_len = len(base_header) test_data = [ (MAX_HEADER_LENGTH, {}), (MAX_HEADER_LENGTH, {"max_length": None}), (MAX_HEADER_LENGTH + 1, {"max_length": None}), (100, {"max_length": 100}), ] for line_length, kwargs in test_data: with self.subTest(line_length=line_length, kwargs=kwargs): title = "x" * (line_length - base_header_len) line = base_header + title assert len(line) == line_length parsed = parse_header_parameters(line, **kwargs) expected = ("content-type: application/x-stuff", {"title": title}) self.assertEqual(parsed, expected) def test_header_too_long(self): test_data = [ ("x" * (MAX_HEADER_LENGTH + 1), {}), ("x" * 101, {"max_length": 100}), ] for line, kwargs in test_data: with self.subTest(line_length=len(line), kwargs=kwargs): with self.assertRaises(ValueError): parse_header_parameters(line, **kwargs) 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", ), ((True, "some\nfile"), "attachment; filename*=utf-8''some%0Afile"), ) 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 )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_datastructures.py
tests/utils_tests/test_datastructures.py
""" Tests for stuff in django.utils.datastructures. """ import collections.abc import copy import pickle from django.test import SimpleTestCase from django.utils.datastructures import ( CaseInsensitiveMapping, DeferredSubDict, DictWrapper, ImmutableList, MultiValueDict, MultiValueDictKeyError, OrderedSet, ) class OrderedSetTests(SimpleTestCase): def test_init_with_iterable(self): s = OrderedSet([1, 2, 3]) self.assertEqual(list(s.dict.keys()), [1, 2, 3]) def test_remove(self): s = OrderedSet() self.assertEqual(len(s), 0) s.add(1) s.add(2) s.remove(2) self.assertEqual(len(s), 1) self.assertNotIn(2, s) def test_discard(self): s = OrderedSet() self.assertEqual(len(s), 0) s.add(1) s.discard(2) self.assertEqual(len(s), 1) def test_reversed(self): s = reversed(OrderedSet([1, 2, 3])) self.assertIsInstance(s, collections.abc.Iterator) self.assertEqual(list(s), [3, 2, 1]) def test_contains(self): s = OrderedSet() self.assertEqual(len(s), 0) s.add(1) self.assertIn(1, s) def test_bool(self): # Refs #23664 s = OrderedSet() self.assertFalse(s) s.add(1) self.assertTrue(s) def test_len(self): s = OrderedSet() self.assertEqual(len(s), 0) s.add(1) s.add(2) s.add(2) self.assertEqual(len(s), 2) def test_repr(self): self.assertEqual(repr(OrderedSet()), "OrderedSet()") self.assertEqual(repr(OrderedSet([2, 3, 2, 1])), "OrderedSet([2, 3, 1])") class MultiValueDictTests(SimpleTestCase): def test_repr(self): d = MultiValueDict({"key": "value"}) self.assertEqual(repr(d), "<MultiValueDict: {'key': 'value'}>") def test_multivaluedict(self): d = MultiValueDict( {"name": ["Adrian", "Simon"], "position": ["Developer"], "empty": []} ) self.assertEqual(d["name"], "Simon") self.assertEqual(d.get("name"), "Simon") self.assertEqual(d.getlist("name"), ["Adrian", "Simon"]) self.assertEqual( list(d.items()), [("name", "Simon"), ("position", "Developer"), ("empty", [])], ) self.assertEqual( list(d.lists()), [("name", ["Adrian", "Simon"]), ("position", ["Developer"]), ("empty", [])], ) with self.assertRaisesMessage(MultiValueDictKeyError, "'lastname'"): d.__getitem__("lastname") self.assertIsNone(d.get("empty")) self.assertEqual(d.get("empty", "nonexistent"), "nonexistent") self.assertIsNone(d.get("lastname")) self.assertEqual(d.get("lastname", "nonexistent"), "nonexistent") self.assertEqual(d.getlist("lastname"), []) self.assertEqual( d.getlist("doesnotexist", ["Adrian", "Simon"]), ["Adrian", "Simon"] ) d.setlist("lastname", ["Holovaty", "Willison"]) self.assertEqual(d.getlist("lastname"), ["Holovaty", "Willison"]) self.assertEqual(list(d.values()), ["Simon", "Developer", [], "Willison"]) d.setlistdefault("lastname", ["Doe"]) self.assertEqual(d.getlist("lastname"), ["Holovaty", "Willison"]) d.setlistdefault("newkey", ["Doe"]) self.assertEqual(d.getlist("newkey"), ["Doe"]) def test_appendlist(self): d = MultiValueDict() d.appendlist("name", "Adrian") d.appendlist("name", "Simon") self.assertEqual(d.getlist("name"), ["Adrian", "Simon"]) def test_copy(self): for copy_func in [copy.copy, lambda d: d.copy()]: with self.subTest(copy_func): d1 = MultiValueDict({"developers": ["Carl", "Fred"]}) self.assertEqual(d1["developers"], "Fred") d2 = copy_func(d1) d2.update({"developers": "Groucho"}) self.assertEqual(d2["developers"], "Groucho") self.assertEqual(d1["developers"], "Fred") d1 = MultiValueDict({"key": [[]]}) self.assertEqual(d1["key"], []) d2 = copy_func(d1) d2["key"].append("Penguin") self.assertEqual(d1["key"], ["Penguin"]) self.assertEqual(d2["key"], ["Penguin"]) def test_deepcopy(self): d1 = MultiValueDict({"a": [[123]]}) d2 = copy.copy(d1) d3 = copy.deepcopy(d1) self.assertIs(d1["a"], d2["a"]) self.assertIsNot(d1["a"], d3["a"]) def test_pickle(self): x = MultiValueDict({"a": ["1", "2"], "b": ["3"]}) self.assertEqual(x, pickle.loads(pickle.dumps(x))) def test_dict_translation(self): mvd = MultiValueDict( { "devs": ["Bob", "Joe"], "pm": ["Rory"], } ) d = mvd.dict() self.assertEqual(list(d), list(mvd)) for key in mvd: self.assertEqual(d[key], mvd[key]) self.assertEqual({}, MultiValueDict().dict()) def test_getlist_doesnt_mutate(self): x = MultiValueDict({"a": ["1", "2"], "b": ["3"]}) values = x.getlist("a") values += x.getlist("b") self.assertEqual(x.getlist("a"), ["1", "2"]) def test_internal_getlist_does_mutate(self): x = MultiValueDict({"a": ["1", "2"], "b": ["3"]}) values = x._getlist("a") values += x._getlist("b") self.assertEqual(x._getlist("a"), ["1", "2", "3"]) def test_getlist_default(self): x = MultiValueDict({"a": [1]}) MISSING = object() values = x.getlist("b", default=MISSING) self.assertIs(values, MISSING) def test_getlist_none_empty_values(self): x = MultiValueDict({"a": None, "b": []}) self.assertIsNone(x.getlist("a")) self.assertEqual(x.getlist("b"), []) def test_setitem(self): x = MultiValueDict({"a": [1, 2]}) x["a"] = 3 self.assertEqual(list(x.lists()), [("a", [3])]) def test_setdefault(self): x = MultiValueDict({"a": [1, 2]}) a = x.setdefault("a", 3) b = x.setdefault("b", 3) self.assertEqual(a, 2) self.assertEqual(b, 3) self.assertEqual(list(x.lists()), [("a", [1, 2]), ("b", [3])]) def test_update_too_many_args(self): x = MultiValueDict({"a": []}) msg = "update expected at most 1 argument, got 2" with self.assertRaisesMessage(TypeError, msg): x.update(1, 2) def test_update_no_args(self): x = MultiValueDict({"a": []}) x.update() self.assertEqual(list(x.lists()), [("a", [])]) def test_update_dict_arg(self): x = MultiValueDict({"a": [1], "b": [2], "c": [3]}) x.update({"a": 4, "b": 5}) self.assertEqual(list(x.lists()), [("a", [1, 4]), ("b", [2, 5]), ("c", [3])]) def test_update_multivaluedict_arg(self): x = MultiValueDict({"a": [1], "b": [2], "c": [3]}) x.update(MultiValueDict({"a": [4], "b": [5]})) self.assertEqual(list(x.lists()), [("a", [1, 4]), ("b", [2, 5]), ("c", [3])]) def test_update_kwargs(self): x = MultiValueDict({"a": [1], "b": [2], "c": [3]}) x.update(a=4, b=5) self.assertEqual(list(x.lists()), [("a", [1, 4]), ("b", [2, 5]), ("c", [3])]) def test_update_with_empty_iterable(self): for value in ["", b"", (), [], set(), {}]: d = MultiValueDict() d.update(value) self.assertEqual(d, MultiValueDict()) def test_update_with_iterable_of_pairs(self): for value in [(("a", 1),), [("a", 1)], {("a", 1)}]: d = MultiValueDict() d.update(value) self.assertEqual(d, MultiValueDict({"a": [1]})) def test_update_raises_correct_exceptions(self): # MultiValueDict.update() raises equivalent exceptions to # dict.update(). # Non-iterable values raise TypeError. for value in [None, True, False, 123, 123.45]: with self.subTest(value), self.assertRaises(TypeError): MultiValueDict().update(value) # Iterables of objects that cannot be unpacked raise TypeError. for value in [b"123", b"abc", (1, 2, 3), [1, 2, 3], {1, 2, 3}]: with self.subTest(value), self.assertRaises(TypeError): MultiValueDict().update(value) # Iterables of unpackable objects with incorrect number of items raise # ValueError. for value in ["123", "abc", ("a", "b", "c"), ["a", "b", "c"], {"a", "b", "c"}]: with self.subTest(value), self.assertRaises(ValueError): MultiValueDict().update(value) class ImmutableListTests(SimpleTestCase): def test_sort(self): d = ImmutableList(range(10)) # AttributeError: ImmutableList object is immutable. with self.assertRaisesMessage( AttributeError, "ImmutableList object is immutable." ): d.sort() self.assertEqual(repr(d), "(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)") def test_custom_warning(self): d = ImmutableList(range(10), warning="Object is immutable!") self.assertEqual(d[1], 1) # AttributeError: Object is immutable! with self.assertRaisesMessage(AttributeError, "Object is immutable!"): d.__setitem__(1, "test") class DictWrapperTests(SimpleTestCase): def test_dictwrapper(self): def f(x): return "*%s" % x d = DictWrapper({"a": "a"}, f, "xx_") self.assertEqual( "Normal: %(a)s. Modified: %(xx_a)s" % d, "Normal: a. Modified: *a" ) class CaseInsensitiveMappingTests(SimpleTestCase): def setUp(self): self.dict1 = CaseInsensitiveMapping( { "Accept": "application/json", "content-type": "text/html", } ) def test_create_with_invalid_values(self): msg = "dictionary update sequence element #1 has length 4; 2 is required" with self.assertRaisesMessage(ValueError, msg): CaseInsensitiveMapping([("Key1", "Val1"), "Key2"]) def test_create_with_invalid_key(self): msg = "Element key 1 invalid, only strings are allowed" with self.assertRaisesMessage(ValueError, msg): CaseInsensitiveMapping([(1, "2")]) def test_list(self): self.assertEqual(list(self.dict1), ["Accept", "content-type"]) def test_dict(self): self.assertEqual( dict(self.dict1), {"Accept": "application/json", "content-type": "text/html"}, ) def test_repr(self): dict1 = CaseInsensitiveMapping({"Accept": "application/json"}) dict2 = CaseInsensitiveMapping({"content-type": "text/html"}) self.assertEqual(repr(dict1), repr({"Accept": "application/json"})) self.assertEqual(repr(dict2), repr({"content-type": "text/html"})) def test_str(self): dict1 = CaseInsensitiveMapping({"Accept": "application/json"}) dict2 = CaseInsensitiveMapping({"content-type": "text/html"}) self.assertEqual(str(dict1), str({"Accept": "application/json"})) self.assertEqual(str(dict2), str({"content-type": "text/html"})) def test_equal(self): self.assertEqual( self.dict1, {"Accept": "application/json", "content-type": "text/html"} ) self.assertNotEqual( self.dict1, {"accept": "application/jso", "Content-Type": "text/html"} ) self.assertNotEqual(self.dict1, "string") def test_items(self): other = {"Accept": "application/json", "content-type": "text/html"} self.assertEqual(sorted(self.dict1.items()), sorted(other.items())) def test_copy(self): copy = self.dict1.copy() self.assertIs(copy, self.dict1) self.assertEqual(copy, self.dict1) def test_getitem(self): self.assertEqual(self.dict1["Accept"], "application/json") self.assertEqual(self.dict1["accept"], "application/json") self.assertEqual(self.dict1["aCCept"], "application/json") self.assertEqual(self.dict1["content-type"], "text/html") self.assertEqual(self.dict1["Content-Type"], "text/html") self.assertEqual(self.dict1["Content-type"], "text/html") def test_in(self): self.assertIn("Accept", self.dict1) self.assertIn("accept", self.dict1) self.assertIn("aCCept", self.dict1) self.assertIn("content-type", self.dict1) self.assertIn("Content-Type", self.dict1) def test_del(self): self.assertIn("Accept", self.dict1) msg = "'CaseInsensitiveMapping' object does not support item deletion" with self.assertRaisesMessage(TypeError, msg): del self.dict1["Accept"] self.assertIn("Accept", self.dict1) def test_set(self): self.assertEqual(len(self.dict1), 2) msg = "'CaseInsensitiveMapping' object does not support item assignment" with self.assertRaisesMessage(TypeError, msg): self.dict1["New Key"] = 1 self.assertEqual(len(self.dict1), 2) class DeferredSubDictTests(SimpleTestCase): def test_basic(self): parent = { "settings": {"theme": "dark", "language": "en"}, "config": {"enabled": True, "timeout": 30}, } sub = DeferredSubDict(parent, "settings") self.assertEqual(sub["theme"], "dark") self.assertEqual(sub["language"], "en") with self.assertRaises(KeyError): sub["enabled"] def test_reflects_changes_in_parent(self): parent = {"settings": {"theme": "dark"}} sub = DeferredSubDict(parent, "settings") parent["settings"]["theme"] = "light" self.assertEqual(sub["theme"], "light") parent["settings"]["mode"] = "tight" self.assertEqual(sub["mode"], "tight") def test_missing_deferred_key_raises_keyerror(self): parent = {"settings": {"theme": "dark"}} sub = DeferredSubDict(parent, "nonexistent") with self.assertRaises(KeyError): sub["anything"] def test_missing_child_key_raises_keyerror(self): parent = {"settings": {"theme": "dark"}} sub = DeferredSubDict(parent, "settings") with self.assertRaises(KeyError): sub["nonexistent"] def test_child_not_a_dict_raises_typeerror(self): parent = {"bad": "not_a_dict"} sub = DeferredSubDict(parent, "bad") with self.assertRaises(TypeError): sub["any_key"]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_inspect.py
tests/utils_tests/test_inspect.py
import subprocess import unittest from typing import TYPE_CHECKING from django.shortcuts import aget_object_or_404 from django.utils import inspect from django.utils.version import PY314 if TYPE_CHECKING: from django.utils.safestring import SafeString class Person: def no_arguments(self): return None def one_argument(self, something): return something def just_args(self, *args): return args def all_kinds(self, name, address="home", age=25, *args, **kwargs): return kwargs @classmethod def cls_all_kinds(cls, name, address="home", age=25, *args, **kwargs): return kwargs class TestInspectMethods(unittest.TestCase): def test_get_callable_parameters(self): self.assertIs( inspect._get_callable_parameters(Person.no_arguments), inspect._get_callable_parameters(Person.no_arguments), ) self.assertIs( inspect._get_callable_parameters(Person().no_arguments), inspect._get_callable_parameters(Person().no_arguments), ) def test_get_func_full_args_no_arguments(self): self.assertEqual(inspect.get_func_full_args(Person.no_arguments), []) self.assertEqual(inspect.get_func_full_args(Person().no_arguments), []) def test_get_func_full_args_one_argument(self): self.assertEqual( inspect.get_func_full_args(Person.one_argument), [("something",)] ) self.assertEqual( inspect.get_func_full_args(Person().one_argument), [("something",)], ) def test_get_func_full_args_all_arguments_method(self): arguments = [ ("name",), ("address", "home"), ("age", 25), ("*args",), ("**kwargs",), ] self.assertEqual(inspect.get_func_full_args(Person.all_kinds), arguments) self.assertEqual(inspect.get_func_full_args(Person().all_kinds), arguments) def test_get_func_full_args_all_arguments_classmethod(self): arguments = [ ("name",), ("address", "home"), ("age", 25), ("*args",), ("**kwargs",), ] self.assertEqual(inspect.get_func_full_args(Person.cls_all_kinds), arguments) self.assertEqual(inspect.get_func_full_args(Person().cls_all_kinds), arguments) def test_func_accepts_var_args_has_var_args(self): self.assertIs(inspect.func_accepts_var_args(Person.just_args), True) self.assertIs(inspect.func_accepts_var_args(Person().just_args), True) def test_func_accepts_var_args_no_var_args(self): self.assertIs(inspect.func_accepts_var_args(Person.one_argument), False) self.assertIs(inspect.func_accepts_var_args(Person().one_argument), False) def test_method_has_no_args(self): self.assertIs(inspect.method_has_no_args(Person.no_arguments), True) self.assertIs(inspect.method_has_no_args(Person().no_arguments), True) self.assertIs(inspect.method_has_no_args(Person.one_argument), False) self.assertIs(inspect.method_has_no_args(Person().one_argument), False) def test_func_supports_parameter(self): self.assertIs( inspect.func_supports_parameter(Person.all_kinds, "address"), True ) self.assertIs( inspect.func_supports_parameter(Person().all_kinds, "address"), True, ) self.assertIs(inspect.func_supports_parameter(Person.all_kinds, "zone"), False) self.assertIs( inspect.func_supports_parameter(Person().all_kinds, "zone"), False, ) def test_func_accepts_kwargs(self): self.assertIs(inspect.func_accepts_kwargs(Person.just_args), False) self.assertIs(inspect.func_accepts_kwargs(Person().just_args), False) self.assertIs(inspect.func_accepts_kwargs(Person.all_kinds), True) self.assertIs(inspect.func_accepts_kwargs(Person().just_args), False) @unittest.skipUnless(PY314, "Deferred annotations are Python 3.14+ only") def test_func_accepts_kwargs_deferred_annotations(self): def func_with_annotations(self, name: str, complex: SafeString) -> None: pass # Inspection fails with deferred annotations with python 3.14+. Earlier # Python versions trigger the NameError on module initialization. self.assertIs(inspect.func_accepts_kwargs(func_with_annotations), False) class IsModuleLevelFunctionTestCase(unittest.TestCase): @classmethod def _class_method(cls) -> None: return None @staticmethod def _static_method() -> None: return None def test_builtin(self): self.assertIs(inspect.is_module_level_function(any), False) self.assertIs(inspect.is_module_level_function(isinstance), False) def test_from_module(self): self.assertIs(inspect.is_module_level_function(subprocess.run), True) self.assertIs(inspect.is_module_level_function(subprocess.check_output), True) self.assertIs( inspect.is_module_level_function(inspect.is_module_level_function), True ) def test_private_function(self): def private_function(): pass self.assertIs(inspect.is_module_level_function(private_function), False) def test_coroutine(self): self.assertIs(inspect.is_module_level_function(aget_object_or_404), True) def test_method(self): self.assertIs(inspect.is_module_level_function(self.test_method), False) self.assertIs(inspect.is_module_level_function(self.setUp), False) def test_unbound_method(self): self.assertIs( inspect.is_module_level_function(self.__class__.test_unbound_method), True ) self.assertIs(inspect.is_module_level_function(self.__class__.setUp), True) def test_lambda(self): self.assertIs(inspect.is_module_level_function(lambda: True), False) def test_class_and_static_method(self): self.assertIs(inspect.is_module_level_function(self._static_method), True) self.assertIs(inspect.is_module_level_function(self._class_method), False)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/models.py
tests/utils_tests/models.py
from django.db import models class Category(models.Model): name = models.CharField(max_length=100) class CategoryInfo(models.Model): category = models.OneToOneField(Category, models.CASCADE)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_duration.py
tests/utils_tests/test_duration.py
import datetime import unittest from django.utils.dateparse import parse_duration from django.utils.duration import ( duration_iso_string, duration_microseconds, duration_string, ) class TestDurationString(unittest.TestCase): def test_simple(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5) self.assertEqual(duration_string(duration), "01:03:05") def test_days(self): duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5) self.assertEqual(duration_string(duration), "1 01:03:05") def test_microseconds(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345) self.assertEqual(duration_string(duration), "01:03:05.012345") def test_negative(self): duration = datetime.timedelta(days=-1, hours=1, minutes=3, seconds=5) self.assertEqual(duration_string(duration), "-1 01:03:05") class TestParseDurationRoundtrip(unittest.TestCase): def test_simple(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5) self.assertEqual(parse_duration(duration_string(duration)), duration) def test_days(self): duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5) self.assertEqual(parse_duration(duration_string(duration)), duration) def test_microseconds(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345) self.assertEqual(parse_duration(duration_string(duration)), duration) def test_negative(self): duration = datetime.timedelta(days=-1, hours=1, minutes=3, seconds=5) self.assertEqual(parse_duration(duration_string(duration)), duration) class TestISODurationString(unittest.TestCase): def test_simple(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5) self.assertEqual(duration_iso_string(duration), "P0DT01H03M05S") def test_days(self): duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5) self.assertEqual(duration_iso_string(duration), "P1DT01H03M05S") def test_microseconds(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345) self.assertEqual(duration_iso_string(duration), "P0DT01H03M05.012345S") def test_negative(self): duration = -1 * datetime.timedelta(days=1, hours=1, minutes=3, seconds=5) self.assertEqual(duration_iso_string(duration), "-P1DT01H03M05S") class TestParseISODurationRoundtrip(unittest.TestCase): def test_simple(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5) self.assertEqual(parse_duration(duration_iso_string(duration)), duration) def test_days(self): duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5) self.assertEqual(parse_duration(duration_iso_string(duration)), duration) def test_microseconds(self): duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345) self.assertEqual(parse_duration(duration_iso_string(duration)), duration) def test_negative(self): duration = datetime.timedelta(days=-1, hours=1, minutes=3, seconds=5) self.assertEqual( parse_duration(duration_iso_string(duration)).total_seconds(), duration.total_seconds(), ) class TestDurationMicroseconds(unittest.TestCase): def test(self): deltas = [ datetime.timedelta.max, datetime.timedelta.min, datetime.timedelta.resolution, -datetime.timedelta.resolution, datetime.timedelta(microseconds=8999999999999999), ] for delta in deltas: with self.subTest(delta=delta): self.assertEqual( datetime.timedelta(microseconds=duration_microseconds(delta)), delta )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_connection.py
tests/utils_tests/test_connection.py
from django.test import SimpleTestCase from django.utils.connection import BaseConnectionHandler class BaseConnectionHandlerTests(SimpleTestCase): def test_create_connection(self): handler = BaseConnectionHandler() msg = "Subclasses must implement create_connection()." with self.assertRaisesMessage(NotImplementedError, msg): handler.create_connection(None) def test_all_initialized_only(self): handler = BaseConnectionHandler({"default": {}}) self.assertEqual(handler.all(initialized_only=True), [])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_tree.py
tests/utils_tests/test_tree.py
import copy import unittest from django.db.models.sql import AND, OR from django.utils.tree import Node class NodeTests(unittest.TestCase): def setUp(self): self.node1_children = [("a", 1), ("b", 2)] self.node1 = Node(self.node1_children) self.node2 = Node() def test_str(self): self.assertEqual(str(self.node1), "(DEFAULT: ('a', 1), ('b', 2))") self.assertEqual(str(self.node2), "(DEFAULT: )") def test_repr(self): self.assertEqual(repr(self.node1), "<Node: (DEFAULT: ('a', 1), ('b', 2))>") self.assertEqual(repr(self.node2), "<Node: (DEFAULT: )>") def test_hash(self): node3 = Node(self.node1_children, negated=True) node4 = Node(self.node1_children, connector="OTHER") node5 = Node(self.node1_children) node6 = Node([["a", 1], ["b", 2]]) node7 = Node([("a", [1, 2])]) node8 = Node([("a", (1, 2))]) self.assertNotEqual(hash(self.node1), hash(self.node2)) self.assertNotEqual(hash(self.node1), hash(node3)) self.assertNotEqual(hash(self.node1), hash(node4)) self.assertEqual(hash(self.node1), hash(node5)) self.assertEqual(hash(self.node1), hash(node6)) self.assertEqual(hash(self.node2), hash(Node())) self.assertEqual(hash(node7), hash(node8)) def test_len(self): self.assertEqual(len(self.node1), 2) self.assertEqual(len(self.node2), 0) def test_bool(self): self.assertTrue(self.node1) self.assertFalse(self.node2) def test_contains(self): self.assertIn(("a", 1), self.node1) self.assertNotIn(("a", 1), self.node2) def test_add(self): # start with the same children of node1 then add an item node3 = Node(self.node1_children) node3_added_child = ("c", 3) # add() returns the added data self.assertEqual(node3.add(node3_added_child, Node.default), node3_added_child) # we added exactly one item, len() should reflect that self.assertEqual(len(self.node1) + 1, len(node3)) self.assertEqual(str(node3), "(DEFAULT: ('a', 1), ('b', 2), ('c', 3))") def test_add_eq_child_mixed_connector(self): node = Node(["a", "b"], OR) self.assertEqual(node.add("a", AND), "a") self.assertEqual(node, Node([Node(["a", "b"], OR), "a"], AND)) def test_negate(self): # negated is False by default self.assertFalse(self.node1.negated) self.node1.negate() self.assertTrue(self.node1.negated) self.node1.negate() self.assertFalse(self.node1.negated) def test_create(self): SubNode = type("SubNode", (Node,), {}) a = SubNode([SubNode(["a", "b"], OR), "c"], AND) b = SubNode.create(a.children, a.connector, a.negated) self.assertEqual(a, b) # Children lists are the same object, but equal. self.assertIsNot(a.children, b.children) self.assertEqual(a.children, b.children) # Child Node objects are the same objects. for a_child, b_child in zip(a.children, b.children): if isinstance(a_child, Node): self.assertIs(a_child, b_child) self.assertEqual(a_child, b_child) def test_copy(self): a = Node([Node(["a", "b"], OR), "c"], AND) b = copy.copy(a) self.assertEqual(a, b) # Children lists are the same object. self.assertIs(a.children, b.children) # Child Node objects are the same objects. for a_child, b_child in zip(a.children, b.children): if isinstance(a_child, Node): self.assertIs(a_child, b_child) self.assertEqual(a_child, b_child) def test_deepcopy(self): a = Node([Node(["a", "b"], OR), "c"], AND) b = copy.deepcopy(a) self.assertEqual(a, b) # Children lists are not be the same object, but equal. self.assertIsNot(a.children, b.children) self.assertEqual(a.children, b.children) # Child Node objects are not be the same objects. for a_child, b_child in zip(a.children, b.children): if isinstance(a_child, Node): self.assertIsNot(a_child, b_child) self.assertEqual(a_child, b_child) def test_eq_children(self): node = Node(self.node1_children) self.assertEqual(node, self.node1) self.assertNotEqual(node, self.node2) def test_eq_connector(self): new_node = Node(connector="NEW") default_node = Node(connector="DEFAULT") self.assertEqual(default_node, self.node2) self.assertNotEqual(default_node, new_node) def test_eq_negated(self): node = Node(negated=False) negated = Node(negated=True) self.assertNotEqual(negated, node)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_regex_helper.py
tests/utils_tests/test_regex_helper.py
import re import unittest from django.test import SimpleTestCase from django.utils import regex_helper class NormalizeTests(unittest.TestCase): def test_empty(self): pattern = r"" expected = [("", [])] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) def test_escape(self): pattern = r"\\\^\$\.\|\?\*\+\(\)\[" expected = [("\\^$.|?*+()[", [])] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) def test_group_positional(self): pattern = r"(.*)-(.+)" expected = [("%(_0)s-%(_1)s", ["_0", "_1"])] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) def test_group_noncapturing(self): pattern = r"(?:non-capturing)" expected = [("non-capturing", [])] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) def test_group_named(self): pattern = r"(?P<first_group_name>.*)-(?P<second_group_name>.*)" expected = [ ( "%(first_group_name)s-%(second_group_name)s", ["first_group_name", "second_group_name"], ) ] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) def test_group_backreference(self): pattern = r"(?P<first_group_name>.*)-(?P=first_group_name)" expected = [("%(first_group_name)s-%(first_group_name)s", ["first_group_name"])] result = regex_helper.normalize(pattern) self.assertEqual(result, expected) class LazyReCompileTests(SimpleTestCase): def test_flags_with_pre_compiled_regex(self): test_pattern = re.compile("test") lazy_test_pattern = regex_helper._lazy_re_compile(test_pattern, re.I) msg = "flags must be empty if regex is passed pre-compiled" with self.assertRaisesMessage(AssertionError, msg): lazy_test_pattern.match("TEST")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/utils.py
tests/utils_tests/utils.py
import platform def on_macos_with_hfs(): """ MacOS 10.13 (High Sierra) and lower can use HFS+ as a filesystem. HFS+ has a time resolution of only one second which can be too low for some of the tests. """ macos_version = platform.mac_ver()[0] if macos_version != "": parsed_macos_version = tuple(int(x) for x in macos_version.split(".")) return parsed_macos_version < (10, 14) return False
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_timesince.py
tests/utils_tests/test_timesince.py
import datetime import zoneinfo from django.test import TestCase from django.test.utils import override_settings, requires_tz_support from django.utils import timezone, translation from django.utils.timesince import timesince, timeuntil from django.utils.translation import npgettext_lazy class TimesinceTests(TestCase): def setUp(self): self.t = datetime.datetime(2007, 8, 14, 13, 46, 0) self.onemicrosecond = datetime.timedelta(microseconds=1) self.onesecond = datetime.timedelta(seconds=1) self.oneminute = datetime.timedelta(minutes=1) self.onehour = datetime.timedelta(hours=1) self.oneday = datetime.timedelta(days=1) self.oneweek = datetime.timedelta(days=7) self.onemonth = datetime.timedelta(days=31) self.oneyear = datetime.timedelta(days=366) def test_equal_datetimes(self): """equal datetimes.""" # NOTE: \xa0 avoids wrapping between value and unit self.assertEqual(timesince(self.t, self.t), "0\xa0minutes") def test_ignore_microseconds_and_seconds(self): """Microseconds and seconds are ignored.""" self.assertEqual( timesince(self.t, self.t + self.onemicrosecond), "0\xa0minutes" ) self.assertEqual(timesince(self.t, self.t + self.onesecond), "0\xa0minutes") def test_other_units(self): """Test other units.""" self.assertEqual(timesince(self.t, self.t + self.oneminute), "1\xa0minute") self.assertEqual(timesince(self.t, self.t + self.onehour), "1\xa0hour") self.assertEqual(timesince(self.t, self.t + self.oneday), "1\xa0day") self.assertEqual(timesince(self.t, self.t + self.oneweek), "1\xa0week") self.assertEqual(timesince(self.t, self.t + self.onemonth), "1\xa0month") self.assertEqual(timesince(self.t, self.t + self.oneyear), "1\xa0year") def test_multiple_units(self): """Test multiple units.""" self.assertEqual( timesince(self.t, self.t + 2 * self.oneday + 6 * self.onehour), "2\xa0days, 6\xa0hours", ) self.assertEqual( timesince(self.t, self.t + 2 * self.oneweek + 2 * self.oneday), "2\xa0weeks, 2\xa0days", ) def test_display_first_unit(self): """ If the two differing units aren't adjacent, only the first unit is displayed. """ self.assertEqual( timesince( self.t, self.t + 2 * self.oneweek + 3 * self.onehour + 4 * self.oneminute, ), "2\xa0weeks", ) self.assertEqual( timesince(self.t, self.t + 4 * self.oneday + 5 * self.oneminute), "4\xa0days", ) def test_display_second_before_first(self): """ When the second date occurs before the first, we should always get 0 minutes. """ self.assertEqual( timesince(self.t, self.t - self.onemicrosecond), "0\xa0minutes" ) self.assertEqual(timesince(self.t, self.t - self.onesecond), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.oneminute), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.onehour), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.oneday), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.oneweek), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.onemonth), "0\xa0minutes") self.assertEqual(timesince(self.t, self.t - self.oneyear), "0\xa0minutes") self.assertEqual( timesince(self.t, self.t - 2 * self.oneday - 6 * self.onehour), "0\xa0minutes", ) self.assertEqual( timesince(self.t, self.t - 2 * self.oneweek - 2 * self.oneday), "0\xa0minutes", ) self.assertEqual( timesince( self.t, self.t - 2 * self.oneweek - 3 * self.onehour - 4 * self.oneminute, ), "0\xa0minutes", ) self.assertEqual( timesince(self.t, self.t - 4 * self.oneday - 5 * self.oneminute), "0\xa0minutes", ) def test_second_before_equal_first_humanize_time_strings(self): time_strings = { "minute": npgettext_lazy( "naturaltime-future", "%(num)d minute", "%(num)d minutes", "num", ), } with translation.override("cs"): for now in [self.t, self.t - self.onemicrosecond, self.t - self.oneday]: with self.subTest(now): self.assertEqual( timesince(self.t, now, time_strings=time_strings), "0\xa0minut", ) @requires_tz_support def test_different_timezones(self): """When using two different timezones.""" now = datetime.datetime.now() now_tz = timezone.make_aware(now, timezone.get_default_timezone()) now_tz_i = timezone.localtime(now_tz, timezone.get_fixed_timezone(195)) self.assertEqual(timesince(now), "0\xa0minutes") self.assertEqual(timesince(now_tz), "0\xa0minutes") self.assertEqual(timesince(now_tz_i), "0\xa0minutes") self.assertEqual(timesince(now_tz, now_tz_i), "0\xa0minutes") self.assertEqual(timeuntil(now), "0\xa0minutes") self.assertEqual(timeuntil(now_tz), "0\xa0minutes") self.assertEqual(timeuntil(now_tz_i), "0\xa0minutes") self.assertEqual(timeuntil(now_tz, now_tz_i), "0\xa0minutes") def test_date_objects(self): """ Both timesince and timeuntil should work on date objects (#17937). """ today = datetime.date.today() self.assertEqual(timesince(today + self.oneday), "0\xa0minutes") self.assertEqual(timeuntil(today - self.oneday), "0\xa0minutes") def test_both_date_objects(self): """Timesince should work with both date objects (#9672)""" today = datetime.date.today() self.assertEqual(timeuntil(today + self.oneday, today), "1\xa0day") self.assertEqual(timeuntil(today - self.oneday, today), "0\xa0minutes") self.assertEqual(timeuntil(today + self.oneweek, today), "1\xa0week") def test_leap_year(self): start_date = datetime.date(2016, 12, 25) self.assertEqual(timeuntil(start_date + self.oneweek, start_date), "1\xa0week") self.assertEqual(timesince(start_date, start_date + self.oneweek), "1\xa0week") def test_leap_year_new_years_eve(self): t = datetime.date(2016, 12, 31) now = datetime.datetime(2016, 12, 31, 18, 0, 0) self.assertEqual(timesince(t + self.oneday, now), "0\xa0minutes") self.assertEqual(timeuntil(t - self.oneday, now), "0\xa0minutes") def test_naive_datetime_with_tzinfo_attribute(self): class naive(datetime.tzinfo): def utcoffset(self, dt): return None future = datetime.datetime(2080, 1, 1, tzinfo=naive()) self.assertEqual(timesince(future), "0\xa0minutes") past = datetime.datetime(1980, 1, 1, tzinfo=naive()) self.assertEqual(timeuntil(past), "0\xa0minutes") def test_thousand_years_ago(self): t = self.t.replace(year=self.t.year - 1000) self.assertEqual(timesince(t, self.t), "1000\xa0years") self.assertEqual(timeuntil(self.t, t), "1000\xa0years") def test_depth(self): t = ( self.t + self.oneyear + self.onemonth + self.oneweek + self.oneday + self.onehour ) tests = [ (t, 1, "1\xa0year"), (t, 2, "1\xa0year, 1\xa0month"), (t, 3, "1\xa0year, 1\xa0month, 1\xa0week"), (t, 4, "1\xa0year, 1\xa0month, 1\xa0week, 1\xa0day"), (t, 5, "1\xa0year, 1\xa0month, 1\xa0week, 1\xa0day, 1\xa0hour"), (t, 6, "1\xa0year, 1\xa0month, 1\xa0week, 1\xa0day, 1\xa0hour"), (self.t + self.onehour, 5, "1\xa0hour"), (self.t + (4 * self.oneminute), 3, "4\xa0minutes"), (self.t + self.onehour + self.oneminute, 1, "1\xa0hour"), (self.t + self.oneday + self.onehour, 1, "1\xa0day"), (self.t + self.oneweek + self.oneday, 1, "1\xa0week"), (self.t + self.onemonth + self.oneweek, 1, "1\xa0month"), (self.t + self.oneyear + self.onemonth, 1, "1\xa0year"), (self.t + self.oneyear + self.oneweek + self.oneday, 3, "1\xa0year"), ] for value, depth, expected in tests: with self.subTest(): self.assertEqual(timesince(self.t, value, depth=depth), expected) self.assertEqual(timeuntil(value, self.t, depth=depth), expected) def test_months_edge(self): t = datetime.datetime(2022, 1, 1) tests = [ (datetime.datetime(2022, 1, 31), "4\xa0weeks, 2\xa0days"), (datetime.datetime(2022, 2, 1), "1\xa0month"), (datetime.datetime(2022, 2, 28), "1\xa0month, 3\xa0weeks"), (datetime.datetime(2022, 3, 1), "2\xa0months"), (datetime.datetime(2022, 3, 31), "2\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 4, 1), "3\xa0months"), (datetime.datetime(2022, 4, 30), "3\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 5, 1), "4\xa0months"), (datetime.datetime(2022, 5, 31), "4\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 6, 1), "5\xa0months"), (datetime.datetime(2022, 6, 30), "5\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 7, 1), "6\xa0months"), (datetime.datetime(2022, 7, 31), "6\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 8, 1), "7\xa0months"), (datetime.datetime(2022, 8, 31), "7\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 9, 1), "8\xa0months"), (datetime.datetime(2022, 9, 30), "8\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 10, 1), "9\xa0months"), (datetime.datetime(2022, 10, 31), "9\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 11, 1), "10\xa0months"), (datetime.datetime(2022, 11, 30), "10\xa0months, 4\xa0weeks"), (datetime.datetime(2022, 12, 1), "11\xa0months"), (datetime.datetime(2022, 12, 31), "11\xa0months, 4\xa0weeks"), ] for value, expected in tests: with self.subTest(): self.assertEqual(timesince(t, value), expected) def test_depth_invalid(self): msg = "depth must be greater than 0." with self.assertRaisesMessage(ValueError, msg): timesince(self.t, self.t, depth=0) @requires_tz_support def test_less_than_a_day_with_zoneinfo(self): now_with_zoneinfo = timezone.now().astimezone( zoneinfo.ZoneInfo(key="Asia/Kathmandu") # UTC+05:45 ) tests = [ (now_with_zoneinfo, "0\xa0minutes"), (now_with_zoneinfo - self.onemicrosecond, "0\xa0minutes"), (now_with_zoneinfo - self.onesecond, "0\xa0minutes"), (now_with_zoneinfo - self.oneminute, "1\xa0minute"), (now_with_zoneinfo - self.onehour, "1\xa0hour"), ] for value, expected in tests: with self.subTest(value): self.assertEqual(timesince(value), expected) @requires_tz_support def test_less_than_a_day_cross_day_with_zoneinfo(self): now_with_zoneinfo = timezone.make_aware( datetime.datetime(2023, 4, 14, 1, 30, 30), zoneinfo.ZoneInfo(key="Asia/Kathmandu"), # UTC+05:45 ) now_utc = now_with_zoneinfo.astimezone(datetime.UTC) tests = [ (now_with_zoneinfo, "0\xa0minutes"), (now_with_zoneinfo - self.onemicrosecond, "0\xa0minutes"), (now_with_zoneinfo - self.onesecond, "0\xa0minutes"), (now_with_zoneinfo - self.oneminute, "1\xa0minute"), (now_with_zoneinfo - self.onehour, "1\xa0hour"), ] for value, expected in tests: with self.subTest(value): self.assertEqual(timesince(value, now_utc), expected) @requires_tz_support @override_settings(USE_TZ=True) class TZAwareTimesinceTests(TimesinceTests): def setUp(self): super().setUp() self.t = timezone.make_aware(self.t, timezone.get_default_timezone())
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_deconstruct.py
tests/utils_tests/test_deconstruct.py
from django.test import SimpleTestCase from django.utils.deconstruct import deconstructible from django.utils.version import get_docs_version @deconstructible() class DeconstructibleClass: pass class DeconstructibleChildClass(DeconstructibleClass): pass @deconstructible( path="utils_tests.deconstructible_classes.DeconstructibleWithPathClass" ) class DeconstructibleWithPathClass: pass class DeconstructibleWithPathChildClass(DeconstructibleWithPathClass): pass @deconstructible( path="utils_tests.deconstructible_classes.DeconstructibleInvalidPathClass", ) class DeconstructibleInvalidPathClass: pass class DeconstructibleInvalidPathChildClass(DeconstructibleInvalidPathClass): pass class DeconstructibleTests(SimpleTestCase): def test_deconstruct(self): obj = DeconstructibleClass("arg", key="value") path, args, kwargs = obj.deconstruct() self.assertEqual(path, "utils_tests.test_deconstruct.DeconstructibleClass") self.assertEqual(args, ("arg",)) self.assertEqual(kwargs, {"key": "value"}) def test_deconstruct_with_path(self): obj = DeconstructibleWithPathClass("arg", key="value") path, args, kwargs = obj.deconstruct() self.assertEqual( path, "utils_tests.deconstructible_classes.DeconstructibleWithPathClass", ) self.assertEqual(args, ("arg",)) self.assertEqual(kwargs, {"key": "value"}) def test_deconstruct_child(self): obj = DeconstructibleChildClass("arg", key="value") path, args, kwargs = obj.deconstruct() self.assertEqual(path, "utils_tests.test_deconstruct.DeconstructibleChildClass") self.assertEqual(args, ("arg",)) self.assertEqual(kwargs, {"key": "value"}) def test_deconstruct_child_with_path(self): obj = DeconstructibleWithPathChildClass("arg", key="value") path, args, kwargs = obj.deconstruct() self.assertEqual( path, "utils_tests.test_deconstruct.DeconstructibleWithPathChildClass", ) self.assertEqual(args, ("arg",)) self.assertEqual(kwargs, {"key": "value"}) def test_invalid_path(self): obj = DeconstructibleInvalidPathClass() docs_version = get_docs_version() msg = ( f"Could not find object DeconstructibleInvalidPathClass in " f"utils_tests.deconstructible_classes.\n" f"Please note that you cannot serialize things like inner " f"classes. Please move the object into the main module body to " f"use migrations.\n" f"For more information, see " f"https://docs.djangoproject.com/en/{docs_version}/topics/" f"migrations/#serializing-values" ) with self.assertRaisesMessage(ValueError, msg): obj.deconstruct() def test_parent_invalid_path(self): obj = DeconstructibleInvalidPathChildClass("arg", key="value") path, args, kwargs = obj.deconstruct() self.assertEqual( path, "utils_tests.test_deconstruct.DeconstructibleInvalidPathChildClass", ) self.assertEqual(args, ("arg",)) self.assertEqual(kwargs, {"key": "value"})
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_ipv6.py
tests/utils_tests/test_ipv6.py
import traceback from decimal import Decimal from io import StringIO from ipaddress import IPv6Address from django.core.exceptions import ValidationError from django.test import SimpleTestCase from django.utils.ipv6 import ( MAX_IPV6_ADDRESS_LENGTH, clean_ipv6_address, is_valid_ipv6_address, ) class TestUtilsIPv6(SimpleTestCase): def test_validates_correct_plain_address(self): self.assertTrue(is_valid_ipv6_address("fe80::223:6cff:fe8a:2e8a")) self.assertTrue(is_valid_ipv6_address("2a02::223:6cff:fe8a:2e8a")) self.assertTrue(is_valid_ipv6_address("1::2:3:4:5:6:7")) self.assertTrue(is_valid_ipv6_address("::")) self.assertTrue(is_valid_ipv6_address("::a")) self.assertTrue(is_valid_ipv6_address("2::")) def test_validates_correct_with_v4mapping(self): self.assertTrue(is_valid_ipv6_address("::ffff:254.42.16.14")) self.assertTrue(is_valid_ipv6_address("::ffff:0a0a:0a0a")) def test_validates_correct_with_ipv6_instance(self): cases = [ IPv6Address("::ffff:2.125.160.216"), IPv6Address("fe80::1"), IPv6Address("::"), ] for case in cases: with self.subTest(case=case): self.assertIs(is_valid_ipv6_address(case), True) def test_validates_incorrect_plain_address(self): self.assertFalse(is_valid_ipv6_address("foo")) self.assertFalse(is_valid_ipv6_address("127.0.0.1")) self.assertFalse(is_valid_ipv6_address("12345::")) self.assertFalse(is_valid_ipv6_address("1::2:3::4")) self.assertFalse(is_valid_ipv6_address("1::zzz")) self.assertFalse(is_valid_ipv6_address("1::2:3:4:5:6:7:8")) self.assertFalse(is_valid_ipv6_address("1:2")) self.assertFalse(is_valid_ipv6_address("1:::2")) self.assertFalse(is_valid_ipv6_address("fe80::223: 6cff:fe8a:2e8a")) self.assertFalse(is_valid_ipv6_address("2a02::223:6cff :fe8a:2e8a")) def test_validates_incorrect_with_v4mapping(self): self.assertFalse(is_valid_ipv6_address("::ffff:999.42.16.14")) self.assertFalse(is_valid_ipv6_address("::ffff:zzzz:0a0a")) # The ::1.2.3.4 format used to be valid but was deprecated # in RFC 4291 section 2.5.5.1. self.assertTrue(is_valid_ipv6_address("::254.42.16.14")) self.assertTrue(is_valid_ipv6_address("::0a0a:0a0a")) self.assertFalse(is_valid_ipv6_address("::999.42.16.14")) self.assertFalse(is_valid_ipv6_address("::zzzz:0a0a")) def test_validates_incorrect_with_non_string(self): cases = [None, [], {}, (), Decimal("2.46"), 192.168, 42] for case in cases: with self.subTest(case=case): self.assertIs(is_valid_ipv6_address(case), False) def test_cleans_plain_address(self): self.assertEqual(clean_ipv6_address("DEAD::0:BEEF"), "dead::beef") self.assertEqual( clean_ipv6_address("2001:000:a:0000:0:fe:fe:beef"), "2001:0:a::fe:fe:beef" ) self.assertEqual( clean_ipv6_address("2001::a:0000:0:fe:fe:beef"), "2001:0:a::fe:fe:beef" ) def test_cleans_with_v4_mapping(self): self.assertEqual(clean_ipv6_address("::ffff:0a0a:0a0a"), "::ffff:10.10.10.10") self.assertEqual(clean_ipv6_address("::ffff:1234:1234"), "::ffff:18.52.18.52") self.assertEqual(clean_ipv6_address("::ffff:18.52.18.52"), "::ffff:18.52.18.52") self.assertEqual(clean_ipv6_address("::ffff:0.52.18.52"), "::ffff:0.52.18.52") self.assertEqual(clean_ipv6_address("::ffff:0.0.0.0"), "::ffff:0.0.0.0") def test_unpacks_ipv4(self): self.assertEqual( clean_ipv6_address("::ffff:0a0a:0a0a", unpack_ipv4=True), "10.10.10.10" ) self.assertEqual( clean_ipv6_address("::ffff:1234:1234", unpack_ipv4=True), "18.52.18.52" ) self.assertEqual( clean_ipv6_address("::ffff:18.52.18.52", unpack_ipv4=True), "18.52.18.52" ) def test_address_too_long(self): addresses = [ "0000:0000:0000:0000:0000:ffff:192.168.100.228", # IPv4-mapped IPv6 address "0000:0000:0000:0000:0000:ffff:192.168.100.228%123456", # % scope/zone "fe80::223:6cff:fe8a:2e8a:1234:5678:00000", # MAX_IPV6_ADDRESS_LENGTH + 1 ] msg = "This is the error message." value_error_msg = "Unable to convert %s to an IPv6 address (value too long)." for addr in addresses: with self.subTest(addr=addr): self.assertGreater(len(addr), MAX_IPV6_ADDRESS_LENGTH) self.assertEqual(is_valid_ipv6_address(addr), False) with self.assertRaisesMessage(ValidationError, msg) as ctx: clean_ipv6_address(addr, error_message=msg) exception_traceback = StringIO() traceback.print_exception(ctx.exception, file=exception_traceback) self.assertIn(value_error_msg % addr, exception_traceback.getvalue())
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_text.py
tests/utils_tests/test_text.py
import json import sys from unittest.mock import patch from django.core.exceptions import SuspiciousFileOperation from django.test import SimpleTestCase from django.utils import text from django.utils.functional import lazystr from django.utils.text import format_lazy from django.utils.translation import gettext_lazy, override IS_WIDE_BUILD = len("\U0001f4a9") == 1 class TestUtilsText(SimpleTestCase): def test_get_text_list(self): self.assertEqual(text.get_text_list(["a", "b", "c", "d"]), "a, b, c or d") self.assertEqual(text.get_text_list(["a", "b", "c"], "and"), "a, b and c") self.assertEqual(text.get_text_list(["a", "b"], "and"), "a and b") self.assertEqual(text.get_text_list(["a"]), "a") self.assertEqual(text.get_text_list([]), "") with override("ar"): self.assertEqual(text.get_text_list(["a", "b", "c"]), "a، b أو c") def test_smart_split(self): testdata = [ ('This is "a person" test.', ["This", "is", '"a person"', "test."]), ('This is "a person\'s" test.', ["This", "is", '"a person\'s"', "test."]), ('This is "a person\\"s" test.', ["This", "is", '"a person\\"s"', "test."]), ("\"a 'one", ['"a', "'one"]), ("all friends' tests", ["all", "friends'", "tests"]), ( 'url search_page words="something else"', ["url", "search_page", 'words="something else"'], ), ( "url search_page words='something else'", ["url", "search_page", "words='something else'"], ), ( 'url search_page words "something else"', ["url", "search_page", "words", '"something else"'], ), ( 'url search_page words-"something else"', ["url", "search_page", 'words-"something else"'], ), ("url search_page words=hello", ["url", "search_page", "words=hello"]), ( 'url search_page words="something else', ["url", "search_page", 'words="something', "else"], ), ("cut:','|cut:' '", ["cut:','|cut:' '"]), (lazystr("a b c d"), ["a", "b", "c", "d"]), # Test for #20231 ] for test, expected in testdata: with self.subTest(value=test): self.assertEqual(list(text.smart_split(test)), expected) def test_truncate_chars(self): truncator = text.Truncator("The quick brown fox jumped over the lazy dog.") self.assertEqual( "The quick brown fox jumped over the lazy dog.", truncator.chars(100) ), self.assertEqual("The quick brown fox …", truncator.chars(21)) self.assertEqual("The quick brown fo.....", truncator.chars(23, ".....")) self.assertEqual(".....", truncator.chars(4, ".....")) nfc = text.Truncator("o\xfco\xfco\xfco\xfc") nfd = text.Truncator("ou\u0308ou\u0308ou\u0308ou\u0308") self.assertEqual("oüoüoüoü", nfc.chars(8)) self.assertEqual("oüoüoüoü", nfd.chars(8)) self.assertEqual("oü…", nfc.chars(3)) self.assertEqual("oü…", nfd.chars(3)) # Ensure the final length is calculated correctly when there are # combining characters with no precomposed form, and that combining # characters are not split up. truncator = text.Truncator("-B\u030aB\u030a----8") self.assertEqual("-B\u030a…", truncator.chars(3)) self.assertEqual("-B\u030aB\u030a-…", truncator.chars(5)) self.assertEqual("-B\u030aB\u030a----8", truncator.chars(8)) # Ensure the length of the end text is correctly calculated when it # contains combining characters with no precomposed form. truncator = text.Truncator("-----") self.assertEqual("---B\u030a", truncator.chars(4, "B\u030a")) self.assertEqual("-----", truncator.chars(5, "B\u030a")) # Make a best effort to shorten to the desired length, but requesting # a length shorter than the ellipsis shouldn't break self.assertEqual("...", text.Truncator("asdf").chars(1, truncate="...")) # lazy strings are handled correctly self.assertEqual( text.Truncator(lazystr("The quick brown fox")).chars(10), "The quick…" ) def test_truncate_chars_html(self): truncator = text.Truncator( '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>' "</strong></p>" ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>' "</strong></p>", truncator.chars(80, html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>' "</strong></p>", truncator.chars(46, html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog…</em>' "</strong></p>", truncator.chars(45, html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick…</em></strong></p>', truncator.chars(10, html=True), ) self.assertEqual( '<p id="par"><strong><em>…</em></strong></p>', truncator.chars(1, html=True), ) self.assertEqual("", truncator.chars(0, html=True)) self.assertEqual("", truncator.chars(-1, html=True)) self.assertEqual( '<p id="par"><strong><em>The qu....</em></strong></p>', truncator.chars(10, "....", html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick </em></strong></p>', truncator.chars(10, "", html=True), ) truncator = text.Truncator("foo</p>") self.assertEqual("foo</p>", truncator.chars(5, html=True)) @patch("django.utils.text.Truncator.MAX_LENGTH_HTML", 10_000) def test_truncate_chars_html_size_limit(self): max_len = text.Truncator.MAX_LENGTH_HTML bigger_len = text.Truncator.MAX_LENGTH_HTML + 1 valid_html = "<p>Joel is a slug</p>" # 14 chars perf_test_values = [ ("</a" + "\t" * (max_len - 6) + "//>", "</a>"), ("</p" + "\t" * bigger_len + "//>", "</p>"), ("&" * bigger_len, ""), ("_X<<<<<<<<<<<>", "_X&lt;&lt;&lt;&lt;&lt;&lt;&lt;…"), (valid_html * bigger_len, "<p>Joel is a…</p>"), # 10 chars ] for value, expected in perf_test_values: with self.subTest(value=value): truncator = text.Truncator(value) self.assertEqual(expected, truncator.chars(10, html=True)) def test_truncate_chars_html_with_newline_inside_tag(self): truncator = text.Truncator( '<p>The quick <a href="xyz.html"\n id="mylink">brown fox</a> jumped over ' "the lazy dog.</p>" ) self.assertEqual( '<p>The quick <a href="xyz.html"\n id="mylink">brow…</a></p>', truncator.chars(15, html=True), ) self.assertEqual( "<p>Th…</p>", truncator.chars(3, html=True), ) def test_truncate_chars_html_with_void_elements(self): truncator = text.Truncator( "<br/>The <hr />quick brown fox jumped over the lazy dog." ) self.assertEqual("<br/>The <hr />quick brown…", truncator.chars(16, html=True)) truncator = text.Truncator( "<br>The <hr/>quick <em>brown fox</em> jumped over the lazy dog." ) self.assertEqual( "<br>The <hr/>quick <em>brown…</em>", truncator.chars(16, html=True) ) self.assertEqual("<br>The <hr/>q…", truncator.chars(6, html=True)) self.assertEqual("<br>The <hr/>…", truncator.chars(5, html=True)) self.assertEqual("<br>The…", truncator.chars(4, html=True)) self.assertEqual("<br>Th…", truncator.chars(3, html=True)) def test_truncate_chars_html_with_html_entities(self): truncator = text.Truncator( "<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo est&aacute;?</i>" ) self.assertEqual( "<i>Buenos días! ¿Cómo está?</i>", truncator.chars(40, html=True), ) self.assertEqual( "<i>Buenos días…</i>", truncator.chars(12, html=True), ) self.assertEqual( "<i>Buenos días! ¿Cómo está…</i>", truncator.chars(24, html=True), ) truncator = text.Truncator("<p>I &lt;3 python, what about you?</p>") self.assertEqual("<p>I &lt;3 python, wh…</p>", truncator.chars(16, html=True)) def test_truncate_words(self): truncator = text.Truncator("The quick brown fox jumped over the lazy dog.") self.assertEqual( "The quick brown fox jumped over the lazy dog.", truncator.words(10) ) self.assertEqual("The quick brown fox…", truncator.words(4)) self.assertEqual("The quick brown fox[snip]", truncator.words(4, "[snip]")) # lazy strings are handled correctly truncator = text.Truncator( lazystr("The quick brown fox jumped over the lazy dog.") ) self.assertEqual("The quick brown fox…", truncator.words(4)) self.assertEqual("", truncator.words(0)) self.assertEqual("", truncator.words(-1)) def test_truncate_html_words(self): truncator = text.Truncator( '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>' "</strong></p>" ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>' "</strong></p>", truncator.words(10, html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox…</em></strong></p>', truncator.words(4, html=True), ) self.assertEqual( "", truncator.words(0, html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox....</em></strong></p>', truncator.words(4, "....", html=True), ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox</em></strong></p>', truncator.words(4, "", html=True), ) truncator = text.Truncator( "<p>The quick \t brown fox jumped over the lazy dog.</p>" ) self.assertEqual( "<p>The quick brown fox…</p>", truncator.words(4, html=True), ) # Test with new line inside tag truncator = text.Truncator( '<p>The quick <a href="xyz.html"\n id="mylink">brown fox</a> jumped over ' "the lazy dog.</p>" ) self.assertEqual( '<p>The quick <a href="xyz.html"\n id="mylink">brown…</a></p>', truncator.words(3, html=True), ) self.assertEqual( "<p>The…</p>", truncator.words(1, html=True), ) # Test self-closing tags truncator = text.Truncator( "<br/>The <hr />quick brown fox jumped over the lazy dog." ) self.assertEqual("<br/>The <hr />quick brown…", truncator.words(3, html=True)) truncator = text.Truncator( "<br>The <hr/>quick <em>brown fox</em> jumped over the lazy dog." ) self.assertEqual( "<br>The <hr/>quick <em>brown…</em>", truncator.words(3, html=True) ) # Test html entities truncator = text.Truncator( "<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo est&aacute;?</i>" ) self.assertEqual( "<i>Buenos días! ¿Cómo…</i>", truncator.words(3, html=True), ) truncator = text.Truncator("<p>I &lt;3 python, what about you?</p>") self.assertEqual("<p>I &lt;3 python,…</p>", truncator.words(3, html=True)) truncator = text.Truncator("foo</p>") self.assertEqual("foo</p>", truncator.words(3, html=True)) # Only open brackets. truncator = text.Truncator("<" * 60_000) self.assertEqual(truncator.words(1, html=True), "&lt;…") # Tags with special chars in attrs. truncator = text.Truncator( """<i style="margin: 5%; font: *;">Hello, my dear lady!</i>""" ) self.assertEqual( """<i style="margin: 5%; font: *;">Hello, my dear…</i>""", truncator.words(3, html=True), ) # Tags with special non-latin chars in attrs. truncator = text.Truncator("""<p data-x="א">Hello, my dear lady!</p>""") self.assertEqual( """<p data-x="א">Hello, my dear…</p>""", truncator.words(3, html=True), ) # Misplaced brackets. truncator = text.Truncator("hello >< world") self.assertEqual(truncator.words(1, html=True), "hello…") self.assertEqual(truncator.words(2, html=True), "hello &gt;…") self.assertEqual(truncator.words(3, html=True), "hello &gt;&lt;…") self.assertEqual(truncator.words(4, html=True), "hello &gt;&lt; world") @patch("django.utils.text.Truncator.MAX_LENGTH_HTML", 10_000) def test_truncate_words_html_size_limit(self): max_len = text.Truncator.MAX_LENGTH_HTML bigger_len = text.Truncator.MAX_LENGTH_HTML + 1 valid_html = "<p>Joel is a slug</p>" # 4 words perf_test_values = [ ("</a" + "\t" * (max_len - 6) + "//>", "</a>"), ("</p" + "\t" * bigger_len + "//>", "</p>"), ("&" * max_len, ""), ("&" * bigger_len, ""), ("_X<<<<<<<<<<<>", "_X&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&gt;"), (valid_html * bigger_len, valid_html * 12 + "<p>Joel is…</p>"), # 50 words ] for value, expected in perf_test_values: with self.subTest(value=value): truncator = text.Truncator(value) self.assertEqual(expected, truncator.words(50, html=True)) def test_wrap(self): digits = "1234 67 9" self.assertEqual(text.wrap(digits, 100), "1234 67 9") self.assertEqual(text.wrap(digits, 9), "1234 67 9") self.assertEqual(text.wrap(digits, 8), "1234 67\n9") self.assertEqual(text.wrap("short\na long line", 7), "short\na long\nline") self.assertEqual( text.wrap("do-not-break-long-words please? ok", 8), "do-not-break-long-words\nplease?\nok", ) long_word = "l%sng" % ("o" * 20) self.assertEqual(text.wrap(long_word, 20), long_word) self.assertEqual( text.wrap("a %s word" % long_word, 10), "a\n%s\nword" % long_word ) self.assertEqual(text.wrap(lazystr(digits), 100), "1234 67 9") def test_normalize_newlines(self): self.assertEqual( text.normalize_newlines("abc\ndef\rghi\r\n"), "abc\ndef\nghi\n" ) self.assertEqual(text.normalize_newlines("\n\r\r\n\r"), "\n\n\n\n") self.assertEqual(text.normalize_newlines("abcdefghi"), "abcdefghi") self.assertEqual(text.normalize_newlines(""), "") self.assertEqual( text.normalize_newlines(lazystr("abc\ndef\rghi\r\n")), "abc\ndef\nghi\n" ) def test_phone2numeric(self): numeric = text.phone2numeric("0800 flowers") self.assertEqual(numeric, "0800 3569377") lazy_numeric = lazystr(text.phone2numeric("0800 flowers")) self.assertEqual(lazy_numeric, "0800 3569377") def test_slugify(self): items = ( # given - expected - Unicode? ("Hello, World!", "hello-world", False), ("spam & eggs", "spam-eggs", False), (" multiple---dash and space ", "multiple-dash-and-space", False), ("\t whitespace-in-value \n", "whitespace-in-value", False), ("underscore_in-value", "underscore_in-value", False), ("__strip__underscore-value___", "strip__underscore-value", False), ("--strip-dash-value---", "strip-dash-value", False), ("__strip-mixed-value---", "strip-mixed-value", False), ("_ -strip-mixed-value _-", "strip-mixed-value", False), ("spam & ıçüş", "spam-ıçüş", True), ("foo ıç bar", "foo-ıç-bar", True), (" foo ıç bar", "foo-ıç-bar", True), ("你好", "你好", True), ("İstanbul", "istanbul", True), ) for value, output, is_unicode in items: with self.subTest(value=value): self.assertEqual(text.slugify(value, allow_unicode=is_unicode), output) # Interning the result may be useful, e.g. when fed to Path. with self.subTest("intern"): self.assertEqual(sys.intern(text.slugify("a")), "a") def test_unescape_string_literal(self): items = [ ('"abc"', "abc"), ("'abc'", "abc"), ('"a "bc""', 'a "bc"'), ("''ab' c'", "'ab' c"), ] for value, output in items: with self.subTest(value=value): self.assertEqual(text.unescape_string_literal(value), output) self.assertEqual(text.unescape_string_literal(lazystr(value)), output) def test_unescape_string_literal_invalid_value(self): items = ["", "abc", "'abc\""] for item in items: msg = f"Not a string literal: {item!r}" with self.assertRaisesMessage(ValueError, msg): text.unescape_string_literal(item) def test_get_valid_filename(self): filename = "^&'@{}[],$=!-#()%+~_123.txt" self.assertEqual(text.get_valid_filename(filename), "-_123.txt") self.assertEqual(text.get_valid_filename(lazystr(filename)), "-_123.txt") msg = "Could not derive file name from '???'" with self.assertRaisesMessage(SuspiciousFileOperation, msg): text.get_valid_filename("???") # After sanitizing this would yield '..'. msg = "Could not derive file name from '$.$.$'" with self.assertRaisesMessage(SuspiciousFileOperation, msg): text.get_valid_filename("$.$.$") def test_compress_sequence(self): data = [{"key": i} for i in range(10)] seq = list(json.JSONEncoder().iterencode(data)) seq = [s.encode() for s in seq] actual_length = len(b"".join(seq)) out = text.compress_sequence(seq) compressed_length = len(b"".join(out)) self.assertLess(compressed_length, actual_length) def test_format_lazy(self): self.assertEqual("django/test", format_lazy("{}/{}", "django", lazystr("test"))) self.assertEqual("django/test", format_lazy("{0}/{1}", *("django", "test"))) self.assertEqual( "django/test", format_lazy("{a}/{b}", **{"a": "django", "b": "test"}) ) self.assertEqual( "django/test", format_lazy("{a[0]}/{a[1]}", a=("django", "test")) ) t = {} s = format_lazy("{0[a]}-{p[a]}", t, p=t) t["a"] = lazystr("django") self.assertEqual("django-django", s) t["a"] = "update" self.assertEqual("update-update", s) # The format string can be lazy. (string comes from contrib.admin) s = format_lazy( gettext_lazy("Added {name} “{object}”."), name="article", object="My first try", ) with override("fr"): self.assertEqual("Ajout de article «\xa0My first try\xa0».", s)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_no_submodule.py
tests/utils_tests/test_no_submodule.py
# Used to test for modules which don't have submodules.
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_choices.py
tests/utils_tests/test_choices.py
import collections.abc from unittest import mock from django.db.models import TextChoices from django.test import SimpleTestCase from django.utils.choices import ( BaseChoiceIterator, CallableChoiceIterator, flatten_choices, normalize_choices, ) from django.utils.translation import gettext_lazy as _ class SimpleChoiceIterator(BaseChoiceIterator): def __iter__(self): return ((i, f"Item #{i}") for i in range(1, 4)) class ChoiceIteratorTests(SimpleTestCase): def test_not_implemented_error_on_missing_iter(self): class InvalidChoiceIterator(BaseChoiceIterator): pass # Not overriding __iter__(). msg = "BaseChoiceIterator subclasses must implement __iter__()." with self.assertRaisesMessage(NotImplementedError, msg): iter(InvalidChoiceIterator()) def test_eq(self): unrolled = [(1, "Item #1"), (2, "Item #2"), (3, "Item #3")] self.assertEqual(SimpleChoiceIterator(), unrolled) self.assertEqual(unrolled, SimpleChoiceIterator()) def test_eq_instances(self): self.assertEqual(SimpleChoiceIterator(), SimpleChoiceIterator()) def test_not_equal_subset(self): self.assertNotEqual(SimpleChoiceIterator(), [(1, "Item #1"), (2, "Item #2")]) def test_not_equal_superset(self): self.assertNotEqual( SimpleChoiceIterator(), [(1, "Item #1"), (2, "Item #2"), (3, "Item #3"), None], ) def test_getitem(self): choices = SimpleChoiceIterator() for i, expected in [(0, (1, "Item #1")), (-1, (3, "Item #3"))]: with self.subTest(index=i): self.assertEqual(choices[i], expected) def test_getitem_indexerror(self): choices = SimpleChoiceIterator() for i in (4, -4): with self.subTest(index=i): with self.assertRaises(IndexError) as ctx: choices[i] self.assertTrue(str(ctx.exception).endswith("index out of range")) class FlattenChoicesTests(SimpleTestCase): def test_empty(self): def generator(): yield from () for choices in ({}, [], (), set(), frozenset(), generator(), None, ""): with self.subTest(choices=choices): result = flatten_choices(choices) self.assertIsInstance(result, collections.abc.Generator) self.assertEqual(list(result), []) def test_non_empty(self): choices = [ ("C", _("Club")), ("D", _("Diamond")), ("H", _("Heart")), ("S", _("Spade")), ] result = flatten_choices(choices) self.assertIsInstance(result, collections.abc.Generator) self.assertEqual(list(result), choices) def test_nested_choices(self): choices = [ ("Audio", [("vinyl", _("Vinyl")), ("cd", _("CD"))]), ("Video", [("vhs", _("VHS Tape")), ("dvd", _("DVD"))]), ("unknown", _("Unknown")), ] expected = [ ("vinyl", _("Vinyl")), ("cd", _("CD")), ("vhs", _("VHS Tape")), ("dvd", _("DVD")), ("unknown", _("Unknown")), ] result = flatten_choices(choices) self.assertIsInstance(result, collections.abc.Generator) self.assertEqual(list(result), expected) class NormalizeFieldChoicesTests(SimpleTestCase): expected = [ ("C", _("Club")), ("D", _("Diamond")), ("H", _("Heart")), ("S", _("Spade")), ] expected_nested = [ ("Audio", [("vinyl", _("Vinyl")), ("cd", _("CD"))]), ("Video", [("vhs", _("VHS Tape")), ("dvd", _("DVD"))]), ("unknown", _("Unknown")), ] invalid = [ 1j, 123, 123.45, "invalid", b"invalid", _("invalid"), object(), None, True, False, ] invalid_iterable = [ # Special cases of a string-likes which would unpack incorrectly. ["ab"], [b"ab"], [_("ab")], # Non-iterable items or iterable items with incorrect number of # elements that cannot be unpacked. [123], [("value",)], [("value", "label", "other")], ] invalid_nested = [ # Nested choices can only be two-levels deep, so return callables, # mappings, iterables, etc. at deeper levels unmodified. [("Group", [("Value", lambda: "Label")])], [("Group", [("Value", {"Label 1?": "Label 2?"})])], [("Group", [("Value", [("Label 1?", "Label 2?")])])], ] def test_empty(self): def generator(): yield from () for choices in ({}, [], (), set(), frozenset(), generator()): with self.subTest(choices=choices): self.assertEqual(normalize_choices(choices), []) def test_choices(self): class Medal(TextChoices): GOLD = "GOLD", _("Gold") SILVER = "SILVER", _("Silver") BRONZE = "BRONZE", _("Bronze") expected = [ ("GOLD", _("Gold")), ("SILVER", _("Silver")), ("BRONZE", _("Bronze")), ] self.assertEqual(normalize_choices(Medal), expected) def test_callable(self): def get_choices(): return { "C": _("Club"), "D": _("Diamond"), "H": _("Heart"), "S": _("Spade"), } get_choices_spy = mock.Mock(wraps=get_choices) output = normalize_choices(get_choices_spy) get_choices_spy.assert_not_called() self.assertIsInstance(output, CallableChoiceIterator) self.assertEqual(output, self.expected) get_choices_spy.assert_called_once() def test_mapping(self): choices = { "C": _("Club"), "D": _("Diamond"), "H": _("Heart"), "S": _("Spade"), } self.assertEqual(normalize_choices(choices), self.expected) def test_iterable(self): choices = [ ("C", _("Club")), ("D", _("Diamond")), ("H", _("Heart")), ("S", _("Spade")), ] self.assertEqual(normalize_choices(choices), self.expected) def test_iterator(self): def generator(): yield "C", _("Club") yield "D", _("Diamond") yield "H", _("Heart") yield "S", _("Spade") choices = generator() self.assertEqual(normalize_choices(choices), self.expected) def test_nested_callable(self): def get_audio_choices(): return [("vinyl", _("Vinyl")), ("cd", _("CD"))] def get_video_choices(): return [("vhs", _("VHS Tape")), ("dvd", _("DVD"))] def get_media_choices(): return [ ("Audio", get_audio_choices), ("Video", get_video_choices), ("unknown", _("Unknown")), ] get_media_choices_spy = mock.Mock(wraps=get_media_choices) output = normalize_choices(get_media_choices_spy) get_media_choices_spy.assert_not_called() self.assertIsInstance(output, CallableChoiceIterator) self.assertEqual(output, self.expected_nested) get_media_choices_spy.assert_called_once() def test_nested_mapping(self): choices = { "Audio": {"vinyl": _("Vinyl"), "cd": _("CD")}, "Video": {"vhs": _("VHS Tape"), "dvd": _("DVD")}, "unknown": _("Unknown"), } self.assertEqual(normalize_choices(choices), self.expected_nested) def test_nested_iterable(self): choices = [ ("Audio", [("vinyl", _("Vinyl")), ("cd", _("CD"))]), ("Video", [("vhs", _("VHS Tape")), ("dvd", _("DVD"))]), ("unknown", _("Unknown")), ] self.assertEqual(normalize_choices(choices), self.expected_nested) def test_nested_iterator(self): def generate_audio_choices(): yield "vinyl", _("Vinyl") yield "cd", _("CD") def generate_video_choices(): yield "vhs", _("VHS Tape") yield "dvd", _("DVD") def generate_media_choices(): yield "Audio", generate_audio_choices() yield "Video", generate_video_choices() yield "unknown", _("Unknown") choices = generate_media_choices() self.assertEqual(normalize_choices(choices), self.expected_nested) def test_callable_non_canonical(self): # Canonical form is list of 2-tuple, but nested lists should work. def get_choices(): return [ ["C", _("Club")], ["D", _("Diamond")], ["H", _("Heart")], ["S", _("Spade")], ] get_choices_spy = mock.Mock(wraps=get_choices) output = normalize_choices(get_choices_spy) get_choices_spy.assert_not_called() self.assertIsInstance(output, CallableChoiceIterator) self.assertEqual(output, self.expected) get_choices_spy.assert_called_once() def test_iterable_non_canonical(self): # Canonical form is list of 2-tuple, but nested lists should work. choices = [ ["C", _("Club")], ["D", _("Diamond")], ["H", _("Heart")], ["S", _("Spade")], ] self.assertEqual(normalize_choices(choices), self.expected) def test_iterator_non_canonical(self): # Canonical form is list of 2-tuple, but nested lists should work. def generator(): yield ["C", _("Club")] yield ["D", _("Diamond")] yield ["H", _("Heart")] yield ["S", _("Spade")] choices = generator() self.assertEqual(normalize_choices(choices), self.expected) def test_nested_callable_non_canonical(self): # Canonical form is list of 2-tuple, but nested lists should work. def get_audio_choices(): return [["vinyl", _("Vinyl")], ["cd", _("CD")]] def get_video_choices(): return [["vhs", _("VHS Tape")], ["dvd", _("DVD")]] def get_media_choices(): return [ ["Audio", get_audio_choices], ["Video", get_video_choices], ["unknown", _("Unknown")], ] get_media_choices_spy = mock.Mock(wraps=get_media_choices) output = normalize_choices(get_media_choices_spy) get_media_choices_spy.assert_not_called() self.assertIsInstance(output, CallableChoiceIterator) self.assertEqual(output, self.expected_nested) get_media_choices_spy.assert_called_once() def test_nested_iterable_non_canonical(self): # Canonical form is list of 2-tuple, but nested lists should work. choices = [ ["Audio", [["vinyl", _("Vinyl")], ["cd", _("CD")]]], ["Video", [["vhs", _("VHS Tape")], ["dvd", _("DVD")]]], ["unknown", _("Unknown")], ] self.assertEqual(normalize_choices(choices), self.expected_nested) def test_nested_iterator_non_canonical(self): # Canonical form is list of 2-tuple, but nested lists should work. def generator(): yield ["Audio", [["vinyl", _("Vinyl")], ["cd", _("CD")]]] yield ["Video", [["vhs", _("VHS Tape")], ["dvd", _("DVD")]]] yield ["unknown", _("Unknown")] choices = generator() self.assertEqual(normalize_choices(choices), self.expected_nested) def test_nested_mixed_mapping_and_iterable(self): # Although not documented, as it's better to stick to either mappings # or iterables, nesting of mappings within iterables and vice versa # works and is likely to occur in the wild. This is supported by the # recursive call to `normalize_choices()` which will normalize nested # choices. choices = { "Audio": [("vinyl", _("Vinyl")), ("cd", _("CD"))], "Video": [("vhs", _("VHS Tape")), ("dvd", _("DVD"))], "unknown": _("Unknown"), } self.assertEqual(normalize_choices(choices), self.expected_nested) choices = [ ("Audio", {"vinyl": _("Vinyl"), "cd": _("CD")}), ("Video", {"vhs": _("VHS Tape"), "dvd": _("DVD")}), ("unknown", _("Unknown")), ] self.assertEqual(normalize_choices(choices), self.expected_nested) def test_iterable_set(self): # Although not documented, as sets are unordered which results in # randomised order in form fields, passing a set of 2-tuples works. # Consistent ordering of choices on model fields in migrations is # enforced by the migrations serializer. choices = { ("C", _("Club")), ("D", _("Diamond")), ("H", _("Heart")), ("S", _("Spade")), } self.assertEqual(sorted(normalize_choices(choices)), sorted(self.expected)) def test_unsupported_values_returned_unmodified(self): # Unsupported values must be returned unmodified for model system check # to work correctly. for value in self.invalid + self.invalid_iterable + self.invalid_nested: with self.subTest(value=value): self.assertEqual(normalize_choices(value), value) def test_unsupported_values_from_callable_returned_unmodified(self): for value in self.invalid_iterable + self.invalid_nested: with self.subTest(value=value): self.assertEqual(normalize_choices(lambda: value), value) def test_unsupported_values_from_iterator_returned_unmodified(self): for value in self.invalid_nested: with self.subTest(value=value): self.assertEqual( normalize_choices((lambda: (yield from value))()), value, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_simplelazyobject.py
tests/utils_tests/test_simplelazyobject.py
import pickle from django.contrib.auth.models import User from django.test import TestCase from django.utils.functional import SimpleLazyObject class TestUtilsSimpleLazyObjectDjangoTestCase(TestCase): def test_pickle(self): user = User.objects.create_user("johndoe", "john@example.com", "pass") x = SimpleLazyObject(lambda: user) pickle.dumps(x) # Try the variant protocol levels. pickle.dumps(x, 0) pickle.dumps(x, 1) pickle.dumps(x, 2)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/__init__.py
tests/utils_tests/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_safestring.py
tests/utils_tests/test_safestring.py
from django.template import Context, Template from django.test import SimpleTestCase from django.utils import html, translation from django.utils.functional import Promise, lazy, lazystr from django.utils.safestring import SafeData, SafeString, mark_safe from django.utils.translation import gettext_lazy class customescape(str): def __html__(self): # Implement specific and wrong escaping in order to be able to detect # when it runs. return self.replace("<", "<<").replace(">", ">>") class SafeStringTest(SimpleTestCase): def assertRenderEqual(self, tpl, expected, **context): context = Context(context) tpl = Template(tpl) self.assertEqual(tpl.render(context), expected) def test_mark_safe(self): s = mark_safe("a&b") self.assertRenderEqual("{{ s }}", "a&b", s=s) self.assertRenderEqual("{{ s|force_escape }}", "a&amp;b", s=s) def test_mark_safe_str(self): """ Calling str() on a SafeString instance doesn't lose the safe status. """ s = mark_safe("a&b") self.assertIsInstance(str(s), type(s)) def test_mark_safe_object_implementing_dunder_html(self): e = customescape("<a&b>") s = mark_safe(e) self.assertIs(s, e) self.assertRenderEqual("{{ s }}", "<<a&b>>", s=s) self.assertRenderEqual("{{ s|force_escape }}", "&lt;a&amp;b&gt;", s=s) def test_mark_safe_lazy(self): safe_s = mark_safe(lazystr("a&b")) self.assertIsInstance(safe_s, Promise) self.assertRenderEqual("{{ s }}", "a&b", s=safe_s) self.assertIsInstance(str(safe_s), SafeData) def test_mark_safe_lazy_i18n(self): s = mark_safe(gettext_lazy("name")) tpl = Template("{{ s }}") with translation.override("fr"): self.assertEqual(tpl.render(Context({"s": s})), "nom") def test_mark_safe_object_implementing_dunder_str(self): class Obj: def __str__(self): return "<obj>" s = mark_safe(Obj()) self.assertRenderEqual("{{ s }}", "<obj>", s=s) def test_mark_safe_result_implements_dunder_html(self): self.assertEqual(mark_safe("a&b").__html__(), "a&b") def test_mark_safe_lazy_result_implements_dunder_html(self): self.assertEqual(mark_safe(lazystr("a&b")).__html__(), "a&b") def test_add_lazy_safe_text_and_safe_text(self): s = html.escape(lazystr("a")) s += mark_safe("&b") self.assertRenderEqual("{{ s }}", "a&b", s=s) s = html.escapejs(lazystr("a")) s += mark_safe("&b") self.assertRenderEqual("{{ s }}", "a&b", s=s) def test_mark_safe_as_decorator(self): """ mark_safe used as a decorator leaves the result of a function unchanged. """ def clean_string_provider(): return "<html><body>dummy</body></html>" self.assertEqual(mark_safe(clean_string_provider)(), clean_string_provider()) def test_mark_safe_decorator_does_not_affect_dunder_html(self): """ mark_safe doesn't affect a callable that has an __html__() method. """ class SafeStringContainer: def __html__(self): return "<html></html>" self.assertIs(mark_safe(SafeStringContainer), SafeStringContainer) def test_mark_safe_decorator_does_not_affect_promises(self): """ mark_safe doesn't affect lazy strings (Promise objects). """ def html_str(): return "<html></html>" lazy_str = lazy(html_str, str)() self.assertEqual(mark_safe(lazy_str), html_str()) def test_default_additional_attrs(self): s = SafeString("a&b") msg = "object has no attribute 'dynamic_attr'" with self.assertRaisesMessage(AttributeError, msg): s.dynamic_attr = True def test_default_safe_data_additional_attrs(self): s = SafeData() msg = "object has no attribute 'dynamic_attr'" with self.assertRaisesMessage(AttributeError, msg): s.dynamic_attr = True def test_add_str(self): s = SafeString("a&b") cases = [ ("test", "a&amp;btest"), ("<p>unsafe</p>", "a&amp;b&lt;p&gt;unsafe&lt;/p&gt;"), (SafeString("<p>safe</p>"), SafeString("a&b<p>safe</p>")), ] for case, expected in cases: with self.subTest(case=case): self.assertRenderEqual("{{ s }}", expected, s=s + case) def test_add_obj(self): base_str = "<strong>strange</strong>" add_str = "hello</br>" class Add: def __add__(self, other): return base_str + other class AddSafe: def __add__(self, other): return mark_safe(base_str) + other class Radd: def __radd__(self, other): return other + base_str class RaddSafe: def __radd__(self, other): return other + mark_safe(base_str) left_add_expected = f"{base_str}{add_str}" right_add_expected = f"{add_str}{base_str}" cases = [ # Left-add test cases. (Add(), add_str, left_add_expected, str), (Add(), mark_safe(add_str), left_add_expected, str), (AddSafe(), add_str, left_add_expected, str), (AddSafe(), mark_safe(add_str), left_add_expected, SafeString), # Right-add test cases. (add_str, Radd(), right_add_expected, str), (mark_safe(add_str), Radd(), right_add_expected, str), (add_str, Radd(), right_add_expected, str), (mark_safe(add_str), RaddSafe(), right_add_expected, SafeString), ] for lhs, rhs, expected, expected_type in cases: with self.subTest(lhs=lhs, rhs=rhs): result = lhs + rhs self.assertEqual(result, expected) self.assertEqual(type(result), expected_type) cases = [ ("hello", Add()), ("hello", AddSafe()), (Radd(), "hello"), (RaddSafe(), "hello"), ] for lhs, rhs in cases: with self.subTest(lhs=lhs, rhs=rhs), self.assertRaises(TypeError): lhs + rhs
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_encoding.py
tests/utils_tests/test_encoding.py
import datetime import inspect import sys import unittest from pathlib import Path from unittest import mock from urllib.parse import quote, quote_plus from django.test import SimpleTestCase from django.utils.encoding import ( DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes, force_str, get_system_encoding, iri_to_uri, repercent_broken_unicode, smart_bytes, smart_str, uri_to_iri, ) from django.utils.functional import SimpleLazyObject from django.utils.translation import gettext_lazy from django.utils.version import PYPY class TestEncodingUtils(SimpleTestCase): def test_force_str_exception(self): """ Broken __str__ actually raises an error. """ class MyString: def __str__(self): return b"\xc3\xb6\xc3\xa4\xc3\xbc" # str(s) raises a TypeError if the result is not a text type. with self.assertRaises(TypeError): force_str(MyString()) def test_force_str_lazy(self): s = SimpleLazyObject(lambda: "x") self.assertIs(type(force_str(s)), str) def test_force_str_DjangoUnicodeDecodeError(self): reason = "unexpected end of data" if PYPY else "invalid start byte" msg = ( f"'utf-8' codec can't decode byte 0xff in position 0: {reason}. " "You passed in b'\\xff' (<class 'bytes'>)" ) with self.assertRaisesMessage(DjangoUnicodeDecodeError, msg): force_str(b"\xff") def test_force_bytes_exception(self): """ force_bytes knows how to convert to bytes an exception containing non-ASCII characters in its args. """ error_msg = "This is an exception, voilà" exc = ValueError(error_msg) self.assertEqual(force_bytes(exc), error_msg.encode()) self.assertEqual( force_bytes(exc, encoding="ascii", errors="ignore"), b"This is an exception, voil", ) def test_force_bytes_strings_only(self): today = datetime.date.today() self.assertEqual(force_bytes(today, strings_only=True), today) def test_force_bytes_encoding(self): error_msg = "This is an exception, voilà".encode() result = force_bytes(error_msg, encoding="ascii", errors="ignore") self.assertEqual(result, b"This is an exception, voil") def test_force_bytes_memory_view(self): data = b"abc" result = force_bytes(memoryview(data)) # Type check is needed because memoryview(bytes) == bytes. self.assertIs(type(result), bytes) self.assertEqual(result, data) def test_smart_bytes(self): class Test: def __str__(self): return "ŠĐĆŽćžšđ" lazy_func = gettext_lazy("x") self.assertIs(smart_bytes(lazy_func), lazy_func) self.assertEqual( smart_bytes(Test()), b"\xc5\xa0\xc4\x90\xc4\x86\xc5\xbd\xc4\x87\xc5\xbe\xc5\xa1\xc4\x91", ) self.assertEqual(smart_bytes(1), b"1") self.assertEqual(smart_bytes("foo"), b"foo") def test_smart_str(self): class Test: def __str__(self): return "ŠĐĆŽćžšđ" lazy_func = gettext_lazy("x") self.assertIs(smart_str(lazy_func), lazy_func) self.assertEqual( smart_str(Test()), "\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ) self.assertEqual(smart_str(1), "1") self.assertEqual(smart_str("foo"), "foo") def test_get_default_encoding(self): with mock.patch("locale.getlocale", side_effect=Exception): self.assertEqual(get_system_encoding(), "ascii") def test_repercent_broken_unicode_recursion_error(self): # Prepare a string long enough to force a recursion error if the tested # function uses recursion. data = b"\xfc" * sys.getrecursionlimit() try: self.assertEqual( repercent_broken_unicode(data), b"%FC" * sys.getrecursionlimit() ) except RecursionError: self.fail("Unexpected RecursionError raised.") def test_repercent_broken_unicode_small_fragments(self): data = b"test\xfctest\xfctest\xfc" decoded_paths = [] def mock_quote(*args, **kwargs): # The second frame is the call to repercent_broken_unicode(). decoded_paths.append(inspect.currentframe().f_back.f_locals["path"]) return quote(*args, **kwargs) with mock.patch("django.utils.encoding.quote", mock_quote): self.assertEqual(repercent_broken_unicode(data), b"test%FCtest%FCtest%FC") # decode() is called on smaller fragment of the path each time. self.assertEqual( decoded_paths, [b"test\xfctest\xfctest\xfc", b"test\xfctest\xfc", b"test\xfc"], ) class TestRFC3987IEncodingUtils(unittest.TestCase): def test_filepath_to_uri(self): self.assertIsNone(filepath_to_uri(None)) self.assertEqual( filepath_to_uri("upload\\чубака.mp4"), "upload/%D1%87%D1%83%D0%B1%D0%B0%D0%BA%D0%B0.mp4", ) self.assertEqual(filepath_to_uri(Path("upload/test.png")), "upload/test.png") self.assertEqual(filepath_to_uri(Path("upload\\test.png")), "upload/test.png") def test_iri_to_uri(self): cases = [ # Valid UTF-8 sequences are encoded. ("red%09rosé#red", "red%09ros%C3%A9#red"), ("/blog/for/Jürgen Münster/", "/blog/for/J%C3%BCrgen%20M%C3%BCnster/"), ( "locations/%s" % quote_plus("Paris & Orléans"), "locations/Paris+%26+Orl%C3%A9ans", ), # Reserved chars remain unescaped. ("%&", "%&"), ("red&♥ros%#red", "red&%E2%99%A5ros%#red"), (gettext_lazy("red&♥ros%#red"), "red&%E2%99%A5ros%#red"), ] for iri, uri in cases: with self.subTest(iri): self.assertEqual(iri_to_uri(iri), uri) # Test idempotency. self.assertEqual(iri_to_uri(iri_to_uri(iri)), uri) def test_uri_to_iri(self): cases = [ (None, None), # Valid UTF-8 sequences are decoded. ("/%e2%89%Ab%E2%99%a5%E2%89%aB/", "/≫♥≫/"), ("/%E2%99%A5%E2%99%A5/?utf8=%E2%9C%93", "/♥♥/?utf8=✓"), ("/%41%5a%6B/", "/AZk/"), # Reserved and non-URL valid ASCII chars are not decoded. ("/%25%20%02%41%7b/", "/%25%20%02A%7b/"), # Broken UTF-8 sequences remain escaped. ("/%AAd%AAj%AAa%AAn%AAg%AAo%AA/", "/%AAd%AAj%AAa%AAn%AAg%AAo%AA/"), ("/%E2%99%A5%E2%E2%99%A5/", "/♥%E2♥/"), ("/%E2%99%A5%E2%99%E2%99%A5/", "/♥%E2%99♥/"), ("/%E2%E2%99%A5%E2%99%A5%99/", "/%E2♥♥%99/"), ( "/%E2%99%A5%E2%99%A5/?utf8=%9C%93%E2%9C%93%9C%93", "/♥♥/?utf8=%9C%93✓%9C%93", ), ] for uri, iri in cases: with self.subTest(uri): self.assertEqual(uri_to_iri(uri), iri) # Test idempotency. self.assertEqual(uri_to_iri(uri_to_iri(uri)), iri) def test_complementarity(self): cases = [ ( "/blog/for/J%C3%BCrgen%20M%C3%BCnster/", "/blog/for/J\xfcrgen%20M\xfcnster/", ), ("%&", "%&"), ("red&%E2%99%A5ros%#red", "red&♥ros%#red"), ("/%E2%99%A5%E2%99%A5/", "/♥♥/"), ("/%E2%99%A5%E2%99%A5/?utf8=%E2%9C%93", "/♥♥/?utf8=✓"), ("/%25%20%02%7b/", "/%25%20%02%7b/"), ("/%AAd%AAj%AAa%AAn%AAg%AAo%AA/", "/%AAd%AAj%AAa%AAn%AAg%AAo%AA/"), ("/%E2%99%A5%E2%E2%99%A5/", "/♥%E2♥/"), ("/%E2%99%A5%E2%99%E2%99%A5/", "/♥%E2%99♥/"), ("/%E2%E2%99%A5%E2%99%A5%99/", "/%E2♥♥%99/"), ( "/%E2%99%A5%E2%99%A5/?utf8=%9C%93%E2%9C%93%9C%93", "/♥♥/?utf8=%9C%93✓%9C%93", ), ] for uri, iri in cases: with self.subTest(uri): self.assertEqual(iri_to_uri(uri_to_iri(uri)), uri) self.assertEqual(uri_to_iri(iri_to_uri(iri)), iri) def test_escape_uri_path(self): cases = [ ( "/;some/=awful/?path/:with/@lots/&of/+awful/chars", "/%3Bsome/%3Dawful/%3Fpath/:with/@lots/&of/+awful/chars", ), ("/foo#bar", "/foo%23bar"), ("/foo?bar", "/foo%3Fbar"), ] for uri, expected in cases: with self.subTest(uri): self.assertEqual(escape_uri_path(uri), expected)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_dateformat.py
tests/utils_tests/test_dateformat.py
from datetime import UTC, date, datetime, time, tzinfo from django.test import SimpleTestCase, override_settings from django.test.utils import TZ_SUPPORT, requires_tz_support from django.utils import dateformat, translation from django.utils.dateformat import format from django.utils.timezone import get_default_timezone, get_fixed_timezone, make_aware @override_settings(TIME_ZONE="Europe/Copenhagen") class DateFormatTests(SimpleTestCase): @classmethod def setUpClass(cls): cls.enterClassContext(translation.override("en-us")) super().setUpClass() def test_date(self): d = date(2009, 5, 16) self.assertEqual(date.fromtimestamp(int(format(d, "U"))), d) def test_naive_datetime(self): dt = datetime(2009, 5, 16, 5, 30, 30) self.assertEqual(datetime.fromtimestamp(int(format(dt, "U"))), dt) def test_naive_ambiguous_datetime(self): # dt is ambiguous in Europe/Copenhagen. dt = datetime(2015, 10, 25, 2, 30, 0) # Try all formatters that involve self.timezone. self.assertEqual(format(dt, "I"), "") self.assertEqual(format(dt, "O"), "") self.assertEqual(format(dt, "T"), "") self.assertEqual(format(dt, "Z"), "") @requires_tz_support def test_datetime_with_local_tzinfo(self): ltz = get_default_timezone() dt = make_aware(datetime(2009, 5, 16, 5, 30, 30), ltz) self.assertEqual(datetime.fromtimestamp(int(format(dt, "U")), ltz), dt) self.assertEqual( datetime.fromtimestamp(int(format(dt, "U"))), dt.replace(tzinfo=None) ) @requires_tz_support def test_datetime_with_tzinfo(self): tz = get_fixed_timezone(-510) ltz = get_default_timezone() dt = make_aware(datetime(2009, 5, 16, 5, 30, 30), ltz) self.assertEqual(datetime.fromtimestamp(int(format(dt, "U")), tz), dt) self.assertEqual(datetime.fromtimestamp(int(format(dt, "U")), ltz), dt) # astimezone() is safe here because the target timezone doesn't have # DST self.assertEqual( datetime.fromtimestamp(int(format(dt, "U"))), dt.astimezone(ltz).replace(tzinfo=None), ) self.assertEqual( datetime.fromtimestamp(int(format(dt, "U")), tz).timetuple(), dt.astimezone(tz).timetuple(), ) self.assertEqual( datetime.fromtimestamp(int(format(dt, "U")), ltz).timetuple(), dt.astimezone(ltz).timetuple(), ) def test_epoch(self): udt = datetime(1970, 1, 1, tzinfo=UTC) self.assertEqual(format(udt, "U"), "0") def test_empty_format(self): my_birthday = datetime(1979, 7, 8, 22, 00) self.assertEqual(dateformat.format(my_birthday, ""), "") def test_am_pm(self): morning = time(7, 00) evening = time(19, 00) self.assertEqual(dateformat.format(morning, "a"), "a.m.") self.assertEqual(dateformat.format(evening, "a"), "p.m.") self.assertEqual(dateformat.format(morning, "A"), "AM") self.assertEqual(dateformat.format(evening, "A"), "PM") def test_microsecond(self): # Regression test for #18951 dt = datetime(2009, 5, 16, microsecond=123) self.assertEqual(dateformat.format(dt, "u"), "000123") def test_date_formats(self): # Specifiers 'I', 'r', and 'U' are covered in test_timezones(). my_birthday = datetime(1979, 7, 8, 22, 00) for specifier, expected in [ ("b", "jul"), ("d", "08"), ("D", "Sun"), ("E", "July"), ("F", "July"), ("j", "8"), ("l", "Sunday"), ("L", "False"), ("m", "07"), ("M", "Jul"), ("n", "7"), ("N", "July"), ("o", "1979"), ("S", "th"), ("t", "31"), ("w", "0"), ("W", "27"), ("y", "79"), ("Y", "1979"), ("z", "189"), ]: with self.subTest(specifier=specifier): self.assertEqual(dateformat.format(my_birthday, specifier), expected) def test_date_formats_c_format(self): timestamp = datetime(2008, 5, 19, 11, 45, 23, 123456) self.assertEqual( dateformat.format(timestamp, "c"), "2008-05-19T11:45:23.123456" ) def test_time_formats(self): # Specifiers 'I', 'r', and 'U' are covered in test_timezones(). my_birthday = datetime(1979, 7, 8, 22, 00) for specifier, expected in [ ("a", "p.m."), ("A", "PM"), ("f", "10"), ("g", "10"), ("G", "22"), ("h", "10"), ("H", "22"), ("i", "00"), ("P", "10 p.m."), ("s", "00"), ("u", "000000"), ]: with self.subTest(specifier=specifier): self.assertEqual(dateformat.format(my_birthday, specifier), expected) def test_dateformat(self): my_birthday = datetime(1979, 7, 8, 22, 00) self.assertEqual(dateformat.format(my_birthday, r"Y z \C\E\T"), "1979 189 CET") self.assertEqual(dateformat.format(my_birthday, r"jS \o\f F"), "8th of July") def test_futuredates(self): the_future = datetime(2100, 10, 25, 0, 00) self.assertEqual(dateformat.format(the_future, r"Y"), "2100") def test_day_of_year_leap(self): self.assertEqual(dateformat.format(datetime(2000, 12, 31), "z"), "366") def test_timezones(self): my_birthday = datetime(1979, 7, 8, 22, 00) summertime = datetime(2005, 10, 30, 1, 00) wintertime = datetime(2005, 10, 30, 4, 00) noon = time(12, 0, 0) # 3h30m to the west of UTC tz = get_fixed_timezone(-210) aware_dt = datetime(2009, 5, 16, 5, 30, 30, tzinfo=tz) if TZ_SUPPORT: for specifier, expected in [ ("e", ""), ("O", "+0100"), ("r", "Sun, 08 Jul 1979 22:00:00 +0100"), ("T", "CET"), ("U", "300315600"), ("Z", "3600"), ]: with self.subTest(specifier=specifier): self.assertEqual( dateformat.format(my_birthday, specifier), expected ) self.assertEqual(dateformat.format(aware_dt, "e"), "-0330") self.assertEqual( dateformat.format(aware_dt, "r"), "Sat, 16 May 2009 05:30:30 -0330", ) self.assertEqual(dateformat.format(summertime, "I"), "1") self.assertEqual(dateformat.format(summertime, "O"), "+0200") self.assertEqual(dateformat.format(wintertime, "I"), "0") self.assertEqual(dateformat.format(wintertime, "O"), "+0100") for specifier in ["e", "O", "T", "Z"]: with self.subTest(specifier=specifier): self.assertEqual(dateformat.time_format(noon, specifier), "") # Ticket #16924 -- We don't need timezone support to test this self.assertEqual(dateformat.format(aware_dt, "O"), "-0330") def test_invalid_time_format_specifiers(self): my_birthday = date(1984, 8, 7) for specifier in ["a", "A", "f", "g", "G", "h", "H", "i", "P", "s", "u"]: with self.subTest(specifier=specifier): msg = ( "The format for date objects may not contain time-related " f"format specifiers (found {specifier!r})." ) with self.assertRaisesMessage(TypeError, msg): dateformat.format(my_birthday, specifier) @requires_tz_support def test_e_format_with_named_time_zone(self): dt = datetime(1970, 1, 1, tzinfo=UTC) self.assertEqual(dateformat.format(dt, "e"), "UTC") @requires_tz_support def test_e_format_with_time_zone_with_unimplemented_tzname(self): class NoNameTZ(tzinfo): """Time zone without .tzname() defined.""" def utcoffset(self, dt): return None dt = datetime(1970, 1, 1, tzinfo=NoNameTZ()) self.assertEqual(dateformat.format(dt, "e"), "") def test_P_format(self): for expected, t in [ ("midnight", time(0)), ("noon", time(12)), ("4 a.m.", time(4)), ("8:30 a.m.", time(8, 30)), ("4 p.m.", time(16)), ("8:30 p.m.", time(20, 30)), ]: with self.subTest(time=t): self.assertEqual(dateformat.time_format(t, "P"), expected) def test_r_format_with_date(self): # Assume midnight in default timezone if datetime.date provided. dt = date(2022, 7, 1) self.assertEqual( dateformat.format(dt, "r"), "Fri, 01 Jul 2022 00:00:00 +0200", ) def test_r_format_with_non_en_locale(self): # Changing the locale doesn't change the "r" format. dt = datetime(1979, 7, 8, 22, 00) with translation.override("fr"): self.assertEqual( dateformat.format(dt, "r"), "Sun, 08 Jul 1979 22:00:00 +0100", ) def test_S_format(self): for expected, days in [ ("st", [1, 21, 31]), ("nd", [2, 22]), ("rd", [3, 23]), ("th", (n for n in range(4, 31) if n not in [21, 22, 23])), ]: for day in days: dt = date(1970, 1, day) with self.subTest(day=day): self.assertEqual(dateformat.format(dt, "S"), expected) def test_y_format_year_before_1000(self): tests = [ (476, "76"), (42, "42"), (4, "04"), ] for year, expected_date in tests: with self.subTest(year=year): self.assertEqual( dateformat.format(datetime(year, 9, 8, 5, 0), "y"), expected_date, ) def test_Y_format_year_before_1000(self): self.assertEqual(dateformat.format(datetime(1, 1, 1), "Y"), "0001") self.assertEqual(dateformat.format(datetime(999, 1, 1), "Y"), "0999") def test_twelve_hour_format(self): tests = [ (0, "12", "12"), (1, "1", "01"), (11, "11", "11"), (12, "12", "12"), (13, "1", "01"), (23, "11", "11"), ] for hour, g_expected, h_expected in tests: dt = datetime(2000, 1, 1, hour) with self.subTest(hour=hour): self.assertEqual(dateformat.format(dt, "g"), g_expected) self.assertEqual(dateformat.format(dt, "h"), h_expected)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_crypto.py
tests/utils_tests/test_crypto.py
import hashlib import unittest from django.test import SimpleTestCase from django.utils.crypto import ( InvalidAlgorithm, constant_time_compare, pbkdf2, salted_hmac, ) class TestUtilsCryptoMisc(SimpleTestCase): def test_constant_time_compare(self): # It's hard to test for constant time, just test the result. self.assertTrue(constant_time_compare(b"spam", b"spam")) self.assertFalse(constant_time_compare(b"spam", b"eggs")) self.assertTrue(constant_time_compare("spam", "spam")) self.assertFalse(constant_time_compare("spam", "eggs")) self.assertTrue(constant_time_compare(b"spam", "spam")) self.assertFalse(constant_time_compare("spam", b"eggs")) self.assertTrue(constant_time_compare("ありがとう", "ありがとう")) self.assertFalse(constant_time_compare("ありがとう", "おはよう")) def test_salted_hmac(self): tests = [ ((b"salt", b"value"), {}, "b51a2e619c43b1ca4f91d15c57455521d71d61eb"), (("salt", "value"), {}, "b51a2e619c43b1ca4f91d15c57455521d71d61eb"), ( ("salt", "value"), {"secret": "abcdefg"}, "8bbee04ccddfa24772d1423a0ba43bd0c0e24b76", ), ( ("salt", "value"), {"secret": "x" * hashlib.sha1().block_size}, "bd3749347b412b1b0a9ea65220e55767ac8e96b0", ), ( ("salt", "value"), {"algorithm": "sha256"}, "ee0bf789e4e009371a5372c90f73fcf17695a8439c9108b0480f14e347b3f9ec", ), ( ("salt", "value"), { "algorithm": "blake2b", "secret": "x" * hashlib.blake2b().block_size, }, "fc6b9800a584d40732a07fa33fb69c35211269441823bca431a143853c32f" "e836cf19ab881689528ede647dac412170cd5d3407b44c6d0f44630690c54" "ad3d58", ), ] for args, kwargs, digest in tests: with self.subTest(args=args, kwargs=kwargs): self.assertEqual(salted_hmac(*args, **kwargs).hexdigest(), digest) def test_invalid_algorithm(self): msg = "'whatever' is not an algorithm accepted by the hashlib module." with self.assertRaisesMessage(InvalidAlgorithm, msg): salted_hmac("salt", "value", algorithm="whatever") class TestUtilsCryptoPBKDF2(unittest.TestCase): # https://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-06 rfc_vectors = [ { "args": { "password": "password", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashlib.sha1, }, "result": "0c60c80f961f0e71f3a9b524af6012062fe037a6", }, { "args": { "password": "password", "salt": "salt", "iterations": 2, "dklen": 20, "digest": hashlib.sha1, }, "result": "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957", }, { "args": { "password": "password", "salt": "salt", "iterations": 4096, "dklen": 20, "digest": hashlib.sha1, }, "result": "4b007901b765489abead49d926f721d065a429c1", }, # # this takes way too long :( # { # "args": { # "password": "password", # "salt": "salt", # "iterations": 16777216, # "dklen": 20, # "digest": hashlib.sha1, # }, # "result": "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984", # }, { "args": { "password": "passwordPASSWORDpassword", "salt": "saltSALTsaltSALTsaltSALTsaltSALTsalt", "iterations": 4096, "dklen": 25, "digest": hashlib.sha1, }, "result": "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038", }, { "args": { "password": "pass\0word", "salt": "sa\0lt", "iterations": 4096, "dklen": 16, "digest": hashlib.sha1, }, "result": "56fa6aa75548099dcc37d7f03425e0c3", }, ] regression_vectors = [ { "args": { "password": "password", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashlib.sha256, }, "result": "120fb6cffcf8b32c43e7225256c4f837a86548c9", }, { "args": { "password": "password", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashlib.sha512, }, "result": "867f70cf1ade02cff3752599a3a53dc4af34c7a6", }, { "args": { "password": "password", "salt": "salt", "iterations": 1000, "dklen": 0, "digest": hashlib.sha512, }, "result": ( "afe6c5530785b6cc6b1c6453384731bd5ee432ee" "549fd42fb6695779ad8a1c5bf59de69c48f774ef" "c4007d5298f9033c0241d5ab69305e7b64eceeb8d" "834cfec" ), }, # Check leading zeros are not stripped (#17481) { "args": { "password": b"\xba", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashlib.sha1, }, "result": "0053d3b91a7f1e54effebd6d68771e8a6e0b2c5b", }, ] def test_public_vectors(self): for vector in self.rfc_vectors: result = pbkdf2(**vector["args"]) self.assertEqual(result.hex(), vector["result"]) def test_regression_vectors(self): for vector in self.regression_vectors: result = pbkdf2(**vector["args"]) self.assertEqual(result.hex(), vector["result"]) def test_default_hmac_alg(self): kwargs = { "password": b"password", "salt": b"salt", "iterations": 1, "dklen": 20, } self.assertEqual( pbkdf2(**kwargs), hashlib.pbkdf2_hmac(hash_name=hashlib.sha256().name, **kwargs), )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_os_utils.py
tests/utils_tests/test_os_utils.py
import os import unittest from pathlib import Path from django.core.exceptions import SuspiciousFileOperation from django.utils._os import safe_join, to_path class SafeJoinTests(unittest.TestCase): def test_base_path_ends_with_sep(self): drive, path = os.path.splitdrive(safe_join("/abc/", "abc")) self.assertEqual(path, "{0}abc{0}abc".format(os.path.sep)) def test_root_path(self): drive, path = os.path.splitdrive(safe_join("/", "path")) self.assertEqual( path, "{}path".format(os.path.sep), ) drive, path = os.path.splitdrive(safe_join("/", "")) self.assertEqual( path, os.path.sep, ) def test_parent_path(self): with self.assertRaises(SuspiciousFileOperation): safe_join("/abc/", "../def") class ToPathTests(unittest.TestCase): def test_to_path(self): for path in ("/tmp/some_file.txt", Path("/tmp/some_file.txt")): with self.subTest(path): self.assertEqual(to_path(path), Path("/tmp/some_file.txt")) def test_to_path_invalid_value(self): with self.assertRaises(TypeError): to_path(42)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/deconstructible_classes.py
tests/utils_tests/deconstructible_classes.py
from .test_deconstruct import DeconstructibleWithPathClass # NOQA
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_module/another_bad_module.py
tests/utils_tests/test_module/another_bad_module.py
from . import site content = "Another Bad Module" site._registry.update( { "foo": "bar", } ) raise Exception("Some random exception.")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_module/bad_module.py
tests/utils_tests/test_module/bad_module.py
import a_package_name_that_does_not_exist # NOQA content = "Bad Module"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_module/another_good_module.py
tests/utils_tests/test_module/another_good_module.py
from . import site content = "Another Good Module" site._registry.update( { "lorem": "ipsum", } )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_module/__main__.py
tests/utils_tests/test_module/__main__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_module/main_module.py
tests/utils_tests/test_module/main_module.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_module/__init__.py
tests/utils_tests/test_module/__init__.py
class SiteMock: _registry = {} site = SiteMock()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_module/good_module.py
tests/utils_tests/test_module/good_module.py
content = "Good Module"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_module/child_module/grandchild_module.py
tests/utils_tests/test_module/child_module/grandchild_module.py
content = "Grandchild Module"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/utils_tests/test_module/child_module/__init__.py
tests/utils_tests/test_module/child_module/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/select_related/models.py
tests/select_related/models.py
""" Tests for select_related() ``select_related()`` follows all relationships and pre-caches any foreign key values so that complex trees can be fetched in a single query. However, this isn't always a good idea, so the ``depth`` argument control how many "levels" the select-related behavior will traverse. """ from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models # Who remembers high school biology? class Domain(models.Model): name = models.CharField(max_length=50) class Kingdom(models.Model): name = models.CharField(max_length=50) domain = models.ForeignKey(Domain, models.CASCADE) class Phylum(models.Model): name = models.CharField(max_length=50) kingdom = models.ForeignKey(Kingdom, models.CASCADE) class Klass(models.Model): name = models.CharField(max_length=50) phylum = models.ForeignKey(Phylum, models.CASCADE) class Order(models.Model): name = models.CharField(max_length=50) klass = models.ForeignKey(Klass, models.CASCADE) class Family(models.Model): name = models.CharField(max_length=50) order = models.ForeignKey(Order, models.CASCADE) class Genus(models.Model): name = models.CharField(max_length=50) family = models.ForeignKey(Family, models.CASCADE) class Species(models.Model): name = models.CharField(max_length=50) genus = models.ForeignKey(Genus, models.CASCADE) # and we'll invent a new thing so we have a model with two foreign keys class HybridSpecies(models.Model): name = models.CharField(max_length=50) parent_1 = models.ForeignKey(Species, models.CASCADE, related_name="child_1") parent_2 = models.ForeignKey(Species, models.CASCADE, related_name="child_2") class Topping(models.Model): name = models.CharField(max_length=30) class Pizza(models.Model): name = models.CharField(max_length=100) toppings = models.ManyToManyField(Topping) class TaggedItem(models.Model): tag = models.CharField(max_length=30) content_type = models.ForeignKey( ContentType, models.CASCADE, related_name="select_related_tagged_items" ) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") class Bookmark(models.Model): url = models.URLField() tags = GenericRelation(TaggedItem)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/select_related/__init__.py
tests/select_related/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/select_related/tests.py
tests/select_related/tests.py
import gc from django.core.exceptions import FieldError from django.db.models import FETCH_PEERS from django.test import SimpleTestCase, TestCase from django.test.utils import garbage_collect from .models import ( Bookmark, Domain, Family, Genus, HybridSpecies, Kingdom, Klass, Order, Phylum, Pizza, Species, TaggedItem, ) class SelectRelatedTests(TestCase): @classmethod def create_tree(cls, stringtree): """ Helper to create a complete tree. """ names = stringtree.split() models = [Domain, Kingdom, Phylum, Klass, Order, Family, Genus, Species] assert len(names) == len(models), (names, models) parent = None for name, model in zip(names, models): try: obj = model.objects.get(name=name) except model.DoesNotExist: obj = model(name=name) if parent: setattr(obj, parent.__class__.__name__.lower(), parent) obj.save() parent = obj @classmethod def setUpTestData(cls): cls.create_tree( "Eukaryota Animalia Anthropoda Insecta Diptera Drosophilidae Drosophila " "melanogaster" ) cls.create_tree( "Eukaryota Animalia Chordata Mammalia Primates Hominidae Homo sapiens" ) cls.create_tree( "Eukaryota Plantae Magnoliophyta Magnoliopsida Fabales Fabaceae Pisum " "sativum" ) cls.create_tree( "Eukaryota Fungi Basidiomycota Homobasidiomycatae Agaricales Amanitacae " "Amanita muscaria" ) def setup_gc_debug(self): self.addCleanup(gc.set_debug, 0) self.addCleanup(gc.enable) gc.disable() garbage_collect() gc.set_debug(gc.DEBUG_SAVEALL) def assert_no_memory_leaks(self): garbage_collect() self.assertEqual(gc.garbage, []) def test_access_fks_without_select_related(self): """ Normally, accessing FKs doesn't fill in related objects """ with self.assertNumQueries(8): fly = Species.objects.get(name="melanogaster") domain = fly.genus.family.order.klass.phylum.kingdom.domain self.assertEqual(domain.name, "Eukaryota") def test_access_fks_with_select_related(self): """ A select_related() call will fill in those related objects without any extra queries """ with self.assertNumQueries(1): person = Species.objects.select_related( "genus__family__order__klass__phylum__kingdom__domain" ).get(name="sapiens") domain = person.genus.family.order.klass.phylum.kingdom.domain self.assertEqual(domain.name, "Eukaryota") def test_list_without_select_related(self): with self.assertNumQueries(9): world = Species.objects.all() families = [o.genus.family.name for o in world] self.assertEqual( sorted(families), [ "Amanitacae", "Drosophilidae", "Fabaceae", "Hominidae", ], ) def test_list_with_select_related(self): """select_related() applies to entire lists, not just items.""" with self.assertNumQueries(1): world = Species.objects.select_related() families = [o.genus.family.name for o in world] self.assertEqual( sorted(families), [ "Amanitacae", "Drosophilidae", "Fabaceae", "Hominidae", ], ) def test_list_with_depth(self): """ Passing a relationship field lookup specifier to select_related() will stop the descent at a particular level. This can be used on lists as well. """ with self.assertNumQueries(5): world = Species.objects.select_related("genus__family") orders = [o.genus.family.order.name for o in world] self.assertEqual( sorted(orders), ["Agaricales", "Diptera", "Fabales", "Primates"] ) def test_select_related_with_extra(self): s = ( Species.objects.all() .select_related() .extra(select={"a": "select_related_species.id + 10"})[0] ) self.assertEqual(s.id + 10, s.a) def test_select_related_memory_leak(self): self.setup_gc_debug() list(Species.objects.select_related("genus")) self.assert_no_memory_leaks() def test_certain_fields(self): """ The optional fields passed to select_related() control which related models we pull in. This allows for smaller queries. In this case, we explicitly say to select the 'genus' and 'genus.family' models, leading to the same number of queries as before. """ with self.assertNumQueries(1): world = Species.objects.select_related("genus__family") families = [o.genus.family.name for o in world] self.assertEqual( sorted(families), ["Amanitacae", "Drosophilidae", "Fabaceae", "Hominidae"], ) def test_more_certain_fields(self): """ In this case, we explicitly say to select the 'genus' and 'genus.family' models, leading to the same number of queries as before. """ with self.assertNumQueries(2): world = Species.objects.filter(genus__name="Amanita").select_related( "genus__family" ) orders = [o.genus.family.order.name for o in world] self.assertEqual(orders, ["Agaricales"]) def test_field_traversal(self): with self.assertNumQueries(1): s = ( Species.objects.all() .select_related("genus__family__order") .order_by("id")[0:1] .get() .genus.family.order.name ) self.assertEqual(s, "Diptera") def test_none_clears_list(self): queryset = Species.objects.select_related("genus").select_related(None) self.assertIs(queryset.query.select_related, False) def test_chaining(self): parent_1, parent_2 = Species.objects.all()[:2] HybridSpecies.objects.create( name="hybrid", parent_1=parent_1, parent_2=parent_2 ) queryset = HybridSpecies.objects.select_related("parent_1").select_related( "parent_2" ) with self.assertNumQueries(1): obj = queryset[0] self.assertEqual(obj.parent_1, parent_1) self.assertEqual(obj.parent_2, parent_2) def test_reverse_relation_caching(self): species = ( Species.objects.select_related("genus").filter(name="melanogaster").first() ) with self.assertNumQueries(0): self.assertEqual(species.genus.name, "Drosophila") # The species_set reverse relation isn't cached. self.assertEqual(species.genus._state.fields_cache, {}) with self.assertNumQueries(1): self.assertEqual(species.genus.species_set.first().name, "melanogaster") def test_select_related_after_values(self): """ Running select_related() after calling values() raises a TypeError """ message = "Cannot call select_related() after .values() or .values_list()" with self.assertRaisesMessage(TypeError, message): list(Species.objects.values("name").select_related("genus")) def test_select_related_after_values_list(self): """ Running select_related() after calling values_list() raises a TypeError """ message = "Cannot call select_related() after .values() or .values_list()" with self.assertRaisesMessage(TypeError, message): list(Species.objects.values_list("name").select_related("genus")) def test_fetch_mode_copied_fetching_one(self): fly = ( Species.objects.fetch_mode(FETCH_PEERS) .select_related("genus__family") .get(name="melanogaster") ) self.assertEqual(fly._state.fetch_mode, FETCH_PEERS) self.assertEqual( fly.genus._state.fetch_mode, FETCH_PEERS, ) self.assertEqual( fly.genus.family._state.fetch_mode, FETCH_PEERS, ) def test_fetch_mode_copied_fetching_many(self): specieses = list( Species.objects.fetch_mode(FETCH_PEERS).select_related("genus__family") ) species = specieses[0] self.assertEqual(species._state.fetch_mode, FETCH_PEERS) self.assertEqual( species.genus._state.fetch_mode, FETCH_PEERS, ) self.assertEqual( species.genus.family._state.fetch_mode, FETCH_PEERS, ) class SelectRelatedValidationTests(SimpleTestCase): """ select_related() should thrown an error on fields that do not exist and non-relational fields. """ non_relational_error = ( "Non-relational field given in select_related: '%s'. Choices are: %s" ) invalid_error = ( "Invalid field name(s) given in select_related: '%s'. Choices are: %s" ) def test_non_relational_field(self): with self.assertRaisesMessage( FieldError, self.non_relational_error % ("name", "genus") ): list(Species.objects.select_related("name__some_field")) with self.assertRaisesMessage( FieldError, self.non_relational_error % ("name", "genus") ): list(Species.objects.select_related("name")) with self.assertRaisesMessage( FieldError, self.non_relational_error % ("name", "(none)") ): list(Domain.objects.select_related("name")) def test_non_relational_field_nested(self): with self.assertRaisesMessage( FieldError, self.non_relational_error % ("name", "family") ): list(Species.objects.select_related("genus__name")) def test_many_to_many_field(self): with self.assertRaisesMessage( FieldError, self.invalid_error % ("toppings", "(none)") ): list(Pizza.objects.select_related("toppings")) def test_reverse_relational_field(self): with self.assertRaisesMessage( FieldError, self.invalid_error % ("child_1", "genus") ): list(Species.objects.select_related("child_1")) def test_invalid_field(self): with self.assertRaisesMessage( FieldError, self.invalid_error % ("invalid_field", "genus") ): list(Species.objects.select_related("invalid_field")) with self.assertRaisesMessage( FieldError, self.invalid_error % ("related_invalid_field", "family") ): list(Species.objects.select_related("genus__related_invalid_field")) with self.assertRaisesMessage( FieldError, self.invalid_error % ("invalid_field", "(none)") ): list(Domain.objects.select_related("invalid_field")) def test_generic_relations(self): with self.assertRaisesMessage(FieldError, self.invalid_error % ("tags", "")): list(Bookmark.objects.select_related("tags")) with self.assertRaisesMessage( FieldError, self.invalid_error % ("content_object", "content_type") ): list(TaggedItem.objects.select_related("content_object"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/middleware_exceptions/views.py
tests/middleware_exceptions/views.py
from django.core.exceptions import PermissionDenied from django.http import HttpResponse from django.template import engines from django.template.response import TemplateResponse def normal_view(request): return HttpResponse("OK") def template_response(request): template = engines["django"].from_string( "template_response OK{% for m in mw %}\n{{ m }}{% endfor %}" ) return TemplateResponse(request, template, context={"mw": []}) def server_error(request): raise Exception("Error in view") def permission_denied(request): raise PermissionDenied() def exception_in_render(request): class CustomHttpResponse(HttpResponse): def render(self): raise Exception("Exception in HttpResponse.render()") return CustomHttpResponse("Error") async def async_exception_in_render(request): class CustomHttpResponse(HttpResponse): async def render(self): raise Exception("Exception in HttpResponse.render()") return CustomHttpResponse("Error")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/middleware_exceptions/middleware.py
tests/middleware_exceptions/middleware.py
from asgiref.sync import iscoroutinefunction, markcoroutinefunction from django.http import Http404, HttpResponse from django.template import engines from django.template.response import TemplateResponse from django.utils.decorators import ( async_only_middleware, sync_and_async_middleware, sync_only_middleware, ) log = [] class BaseMiddleware: def __init__(self, get_response): self.get_response = get_response if iscoroutinefunction(self.get_response): markcoroutinefunction(self) def __call__(self, request): return self.get_response(request) class ProcessExceptionMiddleware(BaseMiddleware): def process_exception(self, request, exception): return HttpResponse("Exception caught") @async_only_middleware class AsyncProcessExceptionMiddleware(BaseMiddleware): async def process_exception(self, request, exception): return HttpResponse("Exception caught") class ProcessExceptionLogMiddleware(BaseMiddleware): def process_exception(self, request, exception): log.append("process-exception") class ProcessExceptionExcMiddleware(BaseMiddleware): def process_exception(self, request, exception): raise Exception("from process-exception") class ProcessViewMiddleware(BaseMiddleware): def process_view(self, request, view_func, view_args, view_kwargs): return HttpResponse("Processed view %s" % view_func.__name__) @async_only_middleware class AsyncProcessViewMiddleware(BaseMiddleware): async def process_view(self, request, view_func, view_args, view_kwargs): return HttpResponse("Processed view %s" % view_func.__name__) class ProcessViewNoneMiddleware(BaseMiddleware): def process_view(self, request, view_func, view_args, view_kwargs): log.append("processed view %s" % view_func.__name__) return None class ProcessViewTemplateResponseMiddleware(BaseMiddleware): def process_view(self, request, view_func, view_args, view_kwargs): template = engines["django"].from_string( "Processed view {{ view }}{% for m in mw %}\n{{ m }}{% endfor %}" ) return TemplateResponse( request, template, {"mw": [self.__class__.__name__], "view": view_func.__name__}, ) class TemplateResponseMiddleware(BaseMiddleware): def process_template_response(self, request, response): response.context_data["mw"].append(self.__class__.__name__) return response @async_only_middleware class AsyncTemplateResponseMiddleware(BaseMiddleware): async def process_template_response(self, request, response): response.context_data["mw"].append(self.__class__.__name__) return response class LogMiddleware(BaseMiddleware): def __call__(self, request): response = self.get_response(request) log.append((response.status_code, response.content)) return response class NoTemplateResponseMiddleware(BaseMiddleware): def process_template_response(self, request, response): return None @async_only_middleware class AsyncNoTemplateResponseMiddleware(BaseMiddleware): async def process_template_response(self, request, response): return None class NotFoundMiddleware(BaseMiddleware): def __call__(self, request): raise Http404("not found") class PaymentMiddleware(BaseMiddleware): def __call__(self, request): response = self.get_response(request) response.status_code = 402 return response @async_only_middleware def async_payment_middleware(get_response): async def middleware(request): response = await get_response(request) response.status_code = 402 return response return middleware @sync_and_async_middleware class SyncAndAsyncMiddleware(BaseMiddleware): pass @sync_only_middleware class DecoratedPaymentMiddleware(PaymentMiddleware): pass class NotSyncOrAsyncMiddleware(BaseMiddleware): """Middleware that is deliberately neither sync or async.""" sync_capable = False async_capable = False def __call__(self, request): return self.get_response(request)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/middleware_exceptions/__init__.py
tests/middleware_exceptions/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/middleware_exceptions/tests.py
tests/middleware_exceptions/tests.py
from django.conf import settings from django.core.exceptions import MiddlewareNotUsed from django.http import HttpResponse from django.test import RequestFactory, SimpleTestCase, override_settings from . import middleware as mw @override_settings(ROOT_URLCONF="middleware_exceptions.urls") class MiddlewareTests(SimpleTestCase): def tearDown(self): mw.log = [] @override_settings( MIDDLEWARE=["middleware_exceptions.middleware.ProcessViewNoneMiddleware"] ) def test_process_view_return_none(self): response = self.client.get("/middleware_exceptions/view/") self.assertEqual(mw.log, ["processed view normal_view"]) self.assertEqual(response.content, b"OK") @override_settings( MIDDLEWARE=["middleware_exceptions.middleware.ProcessViewMiddleware"] ) def test_process_view_return_response(self): response = self.client.get("/middleware_exceptions/view/") self.assertEqual(response.content, b"Processed view normal_view") @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.ProcessViewTemplateResponseMiddleware", "middleware_exceptions.middleware.LogMiddleware", ] ) def test_templateresponse_from_process_view_rendered(self): """ TemplateResponses returned from process_view() must be rendered before being passed to any middleware that tries to access response.content, such as middleware_exceptions.middleware.LogMiddleware. """ response = self.client.get("/middleware_exceptions/view/") self.assertEqual( response.content, b"Processed view normal_view\nProcessViewTemplateResponseMiddleware", ) @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.ProcessViewTemplateResponseMiddleware", "middleware_exceptions.middleware.TemplateResponseMiddleware", ] ) def test_templateresponse_from_process_view_passed_to_process_template_response( self, ): """ TemplateResponses returned from process_view() should be passed to any template response middleware. """ response = self.client.get("/middleware_exceptions/view/") expected_lines = [ b"Processed view normal_view", b"ProcessViewTemplateResponseMiddleware", b"TemplateResponseMiddleware", ] self.assertEqual(response.content, b"\n".join(expected_lines)) @override_settings( MIDDLEWARE=["middleware_exceptions.middleware.TemplateResponseMiddleware"] ) def test_process_template_response(self): response = self.client.get("/middleware_exceptions/template_response/") self.assertEqual( response.content, b"template_response OK\nTemplateResponseMiddleware" ) @override_settings( MIDDLEWARE=["middleware_exceptions.middleware.NoTemplateResponseMiddleware"] ) def test_process_template_response_returns_none(self): msg = ( "NoTemplateResponseMiddleware.process_template_response didn't " "return an HttpResponse object. It returned None instead." ) with self.assertRaisesMessage(ValueError, msg): self.client.get("/middleware_exceptions/template_response/") @override_settings(MIDDLEWARE=["middleware_exceptions.middleware.LogMiddleware"]) def test_view_exception_converted_before_middleware(self): response = self.client.get("/middleware_exceptions/permission_denied/") self.assertEqual(mw.log, [(response.status_code, response.content)]) self.assertEqual(response.status_code, 403) @override_settings( MIDDLEWARE=["middleware_exceptions.middleware.ProcessExceptionMiddleware"] ) def test_view_exception_handled_by_process_exception(self): response = self.client.get("/middleware_exceptions/error/") self.assertEqual(response.content, b"Exception caught") @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.ProcessExceptionLogMiddleware", "middleware_exceptions.middleware.ProcessExceptionMiddleware", ] ) def test_response_from_process_exception_short_circuits_remainder(self): response = self.client.get("/middleware_exceptions/error/") self.assertEqual(mw.log, []) self.assertEqual(response.content, b"Exception caught") @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.ProcessExceptionMiddleware", "middleware_exceptions.middleware.ProcessExceptionLogMiddleware", ] ) def test_response_from_process_exception_when_return_response(self): response = self.client.get("/middleware_exceptions/error/") self.assertEqual(mw.log, ["process-exception"]) self.assertEqual(response.content, b"Exception caught") @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.LogMiddleware", "middleware_exceptions.middleware.NotFoundMiddleware", ] ) def test_exception_in_middleware_converted_before_prior_middleware(self): response = self.client.get("/middleware_exceptions/view/") self.assertEqual(mw.log, [(404, response.content)]) self.assertEqual(response.status_code, 404) @override_settings( MIDDLEWARE=["middleware_exceptions.middleware.ProcessExceptionMiddleware"] ) def test_exception_in_render_passed_to_process_exception(self): response = self.client.get("/middleware_exceptions/exception_in_render/") self.assertEqual(response.content, b"Exception caught") @override_settings(ROOT_URLCONF="middleware_exceptions.urls") class RootUrlconfTests(SimpleTestCase): @override_settings(ROOT_URLCONF=None) def test_missing_root_urlconf(self): # Removing ROOT_URLCONF is safe, as override_settings will restore # the previously defined settings. del settings.ROOT_URLCONF with self.assertRaises(AttributeError): self.client.get("/middleware_exceptions/view/") class MyMiddleware: def __init__(self, get_response): raise MiddlewareNotUsed def process_request(self, request): pass class MyMiddlewareWithExceptionMessage: def __init__(self, get_response): raise MiddlewareNotUsed("spam eggs") def process_request(self, request): pass @override_settings( DEBUG=True, ROOT_URLCONF="middleware_exceptions.urls", MIDDLEWARE=["django.middleware.common.CommonMiddleware"], ) class MiddlewareNotUsedTests(SimpleTestCase): rf = RequestFactory() def test_raise_exception(self): request = self.rf.get("middleware_exceptions/view/") with self.assertRaises(MiddlewareNotUsed): MyMiddleware(lambda req: HttpResponse()).process_request(request) @override_settings(MIDDLEWARE=["middleware_exceptions.tests.MyMiddleware"]) def test_log(self): with self.assertLogs("django.request", "DEBUG") as cm: self.client.get("/middleware_exceptions/view/") self.assertEqual( cm.records[0].getMessage(), "MiddlewareNotUsed: 'middleware_exceptions.tests.MyMiddleware'", ) @override_settings( MIDDLEWARE=["middleware_exceptions.tests.MyMiddlewareWithExceptionMessage"] ) def test_log_custom_message(self): with self.assertLogs("django.request", "DEBUG") as cm: self.client.get("/middleware_exceptions/view/") self.assertEqual( cm.records[0].getMessage(), "MiddlewareNotUsed('middleware_exceptions.tests." "MyMiddlewareWithExceptionMessage'): spam eggs", ) @override_settings( DEBUG=False, MIDDLEWARE=["middleware_exceptions.tests.MyMiddleware"], ) def test_do_not_log_when_debug_is_false(self): with self.assertNoLogs("django.request", "DEBUG"): self.client.get("/middleware_exceptions/view/") @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.SyncAndAsyncMiddleware", "middleware_exceptions.tests.MyMiddleware", ] ) async def test_async_and_sync_middleware_chain_async_call(self): with self.assertLogs("django.request", "DEBUG") as cm: response = await self.async_client.get("/middleware_exceptions/view/") self.assertEqual(response.content, b"OK") self.assertEqual(response.status_code, 200) self.assertEqual( cm.records[0].getMessage(), "Asynchronous handler adapted for middleware " "middleware_exceptions.tests.MyMiddleware.", ) self.assertEqual( cm.records[1].getMessage(), "MiddlewareNotUsed: 'middleware_exceptions.tests.MyMiddleware'", ) @override_settings( DEBUG=True, ROOT_URLCONF="middleware_exceptions.urls", ) class MiddlewareSyncAsyncTests(SimpleTestCase): @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.PaymentMiddleware", ] ) def test_sync_middleware(self): response = self.client.get("/middleware_exceptions/view/") self.assertEqual(response.status_code, 402) @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.DecoratedPaymentMiddleware", ] ) def test_sync_decorated_middleware(self): response = self.client.get("/middleware_exceptions/view/") self.assertEqual(response.status_code, 402) @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.async_payment_middleware", ] ) def test_async_middleware(self): with self.assertLogs("django.request", "DEBUG") as cm: response = self.client.get("/middleware_exceptions/view/") self.assertEqual(response.status_code, 402) self.assertEqual( cm.records[0].getMessage(), "Synchronous handler adapted for middleware " "middleware_exceptions.middleware.async_payment_middleware.", ) @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.NotSyncOrAsyncMiddleware", ] ) def test_not_sync_or_async_middleware(self): msg = ( "Middleware " "middleware_exceptions.middleware.NotSyncOrAsyncMiddleware must " "have at least one of sync_capable/async_capable set to True." ) with self.assertRaisesMessage(RuntimeError, msg): self.client.get("/middleware_exceptions/view/") @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.PaymentMiddleware", ] ) async def test_sync_middleware_async(self): with self.assertLogs("django.request", "DEBUG") as cm: response = await self.async_client.get("/middleware_exceptions/view/") self.assertEqual(response.status_code, 402) self.assertEqual( cm.records[0].getMessage(), "Asynchronous handler adapted for middleware " "middleware_exceptions.middleware.PaymentMiddleware.", ) @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.async_payment_middleware", ] ) async def test_async_middleware_async(self): with self.assertLogs("django.request", "WARNING") as cm: response = await self.async_client.get("/middleware_exceptions/view/") self.assertEqual(response.status_code, 402) self.assertEqual( cm.records[0].getMessage(), "Payment Required: /middleware_exceptions/view/", ) @override_settings( DEBUG=False, MIDDLEWARE=[ "middleware_exceptions.middleware.AsyncNoTemplateResponseMiddleware", ], ) def test_async_process_template_response_returns_none_with_sync_client(self): msg = ( "AsyncNoTemplateResponseMiddleware.process_template_response " "didn't return an HttpResponse object." ) with self.assertRaisesMessage(ValueError, msg): self.client.get("/middleware_exceptions/template_response/") @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.SyncAndAsyncMiddleware", ] ) async def test_async_and_sync_middleware_async_call(self): response = await self.async_client.get("/middleware_exceptions/view/") self.assertEqual(response.content, b"OK") self.assertEqual(response.status_code, 200) @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.SyncAndAsyncMiddleware", ] ) def test_async_and_sync_middleware_sync_call(self): response = self.client.get("/middleware_exceptions/view/") self.assertEqual(response.content, b"OK") self.assertEqual(response.status_code, 200) @override_settings(ROOT_URLCONF="middleware_exceptions.urls") class AsyncMiddlewareTests(SimpleTestCase): @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.AsyncTemplateResponseMiddleware", ] ) async def test_process_template_response(self): response = await self.async_client.get( "/middleware_exceptions/template_response/" ) self.assertEqual( response.content, b"template_response OK\nAsyncTemplateResponseMiddleware", ) @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.AsyncNoTemplateResponseMiddleware", ] ) async def test_process_template_response_returns_none(self): msg = ( "AsyncNoTemplateResponseMiddleware.process_template_response " "didn't return an HttpResponse object. It returned None instead." ) with self.assertRaisesMessage(ValueError, msg): await self.async_client.get("/middleware_exceptions/template_response/") @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.AsyncProcessExceptionMiddleware", ] ) async def test_exception_in_render_passed_to_process_exception(self): response = await self.async_client.get( "/middleware_exceptions/exception_in_render/" ) self.assertEqual(response.content, b"Exception caught") @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.AsyncProcessExceptionMiddleware", ] ) async def test_exception_in_async_render_passed_to_process_exception(self): response = await self.async_client.get( "/middleware_exceptions/async_exception_in_render/" ) self.assertEqual(response.content, b"Exception caught") @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.AsyncProcessExceptionMiddleware", ] ) async def test_view_exception_handled_by_process_exception(self): response = await self.async_client.get("/middleware_exceptions/error/") self.assertEqual(response.content, b"Exception caught") @override_settings( MIDDLEWARE=[ "middleware_exceptions.middleware.AsyncProcessViewMiddleware", ] ) async def test_process_view_return_response(self): response = await self.async_client.get("/middleware_exceptions/view/") self.assertEqual(response.content, b"Processed view normal_view")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/middleware_exceptions/urls.py
tests/middleware_exceptions/urls.py
from django.urls import path from . import views urlpatterns = [ path("middleware_exceptions/view/", views.normal_view), path("middleware_exceptions/error/", views.server_error), path("middleware_exceptions/permission_denied/", views.permission_denied), path("middleware_exceptions/exception_in_render/", views.exception_in_render), path("middleware_exceptions/template_response/", views.template_response), # Async views. path( "middleware_exceptions/async_exception_in_render/", views.async_exception_in_render, ), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/transaction_hooks/models.py
tests/transaction_hooks/models.py
from django.db import models class Thing(models.Model): num = models.IntegerField()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/transaction_hooks/__init__.py
tests/transaction_hooks/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/transaction_hooks/tests.py
tests/transaction_hooks/tests.py
from functools import partial from django.db import connection, transaction from django.test import TransactionTestCase, skipUnlessDBFeature from .models import Thing class ForcedError(Exception): pass @skipUnlessDBFeature("supports_transactions") class TestConnectionOnCommit(TransactionTestCase): """ Tests for transaction.on_commit(). Creation/checking of database objects in parallel with callback tracking is to verify that the behavior of the two match in all tested cases. """ available_apps = ["transaction_hooks"] def setUp(self): self.notified = [] def notify(self, id_): if id_ == "error": raise ForcedError() self.notified.append(id_) def do(self, num): """Create a Thing instance and notify about it.""" Thing.objects.create(num=num) transaction.on_commit(lambda: self.notify(num)) def assertDone(self, nums): self.assertNotified(nums) self.assertEqual(sorted(t.num for t in Thing.objects.all()), sorted(nums)) def assertNotified(self, nums): self.assertEqual(self.notified, nums) def test_executes_immediately_if_no_transaction(self): self.do(1) self.assertDone([1]) def test_robust_if_no_transaction(self): def robust_callback(): raise ForcedError("robust callback") with self.assertLogs("django.db.backends.base", "ERROR") as cm: transaction.on_commit(robust_callback, robust=True) self.do(1) self.assertDone([1]) log_record = cm.records[0] self.assertEqual( log_record.getMessage(), "Error calling TestConnectionOnCommit.test_robust_if_no_transaction." "<locals>.robust_callback in on_commit() (robust callback).", ) self.assertIsNotNone(log_record.exc_info) raised_exception = log_record.exc_info[1] self.assertIsInstance(raised_exception, ForcedError) self.assertEqual(str(raised_exception), "robust callback") def test_robust_if_no_transaction_with_callback_as_partial(self): def robust_callback(): raise ForcedError("robust callback") robust_callback_partial = partial(robust_callback) with self.assertLogs("django.db.backends.base", "ERROR") as cm: transaction.on_commit(robust_callback_partial, robust=True) self.do(1) self.assertDone([1]) log_record = cm.records[0] self.assertEqual( log_record.getMessage(), f"Error calling {robust_callback_partial} " f"in on_commit() (robust callback).", ) self.assertIsNotNone(log_record.exc_info) raised_exception = log_record.exc_info[1] self.assertIsInstance(raised_exception, ForcedError) self.assertEqual(str(raised_exception), "robust callback") def test_robust_transaction(self): def robust_callback(): raise ForcedError("robust callback") with self.assertLogs("django.db.backends", "ERROR") as cm: with transaction.atomic(): transaction.on_commit(robust_callback, robust=True) self.do(1) self.assertDone([1]) log_record = cm.records[0] self.assertEqual( log_record.getMessage(), "Error calling TestConnectionOnCommit.test_robust_transaction.<locals>." "robust_callback in on_commit() during transaction (robust callback).", ) self.assertIsNotNone(log_record.exc_info) raised_exception = log_record.exc_info[1] self.assertIsInstance(raised_exception, ForcedError) self.assertEqual(str(raised_exception), "robust callback") def test_robust_transaction_with_callback_as_partial(self): def robust_callback(): raise ForcedError("robust callback") robust_callback_partial = partial(robust_callback) with self.assertLogs("django.db.backends", "ERROR") as cm: with transaction.atomic(): transaction.on_commit(robust_callback_partial, robust=True) self.do(1) self.assertDone([1]) log_record = cm.records[0] self.assertEqual( log_record.getMessage(), f"Error calling {robust_callback_partial} in on_commit() during " "transaction (robust callback).", ) self.assertIsNotNone(log_record.exc_info) raised_exception = log_record.exc_info[1] self.assertIsInstance(raised_exception, ForcedError) self.assertEqual(str(raised_exception), "robust callback") def test_delays_execution_until_after_transaction_commit(self): with transaction.atomic(): self.do(1) self.assertNotified([]) self.assertDone([1]) def test_does_not_execute_if_transaction_rolled_back(self): try: with transaction.atomic(): self.do(1) raise ForcedError() except ForcedError: pass self.assertDone([]) def test_executes_only_after_final_transaction_committed(self): with transaction.atomic(): with transaction.atomic(): self.do(1) self.assertNotified([]) self.assertNotified([]) self.assertDone([1]) def test_discards_hooks_from_rolled_back_savepoint(self): with transaction.atomic(): # one successful savepoint with transaction.atomic(): self.do(1) # one failed savepoint try: with transaction.atomic(): self.do(2) raise ForcedError() except ForcedError: pass # another successful savepoint with transaction.atomic(): self.do(3) # only hooks registered during successful savepoints execute self.assertDone([1, 3]) def test_no_hooks_run_from_failed_transaction(self): """If outer transaction fails, no hooks from within it run.""" try: with transaction.atomic(): with transaction.atomic(): self.do(1) raise ForcedError() except ForcedError: pass self.assertDone([]) def test_inner_savepoint_rolled_back_with_outer(self): with transaction.atomic(): try: with transaction.atomic(): with transaction.atomic(): self.do(1) raise ForcedError() except ForcedError: pass self.do(2) self.assertDone([2]) def test_no_savepoints_atomic_merged_with_outer(self): with transaction.atomic(): with transaction.atomic(): self.do(1) try: with transaction.atomic(savepoint=False): raise ForcedError() except ForcedError: pass self.assertDone([]) def test_inner_savepoint_does_not_affect_outer(self): with transaction.atomic(): with transaction.atomic(): self.do(1) try: with transaction.atomic(): raise ForcedError() except ForcedError: pass self.assertDone([1]) def test_runs_hooks_in_order_registered(self): with transaction.atomic(): self.do(1) with transaction.atomic(): self.do(2) self.do(3) self.assertDone([1, 2, 3]) def test_hooks_cleared_after_successful_commit(self): with transaction.atomic(): self.do(1) with transaction.atomic(): self.do(2) self.assertDone([1, 2]) # not [1, 1, 2] def test_hooks_cleared_after_rollback(self): try: with transaction.atomic(): self.do(1) raise ForcedError() except ForcedError: pass with transaction.atomic(): self.do(2) self.assertDone([2]) @skipUnlessDBFeature("test_db_allows_multiple_connections") def test_hooks_cleared_on_reconnect(self): with transaction.atomic(): self.do(1) connection.close() connection.connect() with transaction.atomic(): self.do(2) self.assertDone([2]) def test_error_in_hook_doesnt_prevent_clearing_hooks(self): try: with transaction.atomic(): transaction.on_commit(lambda: self.notify("error")) except ForcedError: pass with transaction.atomic(): self.do(1) self.assertDone([1]) def test_db_query_in_hook(self): with transaction.atomic(): Thing.objects.create(num=1) transaction.on_commit( lambda: [self.notify(t.num) for t in Thing.objects.all()] ) self.assertDone([1]) def test_transaction_in_hook(self): def on_commit(): with transaction.atomic(): t = Thing.objects.create(num=1) self.notify(t.num) with transaction.atomic(): transaction.on_commit(on_commit) self.assertDone([1]) def test_hook_in_hook(self): def on_commit(i, add_hook): with transaction.atomic(): if add_hook: transaction.on_commit(lambda: on_commit(i + 10, False)) t = Thing.objects.create(num=i) self.notify(t.num) with transaction.atomic(): transaction.on_commit(lambda: on_commit(1, True)) transaction.on_commit(lambda: on_commit(2, True)) self.assertDone([1, 11, 2, 12]) def test_raises_exception_non_autocommit_mode(self): def should_never_be_called(): raise AssertionError("this function should never be called") try: connection.set_autocommit(False) msg = "on_commit() cannot be used in manual transaction management" with self.assertRaisesMessage(transaction.TransactionManagementError, msg): transaction.on_commit(should_never_be_called) finally: connection.set_autocommit(True) def test_raises_exception_non_callable(self): msg = "on_commit()'s callback must be a callable." with self.assertRaisesMessage(TypeError, msg): transaction.on_commit(None)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/lookup/models.py
tests/lookup/models.py
""" The lookup API This demonstrates features of the database API. """ from django.db import models from django.db.models.lookups import IsNull class Alarm(models.Model): desc = models.CharField(max_length=100) time = models.TimeField() def __str__(self): return "%s (%s)" % (self.time, self.desc) class Author(models.Model): name = models.CharField(max_length=100) alias = models.CharField(max_length=50, null=True, blank=True) bio = models.TextField(null=True) class Meta: ordering = ("name",) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() author = models.ForeignKey(Author, models.SET_NULL, blank=True, null=True) slug = models.SlugField(unique=True, blank=True, null=True) class Meta: ordering = ("-pub_date", "headline") def __str__(self): return self.headline class Tag(models.Model): articles = models.ManyToManyField(Article) name = models.CharField(max_length=100) class Meta: ordering = ("name",) class NulledTextField(models.TextField): def get_prep_value(self, value): return None if value == "" else value @NulledTextField.register_lookup class NulledTransform(models.Transform): lookup_name = "nulled" template = "NULL" @NulledTextField.register_lookup class IsNullWithNoneAsRHS(IsNull): lookup_name = "isnull_none_rhs" can_use_none_as_rhs = True class Season(models.Model): year = models.PositiveSmallIntegerField() gt = models.IntegerField(null=True, blank=True) nulled_text_field = NulledTextField(null=True) class Meta: constraints = [ models.UniqueConstraint(fields=["year"], name="season_year_unique"), ] def __str__(self): return str(self.year) class Game(models.Model): season = models.ForeignKey(Season, models.CASCADE, related_name="games") home = models.CharField(max_length=100) away = models.CharField(max_length=100) class Player(models.Model): name = models.CharField(max_length=100) games = models.ManyToManyField(Game, related_name="players") class Product(models.Model): name = models.CharField(max_length=80) qty_target = models.DecimalField(max_digits=6, decimal_places=2) class Stock(models.Model): product = models.ForeignKey(Product, models.CASCADE) short = models.BooleanField(default=False) qty_available = models.DecimalField(max_digits=6, decimal_places=2) class Freebie(models.Model): gift_product = models.ForeignKey(Product, models.CASCADE) stock_id = models.IntegerField(blank=True, null=True) stock = models.ForeignObject( Stock, from_fields=["stock_id", "gift_product"], to_fields=["id", "product"], on_delete=models.CASCADE, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/lookup/test_decimalfield.py
tests/lookup/test_decimalfield.py
from django.db.models import F, Sum from django.test import TestCase from .models import Product, Stock class DecimalFieldLookupTests(TestCase): @classmethod def setUpTestData(cls): cls.p1 = Product.objects.create(name="Product1", qty_target=10) Stock.objects.create(product=cls.p1, qty_available=5) Stock.objects.create(product=cls.p1, qty_available=6) cls.p2 = Product.objects.create(name="Product2", qty_target=10) Stock.objects.create(product=cls.p2, qty_available=5) Stock.objects.create(product=cls.p2, qty_available=5) cls.p3 = Product.objects.create(name="Product3", qty_target=10) Stock.objects.create(product=cls.p3, qty_available=5) Stock.objects.create(product=cls.p3, qty_available=4) cls.queryset = Product.objects.annotate( qty_available_sum=Sum("stock__qty_available"), ).annotate(qty_needed=F("qty_target") - F("qty_available_sum")) def test_gt(self): qs = self.queryset.filter(qty_needed__gt=0) self.assertCountEqual(qs, [self.p3]) def test_gte(self): qs = self.queryset.filter(qty_needed__gte=0) self.assertCountEqual(qs, [self.p2, self.p3]) def test_lt(self): qs = self.queryset.filter(qty_needed__lt=0) self.assertCountEqual(qs, [self.p1]) def test_lte(self): qs = self.queryset.filter(qty_needed__lte=0) self.assertCountEqual(qs, [self.p1, self.p2])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/lookup/__init__.py
tests/lookup/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/lookup/tests.py
tests/lookup/tests.py
import collections.abc from datetime import datetime from math import ceil from operator import attrgetter from unittest import mock, skipUnless from django.core.exceptions import FieldError from django.db import connection, models from django.db.models import ( BooleanField, Case, Exists, ExpressionWrapper, F, Max, OuterRef, Q, Subquery, Value, When, ) from django.db.models.functions import Abs, Cast, Length, Substr from django.db.models.lookups import ( Exact, GreaterThan, GreaterThanOrEqual, In, IsNull, LessThan, LessThanOrEqual, ) from django.test import TestCase, skipUnlessDBFeature from django.test.utils import ignore_warnings, isolate_apps, register_lookup from django.utils.deprecation import RemovedInDjango70Warning from .models import ( Article, Author, Freebie, Game, IsNullWithNoneAsRHS, Player, Product, Season, Stock, Tag, ) class LookupTests(TestCase): @classmethod def setUpTestData(cls): # Create a few Authors. cls.au1 = Author.objects.create(name="Author 1", alias="a1", bio="x" * 4001) cls.au2 = Author.objects.create(name="Author 2", alias="a2") # Create a few Articles. cls.a1 = Article.objects.create( headline="Article 1", pub_date=datetime(2005, 7, 26), author=cls.au1, slug="a1", ) cls.a2 = Article.objects.create( headline="Article 2", pub_date=datetime(2005, 7, 27), author=cls.au1, slug="a2", ) cls.a3 = Article.objects.create( headline="Article 3", pub_date=datetime(2005, 7, 27), author=cls.au1, slug="a3", ) cls.a4 = Article.objects.create( headline="Article 4", pub_date=datetime(2005, 7, 28), author=cls.au1, slug="a4", ) cls.a5 = Article.objects.create( headline="Article 5", pub_date=datetime(2005, 8, 1, 9, 0), author=cls.au2, slug="a5", ) cls.a6 = Article.objects.create( headline="Article 6", pub_date=datetime(2005, 8, 1, 8, 0), author=cls.au2, slug="a6", ) cls.a7 = Article.objects.create( headline="Article 7", pub_date=datetime(2005, 7, 27), author=cls.au2, slug="a7", ) # Create a few Tags. cls.t1 = Tag.objects.create(name="Tag 1") cls.t1.articles.add(cls.a1, cls.a2, cls.a3) cls.t2 = Tag.objects.create(name="Tag 2") cls.t2.articles.add(cls.a3, cls.a4, cls.a5) cls.t3 = Tag.objects.create(name="Tag 3") cls.t3.articles.add(cls.a5, cls.a6, cls.a7) def test_exists(self): # We can use .exists() to check that there are some self.assertTrue(Article.objects.exists()) for a in Article.objects.all(): a.delete() # There should be none now! self.assertFalse(Article.objects.exists()) def test_lookup_int_as_str(self): # Integer value can be queried using string self.assertSequenceEqual( Article.objects.filter(id__iexact=str(self.a1.id)), [self.a1], ) @skipUnlessDBFeature("supports_date_lookup_using_string") def test_lookup_date_as_str(self): # A date lookup can be performed using a string search self.assertSequenceEqual( Article.objects.filter(pub_date__startswith="2005"), [self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1], ) def test_iterator(self): # Each QuerySet gets iterator(), which is a generator that "lazily" # returns results using database-level iteration. self.assertIsInstance(Article.objects.iterator(), collections.abc.Iterator) self.assertQuerySetEqual( Article.objects.iterator(), [ "Article 5", "Article 6", "Article 4", "Article 2", "Article 3", "Article 7", "Article 1", ], transform=attrgetter("headline"), ) # iterator() can be used on any QuerySet. self.assertQuerySetEqual( Article.objects.filter(headline__endswith="4").iterator(), ["Article 4"], transform=attrgetter("headline"), ) def test_count(self): # count() returns the number of objects matching search criteria. self.assertEqual(Article.objects.count(), 7) self.assertEqual( Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).count(), 3 ) self.assertEqual( Article.objects.filter(headline__startswith="Blah blah").count(), 0 ) # count() should respect sliced query sets. articles = Article.objects.all() self.assertEqual(articles.count(), 7) self.assertEqual(articles[:4].count(), 4) self.assertEqual(articles[1:100].count(), 6) self.assertEqual(articles[10:100].count(), 0) # Date and date/time lookups can also be done with strings. self.assertEqual( Article.objects.filter(pub_date__exact="2005-07-27 00:00:00").count(), 3 ) def test_in_bulk(self): # in_bulk() takes a list of IDs and returns a dictionary mapping IDs to # objects. arts = Article.objects.in_bulk([self.a1.id, self.a2.id]) self.assertEqual(arts[self.a1.id], self.a1) self.assertEqual(arts[self.a2.id], self.a2) self.assertEqual( Article.objects.in_bulk(), { self.a1.id: self.a1, self.a2.id: self.a2, self.a3.id: self.a3, self.a4.id: self.a4, self.a5.id: self.a5, self.a6.id: self.a6, self.a7.id: self.a7, }, ) self.assertEqual(Article.objects.in_bulk([self.a3.id]), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk({self.a3.id}), {self.a3.id: self.a3}) self.assertEqual( Article.objects.in_bulk(frozenset([self.a3.id])), {self.a3.id: self.a3} ) self.assertEqual(Article.objects.in_bulk((self.a3.id,)), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk([1000]), {}) self.assertEqual(Article.objects.in_bulk([]), {}) self.assertEqual( Article.objects.in_bulk(iter([self.a1.id])), {self.a1.id: self.a1} ) self.assertEqual(Article.objects.in_bulk(iter([])), {}) with self.assertRaises(TypeError): Article.objects.in_bulk(headline__startswith="Blah") def test_in_bulk_lots_of_ids(self): test_range = 2000 max_query_params = connection.features.max_query_params expected_num_queries = ( ceil(test_range / max_query_params) if max_query_params else 1 ) Author.objects.bulk_create( [Author() for i in range(test_range - Author.objects.count())] ) authors = {author.pk: author for author in Author.objects.all()} with self.assertNumQueries(expected_num_queries): self.assertEqual(Author.objects.in_bulk(authors), authors) def test_in_bulk_with_field(self): self.assertEqual( Article.objects.in_bulk( [self.a1.slug, self.a2.slug, self.a3.slug], field_name="slug" ), { self.a1.slug: self.a1, self.a2.slug: self.a2, self.a3.slug: self.a3, }, ) def test_in_bulk_meta_constraint(self): season_2011 = Season.objects.create(year=2011) season_2012 = Season.objects.create(year=2012) Season.objects.create(year=2013) self.assertEqual( Season.objects.in_bulk( [season_2011.year, season_2012.year], field_name="year", ), {season_2011.year: season_2011, season_2012.year: season_2012}, ) def test_in_bulk_non_unique_field(self): msg = "in_bulk()'s field_name must be a unique field but 'author' isn't." with self.assertRaisesMessage(ValueError, msg): Article.objects.in_bulk([self.au1], field_name="author") def test_in_bulk_preserve_ordering(self): self.assertEqual( list(Article.objects.in_bulk([self.a2.id, self.a1.id])), [self.a2.id, self.a1.id], ) def test_in_bulk_preserve_ordering_with_batch_size(self): qs = Article.objects.all() with ( mock.patch.object(connection.ops, "bulk_batch_size", return_value=2), self.assertNumQueries(2), ): self.assertEqual( list(qs.in_bulk([self.a4.id, self.a3.id, self.a2.id, self.a1.id])), [self.a4.id, self.a3.id, self.a2.id, self.a1.id], ) @skipUnlessDBFeature("can_distinct_on_fields") def test_in_bulk_distinct_field(self): self.assertEqual( Article.objects.order_by("headline") .distinct("headline") .in_bulk( [self.a1.headline, self.a5.headline], field_name="headline", ), {self.a1.headline: self.a1, self.a5.headline: self.a5}, ) @skipUnlessDBFeature("can_distinct_on_fields") def test_in_bulk_multiple_distinct_field(self): msg = "in_bulk()'s field_name must be a unique field but 'pub_date' isn't." with self.assertRaisesMessage(ValueError, msg): Article.objects.order_by("headline", "pub_date").distinct( "headline", "pub_date", ).in_bulk(field_name="pub_date") @isolate_apps("lookup") def test_in_bulk_non_unique_meta_constaint(self): class Model(models.Model): ean = models.CharField(max_length=100) brand = models.CharField(max_length=100) name = models.CharField(max_length=80) class Meta: constraints = [ models.UniqueConstraint( fields=["ean"], name="partial_ean_unique", condition=models.Q(is_active=True), ), models.UniqueConstraint( fields=["brand", "name"], name="together_brand_name_unique", ), ] msg = "in_bulk()'s field_name must be a unique field but '%s' isn't." for field_name in ["brand", "ean"]: with self.subTest(field_name=field_name): with self.assertRaisesMessage(ValueError, msg % field_name): Model.objects.in_bulk(field_name=field_name) def test_in_bulk_sliced_queryset(self): msg = "Cannot use 'limit' or 'offset' with in_bulk()." with self.assertRaisesMessage(TypeError, msg): Article.objects.all()[0:5].in_bulk([self.a1.id, self.a2.id]) def test_in_bulk_values_empty(self): arts = Article.objects.values().in_bulk([]) self.assertEqual(arts, {}) def test_in_bulk_values_all(self): Article.objects.exclude(pk__in=[self.a1.pk, self.a2.pk]).delete() arts = Article.objects.values().in_bulk() self.assertEqual( arts, { self.a1.pk: { "id": self.a1.pk, "author_id": self.au1.pk, "headline": "Article 1", "pub_date": self.a1.pub_date, "slug": "a1", }, self.a2.pk: { "id": self.a2.pk, "author_id": self.au1.pk, "headline": "Article 2", "pub_date": self.a2.pub_date, "slug": "a2", }, }, ) def test_in_bulk_values_pks(self): arts = Article.objects.values().in_bulk([self.a1.pk]) self.assertEqual( arts, { self.a1.pk: { "id": self.a1.pk, "author_id": self.au1.pk, "headline": "Article 1", "pub_date": self.a1.pub_date, "slug": "a1", } }, ) def test_in_bulk_values_fields(self): arts = Article.objects.values("headline").in_bulk([self.a1.pk]) self.assertEqual( arts, {self.a1.pk: {"headline": "Article 1"}}, ) def test_in_bulk_values_fields_including_pk(self): arts = Article.objects.values("pk", "headline").in_bulk([self.a1.pk]) self.assertEqual( arts, {self.a1.pk: {"pk": self.a1.pk, "headline": "Article 1"}}, ) def test_in_bulk_values_fields_pk(self): arts = Article.objects.values("pk").in_bulk([self.a1.pk]) self.assertEqual( arts, {self.a1.pk: {"pk": self.a1.pk}}, ) def test_in_bulk_values_fields_id(self): arts = Article.objects.values("id").in_bulk([self.a1.pk]) self.assertEqual( arts, {self.a1.pk: {"id": self.a1.pk}}, ) def test_in_bulk_values_alternative_field_name(self): arts = Article.objects.values("headline").in_bulk( [self.a1.slug], field_name="slug" ) self.assertEqual( arts, {self.a1.slug: {"headline": "Article 1"}}, ) def test_in_bulk_values_list_empty(self): arts = Article.objects.values_list().in_bulk([]) self.assertEqual(arts, {}) def test_in_bulk_values_list_all(self): Article.objects.exclude(pk__in=[self.a1.pk, self.a2.pk]).delete() arts = Article.objects.values_list().in_bulk() self.assertEqual( arts, { self.a1.pk: ( self.a1.pk, "Article 1", self.a1.pub_date, self.au1.pk, "a1", ), self.a2.pk: ( self.a2.pk, "Article 2", self.a2.pub_date, self.au1.pk, "a2", ), }, ) def test_in_bulk_values_list_fields(self): arts = Article.objects.values_list("headline").in_bulk([self.a1.pk, self.a2.pk]) self.assertEqual( arts, { self.a1.pk: ("Article 1",), self.a2.pk: ("Article 2",), }, ) def test_in_bulk_values_list_fields_including_pk(self): arts = Article.objects.values_list("pk", "headline").in_bulk( [self.a1.pk, self.a2.pk] ) self.assertEqual( arts, { self.a1.pk: (self.a1.pk, "Article 1"), self.a2.pk: (self.a2.pk, "Article 2"), }, ) def test_in_bulk_values_list_fields_pk(self): arts = Article.objects.values_list("pk").in_bulk([self.a1.pk, self.a2.pk]) self.assertEqual( arts, { self.a1.pk: (self.a1.pk,), self.a2.pk: (self.a2.pk,), }, ) def test_in_bulk_values_list_fields_id(self): arts = Article.objects.values_list("id").in_bulk([self.a1.pk, self.a2.pk]) self.assertEqual( arts, { self.a1.pk: (self.a1.pk,), self.a2.pk: (self.a2.pk,), }, ) def test_in_bulk_values_list_named(self): arts = Article.objects.values_list(named=True).in_bulk([self.a1.pk, self.a2.pk]) self.assertIsInstance(arts, dict) self.assertEqual(len(arts), 2) arts1 = arts[self.a1.pk] self.assertEqual( arts1._fields, ("pk", "id", "headline", "pub_date", "author_id", "slug") ) self.assertEqual(arts1.pk, self.a1.pk) self.assertEqual(arts1.headline, "Article 1") self.assertEqual(arts1.pub_date, self.a1.pub_date) self.assertEqual(arts1.author_id, self.au1.pk) self.assertEqual(arts1.slug, "a1") def test_in_bulk_values_list_named_fields(self): arts = Article.objects.values_list("pk", "headline", named=True).in_bulk( [self.a1.pk, self.a2.pk] ) self.assertIsInstance(arts, dict) self.assertEqual(len(arts), 2) arts1 = arts[self.a1.pk] self.assertEqual(arts1._fields, ("pk", "headline")) self.assertEqual(arts1.pk, self.a1.pk) self.assertEqual(arts1.headline, "Article 1") def test_in_bulk_values_list_named_fields_alternative_field(self): arts = Article.objects.values_list("headline", named=True).in_bulk( [self.a1.slug, self.a2.slug], field_name="slug" ) self.assertEqual(len(arts), 2) arts1 = arts[self.a1.slug] self.assertEqual(arts1._fields, ("slug", "headline")) self.assertEqual(arts1.slug, "a1") self.assertEqual(arts1.headline, "Article 1") # RemovedInDjango70Warning: When the deprecation ends, remove this # test. def test_in_bulk_values_list_flat_empty(self): with ignore_warnings(category=RemovedInDjango70Warning): arts = Article.objects.values_list(flat=True).in_bulk([]) self.assertEqual(arts, {}) # RemovedInDjango70Warning: When the deprecation ends, remove this # test. def test_in_bulk_values_list_flat_all(self): Article.objects.exclude(pk__in=[self.a1.pk, self.a2.pk]).delete() with ignore_warnings(category=RemovedInDjango70Warning): arts = Article.objects.values_list(flat=True).in_bulk() self.assertEqual( arts, { self.a1.pk: self.a1.pk, self.a2.pk: self.a2.pk, }, ) # RemovedInDjango70Warning: When the deprecation ends, remove this # test. def test_in_bulk_values_list_flat_pks(self): with ignore_warnings(category=RemovedInDjango70Warning): arts = Article.objects.values_list(flat=True).in_bulk( [self.a1.pk, self.a2.pk] ) self.assertEqual( arts, { self.a1.pk: self.a1.pk, self.a2.pk: self.a2.pk, }, ) def test_in_bulk_values_list_flat_field(self): arts = Article.objects.values_list("headline", flat=True).in_bulk( [self.a1.pk, self.a2.pk] ) self.assertEqual( arts, {self.a1.pk: "Article 1", self.a2.pk: "Article 2"}, ) def test_in_bulk_values_list_flat_field_pk(self): arts = Article.objects.values_list("pk", flat=True).in_bulk( [self.a1.pk, self.a2.pk] ) self.assertEqual( arts, { self.a1.pk: self.a1.pk, self.a2.pk: self.a2.pk, }, ) def test_in_bulk_values_list_flat_field_id(self): arts = Article.objects.values_list("id", flat=True).in_bulk( [self.a1.pk, self.a2.pk] ) self.assertEqual( arts, { self.a1.pk: self.a1.pk, self.a2.pk: self.a2.pk, }, ) def test_values(self): # values() returns a list of dictionaries instead of object instances, # and you can specify which fields you want to retrieve. self.assertSequenceEqual( Article.objects.filter(id__in=(self.a5.id, self.a6.id)).values(), [ { "id": self.a5.id, "headline": "Article 5", "pub_date": datetime(2005, 8, 1, 9, 0), "author_id": self.au2.id, "slug": "a5", }, { "id": self.a6.id, "headline": "Article 6", "pub_date": datetime(2005, 8, 1, 8, 0), "author_id": self.au2.id, "slug": "a6", }, ], ) self.assertSequenceEqual( Article.objects.values("headline"), [ {"headline": "Article 5"}, {"headline": "Article 6"}, {"headline": "Article 4"}, {"headline": "Article 2"}, {"headline": "Article 3"}, {"headline": "Article 7"}, {"headline": "Article 1"}, ], ) self.assertSequenceEqual( Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).values("id"), [{"id": self.a2.id}, {"id": self.a3.id}, {"id": self.a7.id}], ) self.assertSequenceEqual( Article.objects.values("id", "headline"), [ {"id": self.a5.id, "headline": "Article 5"}, {"id": self.a6.id, "headline": "Article 6"}, {"id": self.a4.id, "headline": "Article 4"}, {"id": self.a2.id, "headline": "Article 2"}, {"id": self.a3.id, "headline": "Article 3"}, {"id": self.a7.id, "headline": "Article 7"}, {"id": self.a1.id, "headline": "Article 1"}, ], ) # You can use values() with iterator() for memory savings, # because iterator() uses database-level iteration. self.assertSequenceEqual( list(Article.objects.values("id", "headline").iterator()), [ {"headline": "Article 5", "id": self.a5.id}, {"headline": "Article 6", "id": self.a6.id}, {"headline": "Article 4", "id": self.a4.id}, {"headline": "Article 2", "id": self.a2.id}, {"headline": "Article 3", "id": self.a3.id}, {"headline": "Article 7", "id": self.a7.id}, {"headline": "Article 1", "id": self.a1.id}, ], ) # The values() method works with "extra" fields specified in # extra(select). self.assertSequenceEqual( Article.objects.extra(select={"id_plus_one": "id + 1"}).values( "id", "id_plus_one" ), [ {"id": self.a5.id, "id_plus_one": self.a5.id + 1}, {"id": self.a6.id, "id_plus_one": self.a6.id + 1}, {"id": self.a4.id, "id_plus_one": self.a4.id + 1}, {"id": self.a2.id, "id_plus_one": self.a2.id + 1}, {"id": self.a3.id, "id_plus_one": self.a3.id + 1}, {"id": self.a7.id, "id_plus_one": self.a7.id + 1}, {"id": self.a1.id, "id_plus_one": self.a1.id + 1}, ], ) data = { "id_plus_one": "id+1", "id_plus_two": "id+2", "id_plus_three": "id+3", "id_plus_four": "id+4", "id_plus_five": "id+5", "id_plus_six": "id+6", "id_plus_seven": "id+7", "id_plus_eight": "id+8", } self.assertSequenceEqual( Article.objects.filter(id=self.a1.id).extra(select=data).values(*data), [ { "id_plus_one": self.a1.id + 1, "id_plus_two": self.a1.id + 2, "id_plus_three": self.a1.id + 3, "id_plus_four": self.a1.id + 4, "id_plus_five": self.a1.id + 5, "id_plus_six": self.a1.id + 6, "id_plus_seven": self.a1.id + 7, "id_plus_eight": self.a1.id + 8, } ], ) # You can specify fields from forward and reverse relations, just like # filter(). self.assertSequenceEqual( Article.objects.values("headline", "author__name"), [ {"headline": self.a5.headline, "author__name": self.au2.name}, {"headline": self.a6.headline, "author__name": self.au2.name}, {"headline": self.a4.headline, "author__name": self.au1.name}, {"headline": self.a2.headline, "author__name": self.au1.name}, {"headline": self.a3.headline, "author__name": self.au1.name}, {"headline": self.a7.headline, "author__name": self.au2.name}, {"headline": self.a1.headline, "author__name": self.au1.name}, ], ) self.assertSequenceEqual( Author.objects.values("name", "article__headline").order_by( "name", "article__headline" ), [ {"name": self.au1.name, "article__headline": self.a1.headline}, {"name": self.au1.name, "article__headline": self.a2.headline}, {"name": self.au1.name, "article__headline": self.a3.headline}, {"name": self.au1.name, "article__headline": self.a4.headline}, {"name": self.au2.name, "article__headline": self.a5.headline}, {"name": self.au2.name, "article__headline": self.a6.headline}, {"name": self.au2.name, "article__headline": self.a7.headline}, ], ) self.assertSequenceEqual( ( Author.objects.values( "name", "article__headline", "article__tag__name" ).order_by("name", "article__headline", "article__tag__name") ), [ { "name": self.au1.name, "article__headline": self.a1.headline, "article__tag__name": self.t1.name, }, { "name": self.au1.name, "article__headline": self.a2.headline, "article__tag__name": self.t1.name, }, { "name": self.au1.name, "article__headline": self.a3.headline, "article__tag__name": self.t1.name, }, { "name": self.au1.name, "article__headline": self.a3.headline, "article__tag__name": self.t2.name, }, { "name": self.au1.name, "article__headline": self.a4.headline, "article__tag__name": self.t2.name, }, { "name": self.au2.name, "article__headline": self.a5.headline, "article__tag__name": self.t2.name, }, { "name": self.au2.name, "article__headline": self.a5.headline, "article__tag__name": self.t3.name, }, { "name": self.au2.name, "article__headline": self.a6.headline, "article__tag__name": self.t3.name, }, { "name": self.au2.name, "article__headline": self.a7.headline, "article__tag__name": self.t3.name, }, ], ) # However, an exception FieldDoesNotExist will be thrown if you specify # a nonexistent field name in values() (a field that is neither in the # model nor in extra(select)). msg = ( "Cannot resolve keyword 'id_plus_two' into field. Choices are: " "author, author_id, headline, id, id_plus_one, pub_date, slug, tag" ) with self.assertRaisesMessage(FieldError, msg): Article.objects.extra(select={"id_plus_one": "id + 1"}).values( "id", "id_plus_two" ) # If you don't specify field names to values(), all are returned. self.assertSequenceEqual( Article.objects.filter(id=self.a5.id).values(), [ { "id": self.a5.id, "author_id": self.au2.id, "headline": "Article 5", "pub_date": datetime(2005, 8, 1, 9, 0), "slug": "a5", } ], ) def test_values_list(self): # values_list() is similar to values(), except that the results are # returned as a list of tuples, rather than a list of dictionaries. # Within each tuple, the order of the elements is the same as the order # of fields in the values_list() call. self.assertSequenceEqual( Article.objects.filter(id__in=(self.a5.id, self.a6.id)).values_list(), [ ( self.a5.id, "Article 5", datetime(2005, 8, 1, 9, 0), self.au2.id, "a5", ), ( self.a6.id, "Article 6", datetime(2005, 8, 1, 8, 0), self.au2.id, "a6", ), ], ) # RemovedInDjango70Warning: When the deprecation ends, remove this # assertion. with ignore_warnings(category=RemovedInDjango70Warning): qs = Article.objects.values_list(flat=True) self.assertSequenceEqual( qs, [ self.a5.id, self.a6.id, self.a4.id, self.a2.id, self.a3.id, self.a7.id, self.a1.id, ], ) self.assertSequenceEqual( Article.objects.values_list("headline"), [ ("Article 5",), ("Article 6",), ("Article 4",), ("Article 2",), ("Article 3",), ("Article 7",), ("Article 1",), ], ) self.assertSequenceEqual( Article.objects.values_list("id").order_by("id"), [ (self.a1.id,), (self.a2.id,), (self.a3.id,), (self.a4.id,), (self.a5.id,), (self.a6.id,), (self.a7.id,), ], ) self.assertSequenceEqual( Article.objects.values_list("id", flat=True).order_by("id"), [ self.a1.id, self.a2.id, self.a3.id, self.a4.id, self.a5.id, self.a6.id, self.a7.id, ], ) self.assertSequenceEqual( Article.objects.extra(select={"id_plus_one": "id+1"}) .order_by("id") .values_list("id"), [ (self.a1.id,), (self.a2.id,), (self.a3.id,), (self.a4.id,), (self.a5.id,), (self.a6.id,), (self.a7.id,), ], ) self.assertSequenceEqual( Article.objects.extra(select={"id_plus_one": "id+1"}) .order_by("id") .values_list("id_plus_one", "id"), [ (self.a1.id + 1, self.a1.id), (self.a2.id + 1, self.a2.id), (self.a3.id + 1, self.a3.id), (self.a4.id + 1, self.a4.id), (self.a5.id + 1, self.a5.id), (self.a6.id + 1, self.a6.id), (self.a7.id + 1, self.a7.id), ], ) self.assertSequenceEqual( Article.objects.extra(select={"id_plus_one": "id+1"}) .order_by("id") .values_list("id", "id_plus_one"), [ (self.a1.id, self.a1.id + 1), (self.a2.id, self.a2.id + 1), (self.a3.id, self.a3.id + 1), (self.a4.id, self.a4.id + 1), (self.a5.id, self.a5.id + 1), (self.a6.id, self.a6.id + 1), (self.a7.id, self.a7.id + 1), ], ) args = ("name", "article__headline", "article__tag__name") self.assertSequenceEqual(
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/lookup/test_lookups.py
tests/lookup/test_lookups.py
from datetime import datetime from unittest import mock from django.db.models import DateTimeField, Value from django.db.models.lookups import Lookup, YearLookup from django.test import SimpleTestCase class CustomLookup(Lookup): pass class LookupTests(SimpleTestCase): def test_equality(self): lookup = Lookup(Value(1), Value(2)) self.assertEqual(lookup, lookup) self.assertEqual(lookup, Lookup(lookup.lhs, lookup.rhs)) self.assertEqual(lookup, mock.ANY) self.assertNotEqual(lookup, Lookup(lookup.lhs, Value(3))) self.assertNotEqual(lookup, Lookup(Value(3), lookup.rhs)) self.assertNotEqual(lookup, CustomLookup(lookup.lhs, lookup.rhs)) def test_repr(self): tests = [ (Lookup(Value(1), Value("a")), "Lookup(Value(1), Value('a'))"), ( YearLookup( Value(datetime(2010, 1, 1, 0, 0, 0)), Value(datetime(2010, 1, 1, 23, 59, 59)), ), "YearLookup(" "Value(datetime.datetime(2010, 1, 1, 0, 0)), " "Value(datetime.datetime(2010, 1, 1, 23, 59, 59)))", ), ] for lookup, expected in tests: with self.subTest(lookup=lookup): self.assertEqual(repr(lookup), expected) def test_hash(self): lookup = Lookup(Value(1), Value(2)) self.assertEqual(hash(lookup), hash(lookup)) self.assertEqual(hash(lookup), hash(Lookup(lookup.lhs, lookup.rhs))) self.assertNotEqual(hash(lookup), hash(Lookup(lookup.lhs, Value(3)))) self.assertNotEqual(hash(lookup), hash(Lookup(Value(3), lookup.rhs))) self.assertNotEqual(hash(lookup), hash(CustomLookup(lookup.lhs, lookup.rhs))) class YearLookupTests(SimpleTestCase): def test_get_bound_params(self): look_up = YearLookup( lhs=Value(datetime(2010, 1, 1, 0, 0, 0), output_field=DateTimeField()), rhs=Value(datetime(2010, 1, 1, 23, 59, 59), output_field=DateTimeField()), ) msg = "subclasses of YearLookup must provide a get_bound_params() method" with self.assertRaisesMessage(NotImplementedError, msg): look_up.get_bound_params( datetime(2010, 1, 1, 0, 0, 0), datetime(2010, 1, 1, 23, 59, 59) )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/lookup/test_timefield.py
tests/lookup/test_timefield.py
from django.test import TestCase from .models import Alarm class TimeFieldLookupTests(TestCase): @classmethod def setUpTestData(self): # Create a few Alarms self.al1 = Alarm.objects.create(desc="Early", time="05:30") self.al2 = Alarm.objects.create(desc="Late", time="10:00") self.al3 = Alarm.objects.create(desc="Precise", time="12:34:56") def test_hour_lookups(self): self.assertSequenceEqual( Alarm.objects.filter(time__hour=5), [self.al1], ) def test_minute_lookups(self): self.assertSequenceEqual( Alarm.objects.filter(time__minute=30), [self.al1], ) def test_second_lookups(self): self.assertSequenceEqual( Alarm.objects.filter(time__second=56), [self.al3], )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/csrf_tests/views.py
tests/csrf_tests/views.py
from django.http import HttpResponse from django.middleware.csrf import get_token, rotate_token from django.template import Context, RequestContext, Template from django.template.context_processors import csrf from django.utils.decorators import decorator_from_middleware from django.utils.deprecation import MiddlewareMixin from django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie class TestingHttpResponse(HttpResponse): """ A version of HttpResponse that stores what cookie values are passed to set_cookie() when CSRF_USE_SESSIONS=False. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # This is a list of the cookie values passed to set_cookie() over # the course of the request-response. self._cookies_set = [] def set_cookie(self, key, value, **kwargs): super().set_cookie(key, value, **kwargs) self._cookies_set.append(value) class _CsrfCookieRotator(MiddlewareMixin): def process_response(self, request, response): rotate_token(request) return response csrf_rotating_token = decorator_from_middleware(_CsrfCookieRotator) @csrf_protect def protected_view(request): return HttpResponse("OK") @ensure_csrf_cookie def ensure_csrf_cookie_view(request): return HttpResponse("OK") @csrf_protect @ensure_csrf_cookie def ensured_and_protected_view(request): return TestingHttpResponse("OK") @csrf_protect @csrf_rotating_token @ensure_csrf_cookie def sandwiched_rotate_token_view(request): """ This is a view that calls rotate_token() in process_response() between two calls to CsrfViewMiddleware.process_response(). """ return TestingHttpResponse("OK") def post_form_view(request): """Return a POST form (without a token).""" return HttpResponse( content=""" <html> <body><h1>\u00a1Unicode!<form method="post"><input type="text"></form></body> </html> """ ) def token_view(request): context = RequestContext(request, processors=[csrf]) template = Template("{% csrf_token %}") return HttpResponse(template.render(context)) def non_token_view_using_request_processor(request): """Use the csrf view processor instead of the token.""" context = RequestContext(request, processors=[csrf]) template = Template("") return HttpResponse(template.render(context)) def csrf_token_error_handler(request, **kwargs): """This error handler accesses the CSRF token.""" template = Template(get_token(request)) return HttpResponse(template.render(Context()), status=599)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/csrf_tests/test_context_processor.py
tests/csrf_tests/test_context_processor.py
from django.http import HttpRequest from django.template.context_processors import csrf from django.test import SimpleTestCase from .tests import CsrfFunctionTestMixin class TestContextProcessor(CsrfFunctionTestMixin, SimpleTestCase): def test_force_token_to_string(self): request = HttpRequest() test_secret = 32 * "a" request.META["CSRF_COOKIE"] = test_secret token = csrf(request).get("csrf_token") self.assertMaskedSecretCorrect(token, test_secret)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/csrf_tests/csrf_token_error_handler_urls.py
tests/csrf_tests/csrf_token_error_handler_urls.py
urlpatterns = [] handler404 = "csrf_tests.views.csrf_token_error_handler"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/csrf_tests/__init__.py
tests/csrf_tests/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/csrf_tests/tests.py
tests/csrf_tests/tests.py
import logging import re from django.conf import settings from django.contrib.sessions.backends.cache import SessionStore from django.core.exceptions import ImproperlyConfigured from django.http import HttpRequest, HttpResponse, UnreadablePostError from django.middleware.csrf import ( CSRF_ALLOWED_CHARS, CSRF_SECRET_LENGTH, CSRF_SESSION_KEY, CSRF_TOKEN_LENGTH, REASON_BAD_ORIGIN, REASON_CSRF_TOKEN_MISSING, REASON_NO_CSRF_COOKIE, CsrfViewMiddleware, InvalidTokenFormat, RejectRequest, _check_token_format, _does_token_match, _mask_cipher_secret, _unmask_cipher_token, get_token, rotate_token, ) from django.test import SimpleTestCase, override_settings from django.views.decorators.csrf import csrf_exempt, requires_csrf_token from .views import ( ensure_csrf_cookie_view, ensured_and_protected_view, non_token_view_using_request_processor, post_form_view, protected_view, sandwiched_rotate_token_view, token_view, ) # This is a test (unmasked) CSRF cookie / secret. TEST_SECRET = "lcccccccX2kcccccccY2jcccccccssIC" # Two masked versions of TEST_SECRET for testing purposes. MASKED_TEST_SECRET1 = "1bcdefghij2bcdefghij3bcdefghij4bcdefghij5bcdefghij6bcdefghijABCD" MASKED_TEST_SECRET2 = "2JgchWvM1tpxT2lfz9aydoXW9yT1DN3NdLiejYxOOlzzV4nhBbYqmqZYbAV3V5Bf" class CsrfFunctionTestMixin: # This method depends on _unmask_cipher_token() being correct. def assertMaskedSecretCorrect(self, masked_secret, secret): """Test that a string is a valid masked version of a secret.""" self.assertEqual(len(masked_secret), CSRF_TOKEN_LENGTH) self.assertEqual(len(secret), CSRF_SECRET_LENGTH) self.assertTrue( set(masked_secret).issubset(set(CSRF_ALLOWED_CHARS)), msg=f"invalid characters in {masked_secret!r}", ) actual = _unmask_cipher_token(masked_secret) self.assertEqual(actual, secret) def assertForbiddenReason( self, response, logger_cm, reason, levelno=logging.WARNING ): self.assertEqual( records_len := len(logger_cm.records), 1, f"Unexpected number of records for {logger_cm=} in {levelno=} (expected 1, " f"got {records_len}).", ) record = logger_cm.records[0] self.assertEqual(record.getMessage(), "Forbidden (%s): " % reason) self.assertEqual(record.levelno, levelno) self.assertEqual(record.status_code, 403) self.assertEqual(response.status_code, 403) class CsrfFunctionTests(CsrfFunctionTestMixin, SimpleTestCase): def test_unmask_cipher_token(self): cases = [ (TEST_SECRET, MASKED_TEST_SECRET1), (TEST_SECRET, MASKED_TEST_SECRET2), ( 32 * "a", "vFioG3XOLyGyGsPRFyB9iYUs341ufzIEvFioG3XOLyGyGsPRFyB9iYUs341ufzIE", ), (32 * "a", 64 * "a"), (32 * "a", 64 * "b"), (32 * "b", 32 * "a" + 32 * "b"), (32 * "b", 32 * "b" + 32 * "c"), (32 * "c", 32 * "a" + 32 * "c"), ] for secret, masked_secret in cases: with self.subTest(masked_secret=masked_secret): actual = _unmask_cipher_token(masked_secret) self.assertEqual(actual, secret) def test_mask_cipher_secret(self): cases = [ 32 * "a", TEST_SECRET, "da4SrUiHJYoJ0HYQ0vcgisoIuFOxx4ER", ] for secret in cases: with self.subTest(secret=secret): masked = _mask_cipher_secret(secret) self.assertMaskedSecretCorrect(masked, secret) def test_get_token_csrf_cookie_set(self): request = HttpRequest() request.META["CSRF_COOKIE"] = TEST_SECRET self.assertNotIn("CSRF_COOKIE_NEEDS_UPDATE", request.META) token = get_token(request) self.assertMaskedSecretCorrect(token, TEST_SECRET) # The existing cookie is preserved. self.assertEqual(request.META["CSRF_COOKIE"], TEST_SECRET) self.assertIs(request.META["CSRF_COOKIE_NEEDS_UPDATE"], True) def test_get_token_csrf_cookie_not_set(self): request = HttpRequest() self.assertNotIn("CSRF_COOKIE", request.META) self.assertNotIn("CSRF_COOKIE_NEEDS_UPDATE", request.META) token = get_token(request) cookie = request.META["CSRF_COOKIE"] self.assertMaskedSecretCorrect(token, cookie) self.assertIs(request.META["CSRF_COOKIE_NEEDS_UPDATE"], True) def test_rotate_token(self): request = HttpRequest() request.META["CSRF_COOKIE"] = TEST_SECRET self.assertNotIn("CSRF_COOKIE_NEEDS_UPDATE", request.META) rotate_token(request) # The underlying secret was changed. cookie = request.META["CSRF_COOKIE"] self.assertEqual(len(cookie), CSRF_SECRET_LENGTH) self.assertNotEqual(cookie, TEST_SECRET) self.assertIs(request.META["CSRF_COOKIE_NEEDS_UPDATE"], True) def test_check_token_format_valid(self): cases = [ # A token of length CSRF_SECRET_LENGTH. TEST_SECRET, # A token of length CSRF_TOKEN_LENGTH. MASKED_TEST_SECRET1, 64 * "a", ] for token in cases: with self.subTest(token=token): actual = _check_token_format(token) self.assertIsNone(actual) def test_check_token_format_invalid(self): cases = [ (64 * "*", "has invalid characters"), (16 * "a", "has incorrect length"), ] for token, expected_message in cases: with self.subTest(token=token): with self.assertRaisesMessage(InvalidTokenFormat, expected_message): _check_token_format(token) def test_does_token_match(self): cases = [ # Masked tokens match. ((MASKED_TEST_SECRET1, TEST_SECRET), True), ((MASKED_TEST_SECRET2, TEST_SECRET), True), ((64 * "a", _unmask_cipher_token(64 * "a")), True), # Unmasked tokens match. ((TEST_SECRET, TEST_SECRET), True), ((32 * "a", 32 * "a"), True), # Incorrect tokens don't match. ((32 * "a", TEST_SECRET), False), ((64 * "a", TEST_SECRET), False), ] for (token, secret), expected in cases: with self.subTest(token=token, secret=secret): actual = _does_token_match(token, secret) self.assertIs(actual, expected) def test_does_token_match_wrong_token_length(self): with self.assertRaises(AssertionError): _does_token_match(16 * "a", TEST_SECRET) class TestingSessionStore(SessionStore): """ A version of SessionStore that stores what cookie values are passed to set_cookie() when CSRF_USE_SESSIONS=True. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # This is a list of the cookie values passed to set_cookie() over # the course of the request-response. self._cookies_set = [] def __setitem__(self, key, value): super().__setitem__(key, value) self._cookies_set.append(value) class TestingHttpRequest(HttpRequest): """ A version of HttpRequest that lets one track and change some things more easily. """ def __init__(self): super().__init__() self.session = TestingSessionStore() def is_secure(self): return getattr(self, "_is_secure_override", False) class PostErrorRequest(TestingHttpRequest): """ TestingHttpRequest that can raise errors when accessing POST data. """ post_error = None def _get_post(self): if self.post_error is not None: raise self.post_error return self._post def _set_post(self, post): self._post = post POST = property(_get_post, _set_post) class CsrfViewMiddlewareTestMixin(CsrfFunctionTestMixin): """ Shared methods and tests for session-based and cookie-based tokens. """ _csrf_id_cookie = MASKED_TEST_SECRET1 _csrf_id_token = MASKED_TEST_SECRET2 def _set_csrf_cookie(self, req, cookie): raise NotImplementedError("This method must be implemented by a subclass.") def _read_csrf_cookie(self, req, resp): """ Return the CSRF cookie as a string, or False if no cookie is present. """ raise NotImplementedError("This method must be implemented by a subclass.") def _get_cookies_set(self, req, resp): """ Return a list of the cookie values passed to set_cookie() over the course of the request-response. """ raise NotImplementedError("This method must be implemented by a subclass.") def _get_request(self, method=None, cookie=None, request_class=None): if method is None: method = "GET" if request_class is None: request_class = TestingHttpRequest req = request_class() req.method = method if cookie is not None: self._set_csrf_cookie(req, cookie) return req def _get_csrf_cookie_request( self, method=None, cookie=None, post_token=None, meta_token=None, token_header=None, request_class=None, ): """ The method argument defaults to "GET". The cookie argument defaults to this class's default test cookie. The post_token and meta_token arguments are included in the request's req.POST and req.META headers, respectively, when that argument is provided and non-None. The token_header argument is the header key to use for req.META, defaults to "HTTP_X_CSRFTOKEN". """ if cookie is None: cookie = self._csrf_id_cookie if token_header is None: token_header = "HTTP_X_CSRFTOKEN" req = self._get_request( method=method, cookie=cookie, request_class=request_class, ) if post_token is not None: req.POST["csrfmiddlewaretoken"] = post_token if meta_token is not None: req.META[token_header] = meta_token return req def _get_POST_csrf_cookie_request( self, cookie=None, post_token=None, meta_token=None, token_header=None, request_class=None, ): return self._get_csrf_cookie_request( method="POST", cookie=cookie, post_token=post_token, meta_token=meta_token, token_header=token_header, request_class=request_class, ) def _get_POST_request_with_token(self, cookie=None, request_class=None): """The cookie argument defaults to this class's default test cookie.""" return self._get_POST_csrf_cookie_request( cookie=cookie, post_token=self._csrf_id_token, request_class=request_class, ) # This method depends on _unmask_cipher_token() being correct. def _check_token_present(self, response, csrf_secret=None): if csrf_secret is None: csrf_secret = TEST_SECRET text = str(response.content, response.charset) match = re.search('name="csrfmiddlewaretoken" value="(.*?)"', text) self.assertTrue( match, f"Could not find a csrfmiddlewaretoken value in: {text}", ) csrf_token = match[1] self.assertMaskedSecretCorrect(csrf_token, csrf_secret) def test_process_response_get_token_not_used(self): """ If get_token() is not called, the view middleware does not add a cookie. """ # This is important to make pages cacheable. Pages which do call # get_token(), assuming they use the token, are not cacheable because # the token is specific to the user req = self._get_request() # non_token_view_using_request_processor does not call get_token(), but # does use the csrf request processor. By using this, we are testing # that the view processor is properly lazy and doesn't call get_token() # until needed. mw = CsrfViewMiddleware(non_token_view_using_request_processor) mw.process_request(req) mw.process_view(req, non_token_view_using_request_processor, (), {}) resp = mw(req) csrf_cookie = self._read_csrf_cookie(req, resp) self.assertIs(csrf_cookie, False) def _check_bad_or_missing_cookie(self, cookie, expected): """Passing None for cookie includes no cookie.""" req = self._get_request(method="POST", cookie=cookie) mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) with self.assertLogs("django.security.csrf", "WARNING") as cm: resp = mw.process_view(req, post_form_view, (), {}) self.assertForbiddenReason(resp, cm, expected) def test_no_csrf_cookie(self): """ If no CSRF cookies is present, the middleware rejects the incoming request. This will stop login CSRF. """ self._check_bad_or_missing_cookie(None, REASON_NO_CSRF_COOKIE) def _check_bad_or_missing_token( self, expected, post_token=None, meta_token=None, token_header=None, ): req = self._get_POST_csrf_cookie_request( post_token=post_token, meta_token=meta_token, token_header=token_header, ) mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) with self.assertLogs("django.security.csrf", "WARNING") as cm: resp = mw.process_view(req, post_form_view, (), {}) self.assertEqual(resp["Content-Type"], "text/html; charset=utf-8") self.assertForbiddenReason(resp, cm, expected) def test_csrf_cookie_bad_or_missing_token(self): """ If a CSRF cookie is present but the token is missing or invalid, the middleware rejects the incoming request. """ cases = [ (None, None, REASON_CSRF_TOKEN_MISSING), (16 * "a", None, "CSRF token from POST has incorrect length."), (64 * "*", None, "CSRF token from POST has invalid characters."), (64 * "a", None, "CSRF token from POST incorrect."), ( None, 16 * "a", "CSRF token from the 'X-Csrftoken' HTTP header has incorrect length.", ), ( None, 64 * "*", "CSRF token from the 'X-Csrftoken' HTTP header has invalid characters.", ), ( None, 64 * "a", "CSRF token from the 'X-Csrftoken' HTTP header incorrect.", ), ] for post_token, meta_token, expected in cases: with self.subTest(post_token=post_token, meta_token=meta_token): self._check_bad_or_missing_token( expected, post_token=post_token, meta_token=meta_token, ) @override_settings(CSRF_HEADER_NAME="HTTP_X_CSRFTOKEN_CUSTOMIZED") def test_csrf_cookie_bad_token_custom_header(self): """ If a CSRF cookie is present and an invalid token is passed via a custom CSRF_HEADER_NAME, the middleware rejects the incoming request. """ expected = ( "CSRF token from the 'X-Csrftoken-Customized' HTTP header has " "incorrect length." ) self._check_bad_or_missing_token( expected, meta_token=16 * "a", token_header="HTTP_X_CSRFTOKEN_CUSTOMIZED", ) def test_process_request_csrf_cookie_and_token(self): """ If both a cookie and a token is present, the middleware lets it through. """ req = self._get_POST_request_with_token() mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) def test_process_request_csrf_cookie_no_token_exempt_view(self): """ If a CSRF cookie is present and no token, but the csrf_exempt decorator has been applied to the view, the middleware lets it through """ req = self._get_POST_csrf_cookie_request() mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, csrf_exempt(post_form_view), (), {}) self.assertIsNone(resp) def test_csrf_token_in_header(self): """ The token may be passed in a header instead of in the form. """ req = self._get_POST_csrf_cookie_request(meta_token=self._csrf_id_token) mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) @override_settings(CSRF_HEADER_NAME="HTTP_X_CSRFTOKEN_CUSTOMIZED") def test_csrf_token_in_header_with_customized_name(self): """ settings.CSRF_HEADER_NAME can be used to customize the CSRF header name """ req = self._get_POST_csrf_cookie_request( meta_token=self._csrf_id_token, token_header="HTTP_X_CSRFTOKEN_CUSTOMIZED", ) mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) def test_put_and_delete_rejected(self): """ HTTP PUT and DELETE methods have protection """ req = self._get_request(method="PUT") mw = CsrfViewMiddleware(post_form_view) with self.assertLogs("django.security.csrf", "WARNING") as cm: resp = mw.process_view(req, post_form_view, (), {}) self.assertForbiddenReason(resp, cm, REASON_NO_CSRF_COOKIE) req = self._get_request(method="DELETE") with self.assertLogs("django.security.csrf", "WARNING") as cm: resp = mw.process_view(req, post_form_view, (), {}) self.assertForbiddenReason(resp, cm, REASON_NO_CSRF_COOKIE) def test_put_and_delete_allowed(self): """ HTTP PUT and DELETE can get through with X-CSRFToken and a cookie. """ req = self._get_csrf_cookie_request( method="PUT", meta_token=self._csrf_id_token ) mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) req = self._get_csrf_cookie_request( method="DELETE", meta_token=self._csrf_id_token ) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) def test_rotate_token_triggers_second_reset(self): """ If rotate_token() is called after the token is reset in CsrfViewMiddleware's process_response() and before another call to the same process_response(), the cookie is reset a second time. """ req = self._get_POST_request_with_token() resp = sandwiched_rotate_token_view(req) self.assertContains(resp, "OK") actual_secret = self._read_csrf_cookie(req, resp) # set_cookie() was called a second time with a different secret. cookies_set = self._get_cookies_set(req, resp) # Only compare the last two to exclude a spurious entry that's present # when CsrfViewMiddlewareUseSessionsTests is running. self.assertEqual(cookies_set[-2:], [TEST_SECRET, actual_secret]) self.assertNotEqual(actual_secret, TEST_SECRET) # Tests for the template tag method def test_token_node_no_csrf_cookie(self): """ CsrfTokenNode works when no CSRF cookie is set. """ req = self._get_request() resp = token_view(req) token = get_token(req) self.assertIsNotNone(token) csrf_secret = _unmask_cipher_token(token) self._check_token_present(resp, csrf_secret) def test_token_node_empty_csrf_cookie(self): """ A new token is sent if the csrf_cookie is the empty string. """ req = self._get_request(cookie="") mw = CsrfViewMiddleware(token_view) mw.process_view(req, token_view, (), {}) resp = token_view(req) token = get_token(req) self.assertIsNotNone(token) csrf_secret = _unmask_cipher_token(token) self._check_token_present(resp, csrf_secret) def test_token_node_with_csrf_cookie(self): """ CsrfTokenNode works when a CSRF cookie is set. """ req = self._get_csrf_cookie_request() mw = CsrfViewMiddleware(token_view) mw.process_request(req) mw.process_view(req, token_view, (), {}) resp = token_view(req) self._check_token_present(resp) def test_get_token_for_exempt_view(self): """ get_token still works for a view decorated with 'csrf_exempt'. """ req = self._get_csrf_cookie_request() mw = CsrfViewMiddleware(token_view) mw.process_request(req) mw.process_view(req, csrf_exempt(token_view), (), {}) resp = token_view(req) self._check_token_present(resp) def test_get_token_for_requires_csrf_token_view(self): """ get_token() works for a view decorated solely with requires_csrf_token. """ req = self._get_csrf_cookie_request() resp = requires_csrf_token(token_view)(req) self._check_token_present(resp) def test_token_node_with_new_csrf_cookie(self): """ CsrfTokenNode works when a CSRF cookie is created by the middleware (when one was not already present) """ req = self._get_request() mw = CsrfViewMiddleware(token_view) mw.process_view(req, token_view, (), {}) resp = mw(req) csrf_cookie = self._read_csrf_cookie(req, resp) self._check_token_present(resp, csrf_cookie) def test_cookie_not_reset_on_accepted_request(self): """ The csrf token used in posts is changed on every request (although stays equivalent). The csrf cookie should not change on accepted requests. If it appears in the response, it should keep its value. """ req = self._get_POST_request_with_token() mw = CsrfViewMiddleware(token_view) mw.process_request(req) mw.process_view(req, token_view, (), {}) resp = mw(req) csrf_cookie = self._read_csrf_cookie(req, resp) self.assertEqual( csrf_cookie, TEST_SECRET, "CSRF cookie was changed on an accepted request", ) @override_settings(DEBUG=True, ALLOWED_HOSTS=["www.example.com"]) def test_https_bad_referer(self): """ A POST HTTPS request with a bad referer is rejected """ req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_REFERER"] = "https://www.evil.org/somepage" req.META["SERVER_PORT"] = "443" mw = CsrfViewMiddleware(post_form_view) response = mw.process_view(req, post_form_view, (), {}) self.assertContains( response, "Referer checking failed - https://www.evil.org/somepage does not " "match any trusted origins.", status_code=403, ) def _check_referer_rejects(self, mw, req): with self.assertRaises(RejectRequest): mw._check_referer(req) @override_settings(DEBUG=True) def test_https_no_referer(self): """A POST HTTPS request with a missing referer is rejected.""" req = self._get_POST_request_with_token() req._is_secure_override = True mw = CsrfViewMiddleware(post_form_view) self._check_referer_rejects(mw, req) response = mw.process_view(req, post_form_view, (), {}) self.assertContains( response, "Referer checking failed - no Referer.", status_code=403, ) def test_https_malformed_host(self): """ CsrfViewMiddleware generates a 403 response if it receives an HTTPS request with a bad host. """ req = self._get_request(method="POST") req._is_secure_override = True req.META["HTTP_HOST"] = "@malformed" req.META["HTTP_REFERER"] = "https://www.evil.org/somepage" req.META["SERVER_PORT"] = "443" mw = CsrfViewMiddleware(token_view) expected = ( "Referer checking failed - https://www.evil.org/somepage does not " "match any trusted origins." ) with self.assertRaisesMessage(RejectRequest, expected): mw._check_referer(req) response = mw.process_view(req, token_view, (), {}) self.assertEqual(response.status_code, 403) def test_origin_malformed_host(self): req = self._get_request(method="POST") req._is_secure_override = True req.META["HTTP_HOST"] = "@malformed" req.META["HTTP_ORIGIN"] = "https://www.evil.org" mw = CsrfViewMiddleware(token_view) self._check_referer_rejects(mw, req) response = mw.process_view(req, token_view, (), {}) self.assertEqual(response.status_code, 403) @override_settings(DEBUG=True) def test_https_malformed_referer(self): """ A POST HTTPS request with a bad referer is rejected. """ malformed_referer_msg = "Referer checking failed - Referer is malformed." req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_REFERER"] = "http://http://www.example.com/" mw = CsrfViewMiddleware(post_form_view) self._check_referer_rejects(mw, req) response = mw.process_view(req, post_form_view, (), {}) self.assertContains( response, "Referer checking failed - Referer is insecure while host is secure.", status_code=403, ) # Empty req.META["HTTP_REFERER"] = "" self._check_referer_rejects(mw, req) response = mw.process_view(req, post_form_view, (), {}) self.assertContains(response, malformed_referer_msg, status_code=403) # Non-ASCII req.META["HTTP_REFERER"] = "ØBöIß" self._check_referer_rejects(mw, req) response = mw.process_view(req, post_form_view, (), {}) self.assertContains(response, malformed_referer_msg, status_code=403) # missing scheme # >>> urlsplit('//example.com/') # SplitResult(scheme='', netloc='example.com', path='/', query='', # fragment='') req.META["HTTP_REFERER"] = "//example.com/" self._check_referer_rejects(mw, req) response = mw.process_view(req, post_form_view, (), {}) self.assertContains(response, malformed_referer_msg, status_code=403) # missing netloc # >>> urlsplit('https://') # SplitResult(scheme='https', netloc='', path='', query='', # fragment='') req.META["HTTP_REFERER"] = "https://" self._check_referer_rejects(mw, req) response = mw.process_view(req, post_form_view, (), {}) self.assertContains(response, malformed_referer_msg, status_code=403) # Invalid URL # >>> urlsplit('https://[') # ValueError: Invalid IPv6 URL req.META["HTTP_REFERER"] = "https://[" self._check_referer_rejects(mw, req) response = mw.process_view(req, post_form_view, (), {}) self.assertContains(response, malformed_referer_msg, status_code=403) @override_settings(ALLOWED_HOSTS=["www.example.com"]) def test_https_good_referer(self): """ A POST HTTPS request with a good referer is accepted. """ req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_REFERER"] = "https://www.example.com/somepage" mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) @override_settings(ALLOWED_HOSTS=["www.example.com"]) def test_https_good_referer_2(self): """ A POST HTTPS request with a good referer is accepted where the referer contains no trailing slash. """ # See ticket #15617 req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_REFERER"] = "https://www.example.com" mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) def _test_https_good_referer_behind_proxy(self): req = self._get_POST_request_with_token() req._is_secure_override = True req.META.update( { "HTTP_HOST": "10.0.0.2", "HTTP_REFERER": "https://www.example.com/somepage", "SERVER_PORT": "8080", "HTTP_X_FORWARDED_HOST": "www.example.com", "HTTP_X_FORWARDED_PORT": "443", } ) mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) @override_settings(CSRF_TRUSTED_ORIGINS=["https://dashboard.example.com"]) def test_https_good_referer_malformed_host(self): """ A POST HTTPS request is accepted if it receives a good referer with a bad host. """ req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "@malformed" req.META["HTTP_REFERER"] = "https://dashboard.example.com/somepage" mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) @override_settings( ALLOWED_HOSTS=["www.example.com"], CSRF_TRUSTED_ORIGINS=["https://dashboard.example.com"], ) def test_https_csrf_trusted_origin_allowed(self): """ A POST HTTPS request with a referer added to the CSRF_TRUSTED_ORIGINS setting is accepted. """ req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_REFERER"] = "https://dashboard.example.com" mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) @override_settings( ALLOWED_HOSTS=["www.example.com"], CSRF_TRUSTED_ORIGINS=["https://*.example.com"], ) def test_https_csrf_wildcard_trusted_origin_allowed(self): """ A POST HTTPS request with a referer that matches a CSRF_TRUSTED_ORIGINS wildcard is accepted. """ req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_REFERER"] = "https://dashboard.example.com" mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) response = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(response) def _test_https_good_referer_matches_cookie_domain(self): req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_REFERER"] = "https://foo.example.com/" req.META["SERVER_PORT"] = "443" mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) response = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(response) def _test_https_good_referer_matches_cookie_domain_with_different_port(self): req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_REFERER"] = "https://foo.example.com:4443/"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/m2m_multiple/models.py
tests/m2m_multiple/models.py
""" Multiple many-to-many relationships between the same two tables In this example, an ``Article`` can have many "primary" ``Category`` objects and many "secondary" ``Category`` objects. Set ``related_name`` to designate what the reverse relationship is called. """ from django.db import models class Category(models.Model): name = models.CharField(max_length=20) class Meta: ordering = ("name",) def __str__(self): return self.name class Article(models.Model): headline = models.CharField(max_length=50) pub_date = models.DateTimeField() primary_categories = models.ManyToManyField( Category, related_name="primary_article_set" ) secondary_categories = models.ManyToManyField( Category, related_name="secondary_article_set" ) class Meta: ordering = ("pub_date",) def __str__(self): return self.headline
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false