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/postgres_tests/migrations/0002_create_test_models.py
tests/postgres_tests/migrations/0002_create_test_models.py
from django.db import migrations, models from ..fields import ( ArrayField, BigIntegerRangeField, DateRangeField, DateTimeRangeField, DecimalRangeField, EnumField, HStoreField, IntegerRangeField, OffByOneField, SearchVectorField, ) from ..models import TagField class Migration(migrations.Migration): dependencies = [ ("postgres_tests", "0001_setup_extensions"), ] operations = [ migrations.CreateModel( name="CharArrayModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("field", ArrayField(models.CharField(max_length=10))), ], options={ "required_db_vendor": "postgresql", }, bases=(models.Model,), ), migrations.CreateModel( name="DateTimeArrayModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("datetimes", ArrayField(models.DateTimeField())), ("dates", ArrayField(models.DateField())), ("times", ArrayField(models.TimeField())), ], options={ "required_db_vendor": "postgresql", }, bases=(models.Model,), ), migrations.CreateModel( name="HStoreModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("field", HStoreField(blank=True, null=True)), ("array_field", ArrayField(HStoreField(), null=True)), ], options={ "required_db_vendor": "postgresql", }, bases=(models.Model,), ), migrations.CreateModel( name="OtherTypesArrayModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "ips", ArrayField(models.GenericIPAddressField(), default=list), ), ("uuids", ArrayField(models.UUIDField(), default=list)), ( "decimals", ArrayField( models.DecimalField(max_digits=5, decimal_places=2), default=list, ), ), ("tags", ArrayField(TagField(), blank=True, null=True)), ( "json", ArrayField(models.JSONField(default=dict), default=list), ), ("int_ranges", ArrayField(IntegerRangeField(), null=True, blank=True)), ( "bigint_ranges", ArrayField(BigIntegerRangeField(), null=True, blank=True), ), ], options={ "required_db_vendor": "postgresql", }, bases=(models.Model,), ), migrations.CreateModel( name="IntegerArrayModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "field", ArrayField(models.BigIntegerField(), blank=True, default=list), ), ], options={ "required_db_vendor": "postgresql", }, bases=(models.Model,), ), migrations.CreateModel( name="NestedIntegerArrayModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "field", ArrayField(ArrayField(models.IntegerField())), ), ], options={ "required_db_vendor": "postgresql", }, bases=(models.Model,), ), migrations.CreateModel( name="WithSizeArrayModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "field", ArrayField(models.FloatField(), size=2, null=True, blank=True), ), ], options={ "required_db_vendor": "postgresql", }, bases=(models.Model,), ), migrations.CreateModel( name="NullableIntegerArrayModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "field", ArrayField(models.BigIntegerField(), null=True, blank=True), ), ( "field_nested", ArrayField( ArrayField(models.BigIntegerField(null=True)), null=True ), ), ("order", models.IntegerField(null=True)), ], options={ "required_db_vendor": "postgresql", }, bases=(models.Model,), ), migrations.CreateModel( name="CharFieldModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("field", models.CharField(max_length=64)), ], options=None, bases=None, ), migrations.CreateModel( name="TextFieldModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("field", models.TextField()), ], options=None, bases=None, ), migrations.CreateModel( name="SmallAutoFieldModel", fields=[ ( "id", models.SmallAutoField(serialize=False, primary_key=True), ), ], options=None, ), migrations.CreateModel( name="BigAutoFieldModel", fields=[ ( "id", models.BigAutoField(serialize=False, primary_key=True), ), ], options=None, ), migrations.CreateModel( name="Scene", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("scene", models.TextField()), ("setting", models.CharField(max_length=255)), ], options=None, bases=None, ), migrations.CreateModel( name="Character", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("name", models.CharField(max_length=255)), ], options=None, bases=None, ), migrations.CreateModel( name="Line", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "scene", models.ForeignKey("postgres_tests.Scene", on_delete=models.CASCADE), ), ( "character", models.ForeignKey( "postgres_tests.Character", on_delete=models.CASCADE ), ), ("dialogue", models.TextField(blank=True, null=True)), ("dialogue_search_vector", SearchVectorField(blank=True, null=True)), ( "dialogue_config", models.CharField(max_length=100, blank=True, null=True), ), ], options={ "required_db_vendor": "postgresql", }, bases=None, ), migrations.CreateModel( name="LineSavedSearch", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "line", models.ForeignKey("postgres_tests.Line", on_delete=models.CASCADE), ), ("query", models.CharField(max_length=100)), ], options={ "required_db_vendor": "postgresql", }, ), migrations.CreateModel( name="AggregateTestModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("boolean_field", models.BooleanField(null=True)), ("char_field", models.CharField(max_length=30, blank=True)), ("text_field", models.TextField(blank=True)), ("integer_field", models.IntegerField(null=True)), ("json_field", models.JSONField(null=True)), ], options={ "required_db_vendor": "postgresql", }, ), migrations.CreateModel( name="StatTestModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("int1", models.IntegerField()), ("int2", models.IntegerField()), ( "related_field", models.ForeignKey( "postgres_tests.AggregateTestModel", models.SET_NULL, null=True, ), ), ], options={ "required_db_vendor": "postgresql", }, ), migrations.CreateModel( name="NowTestModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("when", models.DateTimeField(null=True, default=None)), ], ), migrations.CreateModel( name="UUIDTestModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("uuid", models.UUIDField(default=None, null=True)), ], ), migrations.CreateModel( name="RangesModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("ints", IntegerRangeField(null=True, blank=True, db_default=(5, 10))), ("bigints", BigIntegerRangeField(null=True, blank=True)), ("decimals", DecimalRangeField(null=True, blank=True)), ("timestamps", DateTimeRangeField(null=True, blank=True)), ("timestamps_inner", DateTimeRangeField(null=True, blank=True)), ( "timestamps_closed_bounds", DateTimeRangeField(null=True, blank=True, default_bounds="[]"), ), ("dates", DateRangeField(null=True, blank=True)), ("dates_inner", DateRangeField(null=True, blank=True)), ], options={"required_db_vendor": "postgresql"}, bases=(models.Model,), ), migrations.CreateModel( name="RangeLookupsModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "parent", models.ForeignKey( "postgres_tests.RangesModel", models.SET_NULL, blank=True, null=True, ), ), ("integer", models.IntegerField(blank=True, null=True)), ("big_integer", models.BigIntegerField(blank=True, null=True)), ("float", models.FloatField(blank=True, null=True)), ("timestamp", models.DateTimeField(blank=True, null=True)), ("date", models.DateField(blank=True, null=True)), ("small_integer", models.SmallIntegerField(blank=True, null=True)), ( "decimal_field", models.DecimalField( max_digits=5, decimal_places=2, blank=True, null=True ), ), ], options={ "required_db_vendor": "postgresql", }, bases=(models.Model,), ), migrations.CreateModel( name="ArrayEnumModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "array_of_enums", ArrayField(EnumField(max_length=20)), ), ], options={ "required_db_vendor": "postgresql", }, bases=(models.Model,), ), migrations.CreateModel( name="Room", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("number", models.IntegerField(unique=True)), ], ), migrations.CreateModel( name="HotelReservation", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("room", models.ForeignKey("postgres_tests.Room", models.CASCADE)), ("datespan", DateRangeField()), ("start", models.DateTimeField()), ("end", models.DateTimeField()), ("cancelled", models.BooleanField(default=False)), ("requirements", models.JSONField(blank=True, null=True)), ], options={ "required_db_vendor": "postgresql", }, ), migrations.CreateModel( name="OffByOneModel", fields=[ ( "id", models.BigAutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "one_off", OffByOneField(), ), ], options={ "required_db_vendor": "postgresql", }, bases=(models.Model,), ), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_widgets/test_autocomplete_widget.py
tests/admin_widgets/test_autocomplete_widget.py
from django import forms from django.contrib import admin from django.contrib.admin.widgets import AutocompleteSelect from django.forms import ModelChoiceField from django.test import TestCase, override_settings from django.utils import translation from .models import Album, Band, ReleaseEvent, VideoStream class AlbumForm(forms.ModelForm): class Meta: model = Album fields = ["band", "featuring"] widgets = { "band": AutocompleteSelect( Album._meta.get_field("band"), admin.site, attrs={"class": "my-class"}, ), "featuring": AutocompleteSelect( Album._meta.get_field("featuring"), admin.site, ), } class NotRequiredBandForm(forms.Form): band = ModelChoiceField( queryset=Album.objects.all(), widget=AutocompleteSelect( Album._meta.get_field("band").remote_field, admin.site ), required=False, ) class RequiredBandForm(forms.Form): band = ModelChoiceField( queryset=Album.objects.all(), widget=AutocompleteSelect( Album._meta.get_field("band").remote_field, admin.site ), required=True, ) class VideoStreamForm(forms.ModelForm): class Meta: model = VideoStream fields = ["release_event"] widgets = { "release_event": AutocompleteSelect( VideoStream._meta.get_field("release_event"), admin.site, ), } @override_settings(ROOT_URLCONF="admin_widgets.urls") class AutocompleteMixinTests(TestCase): empty_option = '<option value=""></option>' maxDiff = 1000 def test_build_attrs(self): form = AlbumForm() attrs = form["band"].field.widget.get_context( name="my_field", value=None, attrs={} )["widget"]["attrs"] self.assertEqual( attrs, { "class": "my-class admin-autocomplete", "data-ajax--cache": "true", "data-ajax--delay": 250, "data-ajax--type": "GET", "data-ajax--url": "/autocomplete/", "data-theme": "admin-autocomplete", "data-allow-clear": "false", "data-app-label": "admin_widgets", "data-field-name": "band", "data-model-name": "album", "data-placeholder": "", "lang": "en", }, ) def test_build_attrs_no_custom_class(self): form = AlbumForm() attrs = form["featuring"].field.widget.get_context( name="name", value=None, attrs={} )["widget"]["attrs"] self.assertEqual(attrs["class"], "admin-autocomplete") def test_build_attrs_not_required_field(self): form = NotRequiredBandForm() attrs = form["band"].field.widget.build_attrs({}) self.assertJSONEqual(attrs["data-allow-clear"], True) def test_build_attrs_required_field(self): form = RequiredBandForm() attrs = form["band"].field.widget.build_attrs({}) self.assertJSONEqual(attrs["data-allow-clear"], False) def test_get_url(self): rel = Album._meta.get_field("band") w = AutocompleteSelect(rel, admin.site) url = w.get_url() self.assertEqual(url, "/autocomplete/") def test_render_options(self): beatles = Band.objects.create(name="The Beatles", style="rock") who = Band.objects.create(name="The Who", style="rock") # With 'band', a ForeignKey. form = AlbumForm(initial={"band": beatles.uuid}) output = form.as_table() selected_option = ( '<option value="%s" selected>The Beatles</option>' % beatles.uuid ) option = '<option value="%s">The Who</option>' % who.uuid self.assertIn(selected_option, output) self.assertNotIn(option, output) # With 'featuring', a ManyToManyField. form = AlbumForm(initial={"featuring": [beatles.pk, who.pk]}) output = form.as_table() selected_option = ( '<option value="%s" selected>The Beatles</option>' % beatles.pk ) option = '<option value="%s" selected>The Who</option>' % who.pk self.assertIn(selected_option, output) self.assertIn(option, output) def test_render_options_required_field(self): """Empty option is present if the field isn't required.""" form = NotRequiredBandForm() output = form.as_table() self.assertIn(self.empty_option, output) def test_render_options_not_required_field(self): """Empty option isn't present if the field isn't required.""" form = RequiredBandForm() output = form.as_table() self.assertNotIn(self.empty_option, output) def test_render_options_fk_as_pk(self): beatles = Band.objects.create(name="The Beatles", style="rock") rubber_soul = Album.objects.create(name="Rubber Soul", band=beatles) release_event = ReleaseEvent.objects.create( name="Test Target", album=rubber_soul ) form = VideoStreamForm(initial={"release_event": release_event.pk}) output = form.as_table() selected_option = ( '<option value="%s" selected>Test Target</option>' % release_event.pk ) self.assertIn(selected_option, output) def test_media(self): rel = Album._meta.get_field("band").remote_field base_files = ( "admin/js/vendor/jquery/jquery.min.js", "admin/js/vendor/select2/select2.full.min.js", # Language file is inserted here. "admin/js/jquery.init.js", "admin/js/autocomplete.js", ) languages = ( ("de", "de"), # Subsequent language codes are used when the language code is not # supported. ("de-at", "de"), ("de-ch-1901", "de"), ("en-latn-us", "en"), ("nl-nl-x-informal", "nl"), ("zh-hans-HK", "zh-CN"), # Language with code 00 does not exist. ("00", None), # Language files are case sensitive. ("sr-cyrl", "sr-Cyrl"), ("zh-hans", "zh-CN"), ("zh-hant", "zh-TW"), (None, None), ) for lang, select_lang in languages: with self.subTest(lang=lang): if select_lang: expected_files = ( base_files[:2] + (("admin/js/vendor/select2/i18n/%s.js" % select_lang),) + base_files[2:] ) else: expected_files = base_files with translation.override(lang): self.assertEqual( AutocompleteSelect(rel, admin.site).media._js, list(expected_files), )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_widgets/models.py
tests/admin_widgets/models.py
import tempfile import uuid from django.contrib.auth.models import User from django.core.files.storage import FileSystemStorage from django.db import models try: from PIL import Image except ImportError: Image = None else: temp_storage_dir = tempfile.mkdtemp() temp_storage = FileSystemStorage(temp_storage_dir) class MyFileField(models.FileField): pass class Member(models.Model): name = models.CharField(max_length=100) birthdate = models.DateTimeField(blank=True, null=True) gender = models.CharField( max_length=1, blank=True, choices=[("M", "Male"), ("F", "Female")] ) email = models.EmailField(blank=True) def __str__(self): return self.name class Artist(models.Model): pass class Band(Artist): uuid = models.UUIDField(unique=True, default=uuid.uuid4) name = models.CharField(max_length=100) style = models.CharField(max_length=20) members = models.ManyToManyField(Member) def __str__(self): return self.name class UnsafeLimitChoicesTo(models.Model): band = models.ForeignKey( Band, models.CASCADE, limit_choices_to={"name": '"&><escapeme'}, ) class Album(models.Model): band = models.ForeignKey(Band, models.CASCADE, to_field="uuid") featuring = models.ManyToManyField(Band, related_name="featured") name = models.CharField(max_length=100) cover_art = models.FileField(upload_to="albums") backside_art = MyFileField(upload_to="albums_back", null=True) def __str__(self): return self.name class ReleaseEvent(models.Model): """ Used to check that autocomplete widget correctly resolves attname for FK as PK example. """ album = models.ForeignKey(Album, models.CASCADE, primary_key=True) name = models.CharField(max_length=100) class Meta: ordering = ["name"] def __str__(self): return self.name class VideoStream(models.Model): release_event = models.ForeignKey(ReleaseEvent, models.CASCADE) class HiddenInventoryManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(hidden=False) class Inventory(models.Model): barcode = models.PositiveIntegerField(unique=True) parent = models.ForeignKey( "self", models.SET_NULL, to_field="barcode", blank=True, null=True ) name = models.CharField(blank=False, max_length=20) hidden = models.BooleanField(default=False) # see #9258 default_manager = models.Manager() objects = HiddenInventoryManager() def __str__(self): return self.name class Event(models.Model): main_band = models.ForeignKey( Band, models.CASCADE, limit_choices_to=models.Q(pk__gt=0), related_name="events_main_band_at", ) supporting_bands = models.ManyToManyField( Band, blank=True, related_name="events_supporting_band_at", help_text="Supporting Bands.", ) start_date = models.DateField(blank=True, null=True) start_time = models.TimeField(blank=True, null=True) description = models.TextField(blank=True) link = models.URLField(blank=True) min_age = models.IntegerField(blank=True, null=True) class Car(models.Model): owner = models.ForeignKey(User, models.CASCADE) make = models.CharField(max_length=30) model = models.CharField(max_length=30) def __str__(self): return "%s %s" % (self.make, self.model) class CarTire(models.Model): """ A single car tire. This to test that a user can only select their own cars. """ car = models.ForeignKey(Car, models.CASCADE) class Honeycomb(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) location = models.CharField(max_length=20) class Bee(models.Model): """ A model with a FK to a model that won't be registered with the admin (Honeycomb) so the corresponding raw ID widget won't have a magnifying glass link to select related honeycomb instances. """ honeycomb = models.ForeignKey(Honeycomb, models.CASCADE) class Individual(models.Model): """ A model with a FK to itself. It won't be registered with the admin, so the corresponding raw ID widget won't have a magnifying glass link to select related instances (rendering will be called programmatically in this case). """ name = models.CharField(max_length=20) parent = models.ForeignKey("self", models.SET_NULL, null=True) soulmate = models.ForeignKey( "self", models.CASCADE, null=True, related_name="soulmates" ) class Company(models.Model): name = models.CharField(max_length=20) class Advisor(models.Model): """ A model with a m2m to a model that won't be registered with the admin (Company) so the corresponding raw ID widget won't have a magnifying glass link to select related company instances. """ name = models.CharField(max_length=20) companies = models.ManyToManyField(Company) class Student(models.Model): name = models.CharField(max_length=255) if Image: photo = models.ImageField( storage=temp_storage, upload_to="photos", blank=True, null=True ) class Meta: ordering = ("name",) def __str__(self): return self.name class School(models.Model): name = models.CharField(max_length=255) students = models.ManyToManyField(Student, related_name="current_schools") alumni = models.ManyToManyField(Student, related_name="previous_schools") def __str__(self): return self.name class Profile(models.Model): user = models.ForeignKey("auth.User", models.CASCADE, to_field="username") def __str__(self): return self.user.username
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_widgets/__init__.py
tests/admin_widgets/__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_widgets/tests.py
tests/admin_widgets/tests.py
import gettext import os import re import zoneinfo from datetime import datetime, timedelta from importlib import import_module from pathlib import Path from unittest import skipUnless from django import forms from django.conf import settings from django.contrib import admin from django.contrib.admin import widgets from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.auth.models import User from django.core.files.storage import default_storage from django.core.files.uploadedfile import SimpleUploadedFile from django.db.models import ( CharField, DateField, DateTimeField, ForeignKey, ManyToManyField, UUIDField, ) from django.test import SimpleTestCase, TestCase, override_settings from django.test.selenium import screenshot_cases from django.test.utils import requires_tz_support from django.urls import reverse from django.utils import translation from .models import ( Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Image, Individual, Inventory, Member, MyFileField, Profile, ReleaseEvent, School, Student, UnsafeLimitChoicesTo, VideoStream, ) from .widgetadmin import site as widget_admin_site class TestDataMixin: @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email=None ) cls.u2 = User.objects.create_user(username="testser", password="secret") Car.objects.create(owner=cls.superuser, make="Volkswagen", model="Passat") Car.objects.create(owner=cls.u2, make="BMW", model="M3") class AdminFormfieldForDBFieldTests(SimpleTestCase): """ Tests for correct behavior of ModelAdmin.formfield_for_dbfield """ def assertFormfield(self, model, fieldname, widgetclass, **admin_overrides): """ Helper to call formfield_for_dbfield for a given model and field name and verify that the returned formfield is appropriate. """ # Override any settings on the model admin class MyModelAdmin(admin.ModelAdmin): pass for k in admin_overrides: setattr(MyModelAdmin, k, admin_overrides[k]) # Construct the admin, and ask it for a formfield ma = MyModelAdmin(model, admin.site) ff = ma.formfield_for_dbfield(model._meta.get_field(fieldname), request=None) # "unwrap" the widget wrapper, if needed if isinstance(ff.widget, widgets.RelatedFieldWidgetWrapper): widget = ff.widget.widget else: widget = ff.widget self.assertIsInstance(widget, widgetclass) # Return the formfield so that other tests can continue return ff def test_DateField(self): self.assertFormfield(Event, "start_date", widgets.AdminDateWidget) def test_DateTimeField(self): self.assertFormfield(Member, "birthdate", widgets.AdminSplitDateTime) def test_TimeField(self): self.assertFormfield(Event, "start_time", widgets.AdminTimeWidget) def test_TextField(self): self.assertFormfield(Event, "description", widgets.AdminTextareaWidget) def test_URLField(self): self.assertFormfield(Event, "link", widgets.AdminURLFieldWidget) def test_IntegerField(self): self.assertFormfield(Event, "min_age", widgets.AdminIntegerFieldWidget) def test_CharField(self): self.assertFormfield(Member, "name", widgets.AdminTextInputWidget) def test_EmailField(self): self.assertFormfield(Member, "email", widgets.AdminEmailInputWidget) def test_FileField(self): self.assertFormfield(Album, "cover_art", widgets.AdminFileWidget) def test_ForeignKey(self): self.assertFormfield(Event, "main_band", forms.Select) def test_raw_id_ForeignKey(self): self.assertFormfield( Event, "main_band", widgets.ForeignKeyRawIdWidget, raw_id_fields=["main_band"], ) def test_radio_fields_ForeignKey(self): ff = self.assertFormfield( Event, "main_band", widgets.AdminRadioSelect, radio_fields={"main_band": admin.VERTICAL}, ) self.assertIsNone(ff.empty_label) def test_radio_fields_foreignkey_formfield_overrides_empty_label(self): class MyModelAdmin(admin.ModelAdmin): radio_fields = {"parent": admin.VERTICAL} formfield_overrides = { ForeignKey: {"empty_label": "Custom empty label"}, } ma = MyModelAdmin(Inventory, admin.site) ff = ma.formfield_for_dbfield(Inventory._meta.get_field("parent"), request=None) self.assertEqual(ff.empty_label, "Custom empty label") def test_many_to_many(self): self.assertFormfield(Band, "members", forms.SelectMultiple) def test_raw_id_many_to_many(self): self.assertFormfield( Band, "members", widgets.ManyToManyRawIdWidget, raw_id_fields=["members"] ) def test_filtered_many_to_many(self): self.assertFormfield( Band, "members", widgets.FilteredSelectMultiple, filter_vertical=["members"] ) def test_formfield_overrides(self): self.assertFormfield( Event, "start_date", forms.TextInput, formfield_overrides={DateField: {"widget": forms.TextInput}}, ) def test_formfield_overrides_widget_instances(self): """ Widget instances in formfield_overrides are not shared between different fields. (#19423) """ class BandAdmin(admin.ModelAdmin): formfield_overrides = { CharField: {"widget": forms.TextInput(attrs={"size": "10"})} } ma = BandAdmin(Band, admin.site) f1 = ma.formfield_for_dbfield(Band._meta.get_field("name"), request=None) f2 = ma.formfield_for_dbfield(Band._meta.get_field("style"), request=None) self.assertNotEqual(f1.widget, f2.widget) self.assertEqual(f1.widget.attrs["maxlength"], "100") self.assertEqual(f2.widget.attrs["maxlength"], "20") self.assertEqual(f2.widget.attrs["size"], "10") def test_formfield_overrides_m2m_filter_widget(self): """ The autocomplete_fields, raw_id_fields, filter_vertical, and filter_horizontal widgets for ManyToManyFields may be overridden by specifying a widget in formfield_overrides. """ class BandAdmin(admin.ModelAdmin): filter_vertical = ["members"] formfield_overrides = { ManyToManyField: {"widget": forms.CheckboxSelectMultiple}, } ma = BandAdmin(Band, admin.site) field = ma.formfield_for_dbfield(Band._meta.get_field("members"), request=None) self.assertIsInstance(field.widget.widget, forms.CheckboxSelectMultiple) def test_formfield_overrides_for_datetime_field(self): """ Overriding the widget for DateTimeField doesn't overrides the default form_class for that field (#26449). """ class MemberAdmin(admin.ModelAdmin): formfield_overrides = { DateTimeField: {"widget": widgets.AdminSplitDateTime} } ma = MemberAdmin(Member, admin.site) f1 = ma.formfield_for_dbfield(Member._meta.get_field("birthdate"), request=None) self.assertIsInstance(f1.widget, widgets.AdminSplitDateTime) self.assertIsInstance(f1, forms.SplitDateTimeField) def test_formfield_overrides_for_custom_field(self): """ formfield_overrides works for a custom field class. """ class AlbumAdmin(admin.ModelAdmin): formfield_overrides = {MyFileField: {"widget": forms.TextInput()}} ma = AlbumAdmin(Member, admin.site) f1 = ma.formfield_for_dbfield( Album._meta.get_field("backside_art"), request=None ) self.assertIsInstance(f1.widget, forms.TextInput) def test_field_with_choices(self): self.assertFormfield(Member, "gender", forms.Select) def test_choices_with_radio_fields(self): self.assertFormfield( Member, "gender", widgets.AdminRadioSelect, radio_fields={"gender": admin.VERTICAL}, ) def test_inheritance(self): self.assertFormfield(Album, "backside_art", widgets.AdminFileWidget) def test_m2m_widgets(self): """m2m fields help text as it applies to admin app (#9321).""" class AdvisorAdmin(admin.ModelAdmin): filter_vertical = ["companies"] self.assertFormfield( Advisor, "companies", widgets.FilteredSelectMultiple, filter_vertical=["companies"], ) ma = AdvisorAdmin(Advisor, admin.site) f = ma.formfield_for_dbfield(Advisor._meta.get_field("companies"), request=None) self.assertEqual( f.help_text, "Hold down “Control”, or “Command” on a Mac, to select more than one.", ) def test_m2m_widgets_no_allow_multiple_selected(self): class NoAllowMultipleSelectedWidget(forms.SelectMultiple): allow_multiple_selected = False class AdvisorAdmin(admin.ModelAdmin): filter_vertical = ["companies"] formfield_overrides = { ManyToManyField: {"widget": NoAllowMultipleSelectedWidget}, } self.assertFormfield( Advisor, "companies", widgets.FilteredSelectMultiple, filter_vertical=["companies"], ) ma = AdvisorAdmin(Advisor, admin.site) f = ma.formfield_for_dbfield(Advisor._meta.get_field("companies"), request=None) self.assertEqual(f.help_text, "") @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminFormfieldForDBFieldWithRequestTests(TestDataMixin, TestCase): def test_filter_choices_by_request_user(self): """ Ensure the user can only see their own cars in the foreign key dropdown. """ self.client.force_login(self.superuser) response = self.client.get(reverse("admin:admin_widgets_cartire_add")) self.assertNotContains(response, "BMW M3") self.assertContains(response, "Volkswagen Passat") @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminForeignKeyWidgetChangeList(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) def test_changelist_ForeignKey(self): response = self.client.get(reverse("admin:admin_widgets_car_changelist")) self.assertContains(response, "/auth/user/add/") @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminForeignKeyRawIdWidget(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) def test_nonexistent_target_id(self): band = Band.objects.create(name="Bogey Blues") pk = band.pk band.delete() post_data = { "main_band": str(pk), } # Try posting with a nonexistent pk in a raw id field: this # should result in an error message, not a server exception. response = self.client.post(reverse("admin:admin_widgets_event_add"), post_data) self.assertContains( response, "Select a valid choice. That choice is not one of the available choices.", ) def test_invalid_target_id(self): for test_str in ("Iñtërnâtiônàlizætiøn", "1234'", -1234): # This should result in an error message, not a server exception. response = self.client.post( reverse("admin:admin_widgets_event_add"), {"main_band": test_str} ) self.assertContains( response, "Select a valid choice. That choice is not one of the available " "choices.", ) def test_url_params_from_lookup_dict_any_iterable(self): lookup1 = widgets.url_params_from_lookup_dict({"color__in": ("red", "blue")}) lookup2 = widgets.url_params_from_lookup_dict({"color__in": ["red", "blue"]}) self.assertEqual(lookup1, {"color__in": "red,blue"}) self.assertEqual(lookup1, lookup2) def test_url_params_from_lookup_dict_callable(self): def my_callable(): return "works" lookup1 = widgets.url_params_from_lookup_dict({"myfield": my_callable}) lookup2 = widgets.url_params_from_lookup_dict({"myfield": my_callable()}) self.assertEqual(lookup1, lookup2) def test_label_and_url_for_value_invalid_uuid(self): field = Bee._meta.get_field("honeycomb") self.assertIsInstance(field.target_field, UUIDField) widget = widgets.ForeignKeyRawIdWidget(field.remote_field, admin.site) self.assertEqual(widget.label_and_url_for_value("invalid-uuid"), ("", "")) class FilteredSelectMultipleWidgetTest(SimpleTestCase): def test_render(self): # Backslash in verbose_name to ensure it is JavaScript escaped. w = widgets.FilteredSelectMultiple("test\\", False) self.assertHTMLEqual( w.render("test", "test"), '<select multiple name="test" class="selectfilter" ' 'data-field-name="test\\" data-is-stacked="0">\n</select>', ) def test_stacked_render(self): # Backslash in verbose_name to ensure it is JavaScript escaped. w = widgets.FilteredSelectMultiple("test\\", True) self.assertHTMLEqual( w.render("test", "test"), '<select multiple name="test" class="selectfilterstacked" ' 'data-field-name="test\\" data-is-stacked="1">\n</select>', ) class AdminDateWidgetTest(SimpleTestCase): def test_attrs(self): w = widgets.AdminDateWidget() self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<p class="date">' '<input aria-describedby="id_test_timezone_warning_helptext" ' 'value="2007-12-01" type="text" class="vDateField" name="test" ' 'size="10"></p>', ) # pass attrs to widget w = widgets.AdminDateWidget(attrs={"size": 20, "class": "myDateField"}) self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<p class="date">' '<input aria-describedby="id_test_timezone_warning_helptext" ' 'value="2007-12-01" type="text" class="myDateField" name="test" ' 'size="20"></p>', ) class AdminTimeWidgetTest(SimpleTestCase): def test_attrs(self): w = widgets.AdminTimeWidget() self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<p class="time">' '<input aria-describedby="id_test_timezone_warning_helptext" ' 'value="09:30:00" type="text" class="vTimeField" name="test" ' 'size="8"></p>', ) # pass attrs to widget w = widgets.AdminTimeWidget(attrs={"size": 20, "class": "myTimeField"}) self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<p class="time">' '<input aria-describedby="id_test_timezone_warning_helptext" ' 'value="09:30:00" type="text" class="myTimeField" name="test" ' 'size="20"></p>', ) class AdminSplitDateTimeWidgetTest(SimpleTestCase): def test_render(self): w = widgets.AdminSplitDateTime() self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30), attrs={"id": "id_test"}), '<p class="datetime">' '<label for="id_test_0">Date:</label> ' '<input aria-describedby="id_test_timezone_warning_helptext" ' 'value="2007-12-01" type="text" class="vDateField" ' 'name="test_0" size="10" id="id_test_0"><br>' '<label for="id_test_1">Time:</label> ' '<input aria-describedby="id_test_timezone_warning_helptext" ' 'value="09:30:00" type="text" class="vTimeField" ' 'name="test_1" size="8" id="id_test_1"></p>', ) def test_localization(self): w = widgets.AdminSplitDateTime() with translation.override("de-at"): w.is_localized = True self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30), attrs={"id": "id_test"}), '<p class="datetime">' '<label for="id_test_0">Datum:</label> ' '<input aria-describedby="id_test_timezone_warning_helptext" ' 'value="01.12.2007" type="text" ' 'class="vDateField" name="test_0" size="10" id="id_test_0"><br>' '<label for="id_test_1">Zeit:</label> ' '<input aria-describedby="id_test_timezone_warning_helptext" ' 'value="09:30:00" type="text" class="vTimeField" ' 'name="test_1" size="8" id="id_test_1"></p>', ) class AdminURLWidgetTest(SimpleTestCase): def test_get_context_validates_url(self): w = widgets.AdminURLFieldWidget() for invalid in [ "", "/not/a/full/url/", 'javascript:alert("Danger XSS!")', "http://" + "한.글." * 1_000_000 + "com", ]: with self.subTest(url=invalid): self.assertFalse(w.get_context("name", invalid, {})["url_valid"]) self.assertTrue(w.get_context("name", "http://example.com", {})["url_valid"]) def test_render(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( w.render("test", ""), '<input class="vURLField" name="test" type="url">' ) self.assertHTMLEqual( w.render("test", "http://example.com"), '<p class="url">Currently:<a href="http://example.com">' "http://example.com</a><br>" 'Change:<input class="vURLField" name="test" type="url" ' 'value="http://example.com"></p>', ) def test_render_idn(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( w.render("test", "http://example-äüö.com"), '<p class="url">Currently: <a href="http://example-%C3%A4%C3%BC%C3%B6.com">' "http://example-äüö.com</a><br>" 'Change:<input class="vURLField" name="test" type="url" ' 'value="http://example-äüö.com"></p>', ) # Does not use obsolete IDNA-2003 encoding (#36013). self.assertNotIn("fass.example.com", w.render("test", "http://faß.example.com")) def test_render_quoting(self): """ WARNING: This test doesn't use assertHTMLEqual since it will get rid of some escapes which are tested here! """ HREF_RE = re.compile('href="([^"]+)"') VALUE_RE = re.compile('value="([^"]+)"') TEXT_RE = re.compile("<a[^>]+>([^>]+)</a>") w = widgets.AdminURLFieldWidget() output = w.render("test", "http://example.com/<sometag>some-text</sometag>") self.assertEqual( HREF_RE.search(output)[1], "http://example.com/%3Csometag%3Esome-text%3C/sometag%3E", ) self.assertEqual( TEXT_RE.search(output)[1], "http://example.com/&lt;sometag&gt;some-text&lt;/sometag&gt;", ) self.assertEqual( VALUE_RE.search(output)[1], "http://example.com/&lt;sometag&gt;some-text&lt;/sometag&gt;", ) output = w.render("test", "http://example-äüö.com/<sometag>some-text</sometag>") self.assertEqual( HREF_RE.search(output)[1], "http://example-%C3%A4%C3%BC%C3%B6.com/" "%3Csometag%3Esome-text%3C/sometag%3E", ) self.assertEqual( TEXT_RE.search(output)[1], "http://example-äüö.com/&lt;sometag&gt;some-text&lt;/sometag&gt;", ) self.assertEqual( VALUE_RE.search(output)[1], "http://example-äüö.com/&lt;sometag&gt;some-text&lt;/sometag&gt;", ) output = w.render( "test", 'http://www.example.com/%C3%A4"><script>alert("XSS!")</script>"' ) self.assertEqual( HREF_RE.search(output)[1], "http://www.example.com/%C3%A4%22%3E%3Cscript%3Ealert(%22XSS!%22)" "%3C/script%3E%22", ) self.assertEqual( TEXT_RE.search(output)[1], "http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;" "alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;", ) self.assertEqual( VALUE_RE.search(output)[1], "http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;" "alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;", ) class AdminUUIDWidgetTests(SimpleTestCase): def test_attrs(self): w = widgets.AdminUUIDInputWidget() self.assertHTMLEqual( w.render("test", "550e8400-e29b-41d4-a716-446655440000"), '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" ' 'class="vUUIDField" name="test">', ) w = widgets.AdminUUIDInputWidget(attrs={"class": "myUUIDInput"}) self.assertHTMLEqual( w.render("test", "550e8400-e29b-41d4-a716-446655440000"), '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" ' 'class="myUUIDInput" name="test">', ) @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminFileWidgetTests(TestDataMixin, TestCase): @classmethod def setUpTestData(cls): super().setUpTestData() band = Band.objects.create(name="Linkin Park") cls.album = band.album_set.create( name="Hybrid Theory", cover_art=r"albums\hybrid_theory.jpg" ) def test_render(self): w = widgets.AdminFileWidget() self.assertHTMLEqual( w.render("test", self.album.cover_art), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a> ' '<span class="clearable-file-input">' '<input type="checkbox" name="test-clear" id="test-clear_id"> ' '<label for="test-clear_id">Clear</label></span><br>' 'Change: <input type="file" name="test"></p>' % { "STORAGE_URL": default_storage.url(""), }, ) self.assertHTMLEqual( w.render("test", SimpleUploadedFile("test", b"content")), '<input type="file" name="test">', ) def test_render_with_attrs_id(self): storage_url = default_storage.url("") w = widgets.AdminFileWidget() self.assertHTMLEqual( w.render("test", self.album.cover_art, attrs={"id": "test_id"}), f'<p class="file-upload">Currently: <a href="{storage_url}albums/' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a> ' '<span class="clearable-file-input">' '<input type="checkbox" name="test-clear" id="test-clear_id"> ' '<label for="test-clear_id">Clear</label></span><br>' 'Change: <input type="file" name="test" id="test_id"></p>', ) def test_render_required(self): widget = widgets.AdminFileWidget() widget.is_required = True self.assertHTMLEqual( widget.render("test", self.album.cover_art), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a><br>' 'Change: <input type="file" name="test"></p>' % { "STORAGE_URL": default_storage.url(""), }, ) def test_render_disabled(self): widget = widgets.AdminFileWidget(attrs={"disabled": True}) self.assertHTMLEqual( widget.render("test", self.album.cover_art), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a> ' '<span class="clearable-file-input">' '<input type="checkbox" name="test-clear" id="test-clear_id" disabled>' '<label for="test-clear_id">Clear</label></span><br>' 'Change: <input type="file" name="test" disabled></p>' % { "STORAGE_URL": default_storage.url(""), }, ) def test_render_checked(self): storage_url = default_storage.url("") widget = widgets.AdminFileWidget() widget.checked = True self.assertHTMLEqual( widget.render("test", self.album.cover_art), f'<p class="file-upload">Currently: <a href="{storage_url}albums/' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a> ' '<span class="clearable-file-input">' '<input type="checkbox" name="test-clear" id="test-clear_id" checked>' '<label for="test-clear_id">Clear</label></span><br>' 'Change: <input type="file" name="test" checked></p>', ) def test_readonly_fields(self): """ File widgets should render as a link when they're marked "read only." """ self.client.force_login(self.superuser) response = self.client.get( reverse("admin:admin_widgets_album_change", args=(self.album.id,)) ) self.assertContains( response, '<div class="readonly"><a href="%(STORAGE_URL)salbums/hybrid_theory.jpg">' r"albums\hybrid_theory.jpg</a></div>" % {"STORAGE_URL": default_storage.url("")}, html=True, ) self.assertNotContains( response, '<input type="file" name="cover_art" id="id_cover_art">', html=True, ) response = self.client.get(reverse("admin:admin_widgets_album_add")) self.assertContains( response, '<div class="readonly">-</div>', html=True, ) @override_settings(ROOT_URLCONF="admin_widgets.urls") class ForeignKeyRawIdWidgetTest(TestCase): def test_render(self): band = Band.objects.create(name="Linkin Park") band.album_set.create( name="Hybrid Theory", cover_art=r"albums\hybrid_theory.jpg" ) rel_uuid = Album._meta.get_field("band").remote_field w = widgets.ForeignKeyRawIdWidget(rel_uuid, widget_admin_site) self.assertHTMLEqual( w.render("test", band.uuid, attrs={}), '<div><input type="text" name="test" value="%(banduuid)s" ' 'class="vForeignKeyRawIdAdminField vUUIDField">' '<a href="/admin_widgets/band/?_to_field=uuid" class="related-lookup" ' 'id="lookup_id_test" title="Lookup"></a>&nbsp;<strong>' '<a href="/admin_widgets/band/%(bandpk)s/change/">Linkin Park</a>' "</strong></div>" % {"banduuid": band.uuid, "bandpk": band.pk}, ) rel_id = ReleaseEvent._meta.get_field("album").remote_field w = widgets.ForeignKeyRawIdWidget(rel_id, widget_admin_site) self.assertHTMLEqual( w.render("test", None, attrs={}), '<div><input type="text" name="test" class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/album/?_to_field=id" class="related-lookup" ' 'id="lookup_id_test" title="Lookup"></a></div>', ) def test_relations_to_non_primary_key(self): # ForeignKeyRawIdWidget works with fields which aren't related to # the model's primary key. apple = Inventory.objects.create(barcode=86, name="Apple") Inventory.objects.create(barcode=22, name="Pear") core = Inventory.objects.create(barcode=87, name="Core", parent=apple) rel = Inventory._meta.get_field("parent").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("test", core.parent_id, attrs={}), '<div><input type="text" name="test" value="86" ' 'class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/inventory/?_to_field=barcode" ' 'class="related-lookup" id="lookup_id_test" title="Lookup"></a>' '&nbsp;<strong><a href="/admin_widgets/inventory/%(pk)s/change/">' "Apple</a></strong></div>" % {"pk": apple.pk}, ) def test_fk_related_model_not_in_admin(self): # FK to a model not registered with admin site. Raw ID widget should # have no magnifying glass link. See #16542 big_honeycomb = Honeycomb.objects.create(location="Old tree") big_honeycomb.bee_set.create() rel = Bee._meta.get_field("honeycomb").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("honeycomb_widget", big_honeycomb.pk, attrs={}), '<input type="text" name="honeycomb_widget" value="%(hcombpk)s">' "&nbsp;<strong>%(hcomb)s</strong>" % {"hcombpk": big_honeycomb.pk, "hcomb": big_honeycomb}, ) def test_fk_to_self_model_not_in_admin(self): # FK to self, not registered with admin site. Raw ID widget should have # no magnifying glass link. See #16542 subject1 = Individual.objects.create(name="Subject #1") Individual.objects.create(name="Child", parent=subject1) rel = Individual._meta.get_field("parent").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("individual_widget", subject1.pk, attrs={}), '<input type="text" name="individual_widget" value="%(subj1pk)s">' "&nbsp;<strong>%(subj1)s</strong>" % {"subj1pk": subject1.pk, "subj1": subject1}, ) def test_proper_manager_for_label_lookup(self): # see #9258 rel = Inventory._meta.get_field("parent").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) hidden = Inventory.objects.create(barcode=93, name="Hidden", hidden=True) child_of_hidden = Inventory.objects.create( barcode=94, name="Child of hidden", parent=hidden ) self.assertHTMLEqual( w.render("test", child_of_hidden.parent_id, attrs={}), '<div><input type="text" name="test" value="93" ' ' class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/inventory/?_to_field=barcode" ' 'class="related-lookup" id="lookup_id_test" title="Lookup"></a>' '&nbsp;<strong><a href="/admin_widgets/inventory/%(pk)s/change/">' "Hidden</a></strong></div>" % {"pk": hidden.pk}, ) def test_render_unsafe_limit_choices_to(self): rel = UnsafeLimitChoicesTo._meta.get_field("band").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("test", None), '<div><input type="text" name="test" class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/band/?name=%22%26%3E%3Cescapeme&amp;' '_to_field=artist_ptr" class="related-lookup" id="lookup_id_test" ' 'title="Lookup"></a></div>', ) def test_render_fk_as_pk_model(self): rel = VideoStream._meta.get_field("release_event").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("test", None), '<div><input type="text" name="test" class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/releaseevent/?_to_field=album" ' 'class="related-lookup" id="lookup_id_test" title="Lookup"></a></div>', ) @override_settings(ROOT_URLCONF="admin_widgets.urls") class ManyToManyRawIdWidgetTest(TestCase): def test_render(self): band = Band.objects.create(name="Linkin Park") m1 = Member.objects.create(name="Chester") m2 = Member.objects.create(name="Mike") band.members.add(m1, m2) rel = Band._meta.get_field("members").remote_field w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("test", [m1.pk, m2.pk], attrs={}), (
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_widgets/widgetadmin.py
tests/admin_widgets/widgetadmin.py
from django.contrib import admin from .models import ( Advisor, Album, Band, Bee, Car, CarTire, Event, Inventory, Member, Profile, ReleaseEvent, School, Student, User, VideoStream, ) class WidgetAdmin(admin.AdminSite): pass class CarAdmin(admin.ModelAdmin): list_display = ["make", "model", "owner"] list_editable = ["owner"] class CarTireAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "car": kwargs["queryset"] = Car.objects.filter(owner=request.user) return db_field.formfield(**kwargs) return super().formfield_for_foreignkey(db_field, request, **kwargs) class EventAdmin(admin.ModelAdmin): raw_id_fields = ["main_band", "supporting_bands"] class AlbumAdmin(admin.ModelAdmin): fields = ( "name", "cover_art", ) readonly_fields = ("cover_art",) class SchoolAdmin(admin.ModelAdmin): filter_vertical = ("students",) filter_horizontal = ("alumni",) site = WidgetAdmin(name="widget-admin") site.register(User) site.register(Car, CarAdmin) site.register(CarTire, CarTireAdmin) site.register(Member) site.register(Band) site.register(Event, EventAdmin) site.register(Album, AlbumAdmin) site.register(ReleaseEvent, search_fields=["name"]) site.register(VideoStream, autocomplete_fields=["release_event"]) site.register(Inventory) site.register(Bee) site.register(Advisor) site.register(School, SchoolAdmin) site.register(Student) site.register(Profile)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_widgets/urls.py
tests/admin_widgets/urls.py
from django.urls import path from . import widgetadmin urlpatterns = [ path("", widgetadmin.site.urls), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/mutually_referential/models.py
tests/mutually_referential/models.py
""" Mutually referential many-to-one relationships Strings can be used instead of model literals to set up "lazy" relations. """ from django.db import models class Parent(models.Model): name = models.CharField(max_length=100) # Use a simple string for forward declarations. bestchild = models.ForeignKey( "Child", models.SET_NULL, null=True, related_name="favored_by" ) class Child(models.Model): name = models.CharField(max_length=100) # You can also explicitly specify the related app. parent = models.ForeignKey("mutually_referential.Parent", models.CASCADE)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/mutually_referential/__init__.py
tests/mutually_referential/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/mutually_referential/tests.py
tests/mutually_referential/tests.py
from django.test import TestCase from .models import Parent class MutuallyReferentialTests(TestCase): def test_mutually_referential(self): # Create a Parent q = Parent(name="Elizabeth") q.save() # Create some children c = q.child_set.create(name="Charles") q.child_set.create(name="Edward") # Set the best child # No assertion require here; if basic assignment and # deletion works, the test passes. q.bestchild = c q.save() q.delete()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_regress/models.py
tests/model_regress/models.py
from django.db import models class Article(models.Model): CHOICES = ( (1, "first"), (2, "second"), ) headline = models.CharField(max_length=100, default="Default headline") pub_date = models.DateTimeField() status = models.IntegerField(blank=True, null=True, choices=CHOICES) misc_data = models.CharField(max_length=100, blank=True) article_text = models.TextField() class Meta: ordering = ("pub_date", "headline") # A utf-8 verbose name (Ångström's Articles) to test they are valid. verbose_name = "\xc3\x85ngstr\xc3\xb6m's Articles" class Movie(models.Model): # Test models with non-default primary keys / AutoFields #5218 movie_id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) class Party(models.Model): when = models.DateField(null=True) class Event(models.Model): when = models.DateTimeField() class Department(models.Model): id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=200) class Worker(models.Model): department = models.ForeignKey(Department, models.CASCADE) name = models.CharField(max_length=200) def __str__(self): return self.name class WorkerProfile(models.Model): worker = models.OneToOneField(Worker, on_delete=models.CASCADE) class NonAutoPK(models.Model): name = models.CharField(max_length=10, primary_key=True) # Chained foreign keys with to_field produce incorrect query #18432 class Model1(models.Model): pkey = models.IntegerField(unique=True, db_index=True) class Model2(models.Model): model1 = models.ForeignKey(Model1, models.CASCADE, unique=True, to_field="pkey") class Model3(models.Model): model2 = models.ForeignKey(Model2, models.CASCADE, unique=True, to_field="model1")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_regress/test_state.py
tests/model_regress/test_state.py
import gc from django.db.models.base import ModelState, ModelStateFieldsCacheDescriptor from django.test import SimpleTestCase from django.test.utils import garbage_collect from .models import Worker, WorkerProfile class ModelStateTests(SimpleTestCase): def test_fields_cache_descriptor(self): self.assertIsInstance(ModelState.fields_cache, ModelStateFieldsCacheDescriptor) def test_one_to_one_field_cycle_collection(self): self.addCleanup(gc.set_debug, gc.get_debug()) gc.set_debug(gc.DEBUG_SAVEALL) def clear_garbage(): del gc.garbage[:] self.addCleanup(clear_garbage) worker = Worker() profile = WorkerProfile(worker=worker) worker_id = id(worker) del worker del profile garbage_collect() leaked = [obj for obj in gc.garbage if id(obj) == worker_id] self.assertEqual(leaked, [])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_regress/__init__.py
tests/model_regress/__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_regress/tests.py
tests/model_regress/tests.py
import copy import datetime from operator import attrgetter from django.core.exceptions import ValidationError from django.db import models, router from django.db.models.sql import InsertQuery from django.test import TestCase, skipUnlessDBFeature from django.test.utils import isolate_apps from django.utils.timezone import get_fixed_timezone from .models import ( Article, Department, Event, Model1, Model2, Model3, NonAutoPK, Party, Worker, ) class ModelTests(TestCase): def test_model_init_too_many_args(self): msg = "Number of args exceeds number of fields" with self.assertRaisesMessage(IndexError, msg): Worker(1, 2, 3, 4) # The bug is that the following queries would raise: # "TypeError: Related Field has invalid lookup: gte" def test_related_gte_lookup(self): """ Regression test for #10153: foreign key __gte lookups. """ Worker.objects.filter(department__gte=0) def test_related_lte_lookup(self): """ Regression test for #10153: foreign key __lte lookups. """ Worker.objects.filter(department__lte=0) def test_sql_insert_compiler_return_id_attribute(self): """ Regression test for #14019: SQLInsertCompiler.as_sql() failure """ db = router.db_for_write(Party) query = InsertQuery(Party) query.insert_values([Party._meta.fields[0]], [], raw=False) # this line will raise an AttributeError without the accompanying fix query.get_compiler(using=db).as_sql() def test_empty_choice(self): # NOTE: Part of the regression test here is merely parsing the model # declaration. The verbose_name, in particular, did not always work. a = Article.objects.create( headline="Look at me!", pub_date=datetime.datetime.now() ) # An empty choice field should return None for the display name. self.assertIs(a.get_status_display(), None) # Empty strings should be returned as string a = Article.objects.get(pk=a.pk) self.assertEqual(a.misc_data, "") def test_long_textfield(self): # TextFields can hold more than 4000 characters (this was broken in # Oracle). a = Article.objects.create( headline="Really, really big", pub_date=datetime.datetime.now(), article_text="ABCDE" * 1000, ) a = Article.objects.get(pk=a.pk) self.assertEqual(len(a.article_text), 5000) def test_long_unicode_textfield(self): # TextFields can hold more than 4000 bytes also when they are # less than 4000 characters a = Article.objects.create( headline="Really, really big", pub_date=datetime.datetime.now(), article_text="\u05d0\u05d1\u05d2" * 1000, ) a = Article.objects.get(pk=a.pk) self.assertEqual(len(a.article_text), 3000) def test_date_lookup(self): # Regression test for #659 Party.objects.create(when=datetime.datetime(1999, 12, 31)) Party.objects.create(when=datetime.datetime(1998, 12, 31)) Party.objects.create(when=datetime.datetime(1999, 1, 1)) Party.objects.create(when=datetime.datetime(1, 3, 3)) self.assertQuerySetEqual(Party.objects.filter(when__month=2), []) self.assertQuerySetEqual( Party.objects.filter(when__month=1), [datetime.date(1999, 1, 1)], attrgetter("when"), ) self.assertQuerySetEqual( Party.objects.filter(when__month=12), [ datetime.date(1999, 12, 31), datetime.date(1998, 12, 31), ], attrgetter("when"), ordered=False, ) self.assertQuerySetEqual( Party.objects.filter(when__year=1998), [ datetime.date(1998, 12, 31), ], attrgetter("when"), ) # Regression test for #8510 self.assertQuerySetEqual( Party.objects.filter(when__day="31"), [ datetime.date(1999, 12, 31), datetime.date(1998, 12, 31), ], attrgetter("when"), ordered=False, ) self.assertQuerySetEqual( Party.objects.filter(when__month="12"), [ datetime.date(1999, 12, 31), datetime.date(1998, 12, 31), ], attrgetter("when"), ordered=False, ) self.assertQuerySetEqual( Party.objects.filter(when__year="1998"), [ datetime.date(1998, 12, 31), ], attrgetter("when"), ) # Regression test for #18969 self.assertQuerySetEqual( Party.objects.filter(when__year=1), [ datetime.date(1, 3, 3), ], attrgetter("when"), ) self.assertQuerySetEqual( Party.objects.filter(when__year="1"), [ datetime.date(1, 3, 3), ], attrgetter("when"), ) def test_date_filter_null(self): # Date filtering was failing with NULL date values in SQLite # (regression test for #3501, among other things). Party.objects.create(when=datetime.datetime(1999, 1, 1)) Party.objects.create() p = Party.objects.filter(when__month=1)[0] self.assertEqual(p.when, datetime.date(1999, 1, 1)) self.assertQuerySetEqual( Party.objects.filter(pk=p.pk).dates("when", "month"), [1], attrgetter("month"), ) def test_get_next_prev_by_field(self): # get_next_by_FIELD() and get_previous_by_FIELD() don't crash when # microseconds values are stored in the database. Event.objects.create(when=datetime.datetime(2000, 1, 1, 16, 0, 0)) Event.objects.create(when=datetime.datetime(2000, 1, 1, 6, 1, 1)) Event.objects.create(when=datetime.datetime(2000, 1, 1, 13, 1, 1)) e = Event.objects.create(when=datetime.datetime(2000, 1, 1, 12, 0, 20, 24)) self.assertEqual( e.get_next_by_when().when, datetime.datetime(2000, 1, 1, 13, 1, 1) ) self.assertEqual( e.get_previous_by_when().when, datetime.datetime(2000, 1, 1, 6, 1, 1) ) def test_get_next_prev_by_field_unsaved(self): msg = "get_next/get_previous cannot be used on unsaved objects." with self.assertRaisesMessage(ValueError, msg): Event().get_next_by_when() with self.assertRaisesMessage(ValueError, msg): Event().get_previous_by_when() def test_primary_key_foreign_key_types(self): # Check Department and Worker (non-default PK type) d = Department.objects.create(id=10, name="IT") w = Worker.objects.create(department=d, name="Full-time") self.assertEqual(str(w), "Full-time") @skipUnlessDBFeature("supports_timezones") def test_timezones(self): # Saving and updating with timezone-aware datetime Python objects. # Regression test for #10443. # The idea is that all these creations and saving should work without # crashing. It's not rocket science. dt1 = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=get_fixed_timezone(600)) dt2 = datetime.datetime(2008, 8, 31, 17, 20, tzinfo=get_fixed_timezone(600)) obj = Article.objects.create( headline="A headline", pub_date=dt1, article_text="foo" ) obj.pub_date = dt2 obj.save() self.assertEqual( Article.objects.filter(headline="A headline").update(pub_date=dt1), 1 ) def test_chained_fks(self): """ Chained foreign keys with to_field produce incorrect query. """ m1 = Model1.objects.create(pkey=1000) m2 = Model2.objects.create(model1=m1) m3 = Model3.objects.create(model2=m2) # this is the actual test for #18432 m3 = Model3.objects.get(model2=1000) m3.model2 @isolate_apps("model_regress") def test_metaclass_can_access_attribute_dict(self): """ Model metaclasses have access to the class attribute dict in __init__() (#30254). """ class HorseBase(models.base.ModelBase): def __init__(cls, name, bases, attrs): super().__init__(name, bases, attrs) cls.horns = 1 if "magic" in attrs else 0 class Horse(models.Model, metaclass=HorseBase): name = models.CharField(max_length=255) magic = True self.assertEqual(Horse.horns, 1) class ModelValidationTest(TestCase): def test_pk_validation(self): NonAutoPK.objects.create(name="one") again = NonAutoPK(name="one") with self.assertRaises(ValidationError): again.validate_unique() class EvaluateMethodTest(TestCase): """ Regression test for #13640: cannot filter by objects with 'evaluate' attr """ def test_model_with_evaluate_method(self): """ You can filter by objects that have an 'evaluate' attr """ dept = Department.objects.create(pk=1, name="abc") dept.evaluate = "abc" Worker.objects.filter(department=dept) class ModelFieldsCacheTest(TestCase): def test_fields_cache_reset_on_copy(self): department1 = Department.objects.create(id=1, name="department1") department2 = Department.objects.create(id=2, name="department2") worker1 = Worker.objects.create(name="worker", department=department1) worker2 = copy.copy(worker1) self.assertEqual(worker2.department, department1) # Changing related fields doesn't mutate the base object. worker2.department = department2 self.assertEqual(worker2.department, department2) self.assertEqual(worker1.department, department1)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_regress/test_pickle.py
tests/model_regress/test_pickle.py
import pickle import django from django.db import DJANGO_VERSION_PICKLE_KEY, models from django.test import SimpleTestCase class ModelPickleTests(SimpleTestCase): def test_missing_django_version_unpickling(self): """ #21430 -- Verifies a warning is raised for models that are unpickled without a Django version """ class MissingDjangoVersion(models.Model): title = models.CharField(max_length=10) def __reduce__(self): reduce_list = super().__reduce__() data = reduce_list[-1] del data[DJANGO_VERSION_PICKLE_KEY] return reduce_list p = MissingDjangoVersion(title="FooBar") msg = "Pickled model instance's Django version is not specified." with self.assertRaisesMessage(RuntimeWarning, msg): pickle.loads(pickle.dumps(p)) def test_unsupported_unpickle(self): """ #21430 -- Verifies a warning is raised for models that are unpickled with a different Django version than the current """ class DifferentDjangoVersion(models.Model): title = models.CharField(max_length=10) def __reduce__(self): reduce_list = super().__reduce__() data = reduce_list[-1] data[DJANGO_VERSION_PICKLE_KEY] = "1.0" return reduce_list p = DifferentDjangoVersion(title="FooBar") msg = ( "Pickled model instance's Django version 1.0 does not match the " "current version %s." % django.__version__ ) with self.assertRaisesMessage(RuntimeWarning, msg): pickle.loads(pickle.dumps(p)) def test_with_getstate(self): """ A model may override __getstate__() to choose the attributes to pickle. """ class PickledModel(models.Model): def __getstate__(self): state = super().__getstate__().copy() del state["dont_pickle"] return state m = PickledModel() m.dont_pickle = 1 dumped = pickle.dumps(m) self.assertEqual(m.dont_pickle, 1) reloaded = pickle.loads(dumped) self.assertFalse(hasattr(reloaded, "dont_pickle"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/m2o_recursive/models.py
tests/m2o_recursive/models.py
""" Relating an object to itself, many-to-one To define a many-to-one relationship between a model and itself, use ``ForeignKey('self', ...)``. In this example, a ``Category`` is related to itself. That is, each ``Category`` has a parent ``Category``. 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) parent = models.ForeignKey( "self", models.SET_NULL, blank=True, null=True, related_name="child_set" ) def __str__(self): return self.name class Person(models.Model): full_name = models.CharField(max_length=20) mother = models.ForeignKey( "self", models.SET_NULL, null=True, related_name="mothers_child_set" ) father = models.ForeignKey( "self", models.SET_NULL, null=True, related_name="fathers_child_set" ) def __str__(self): return self.full_name
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/m2o_recursive/__init__.py
tests/m2o_recursive/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/m2o_recursive/tests.py
tests/m2o_recursive/tests.py
from django.test import TestCase from .models import Category, Person class ManyToOneRecursiveTests(TestCase): @classmethod def setUpTestData(cls): cls.r = Category.objects.create(id=None, name="Root category", parent=None) cls.c = Category.objects.create(id=None, name="Child category", parent=cls.r) def test_m2o_recursive(self): self.assertSequenceEqual(self.r.child_set.all(), [self.c]) self.assertEqual(self.r.child_set.get(name__startswith="Child").id, self.c.id) self.assertIsNone(self.r.parent) self.assertSequenceEqual(self.c.child_set.all(), []) self.assertEqual(self.c.parent.id, self.r.id) class MultipleManyToOneRecursiveTests(TestCase): @classmethod def setUpTestData(cls): cls.dad = Person.objects.create( full_name="John Smith Senior", mother=None, father=None ) cls.mom = Person.objects.create( full_name="Jane Smith", mother=None, father=None ) cls.kid = Person.objects.create( full_name="John Smith Junior", mother=cls.mom, father=cls.dad ) def test_m2o_recursive2(self): self.assertEqual(self.kid.mother.id, self.mom.id) self.assertEqual(self.kid.father.id, self.dad.id) self.assertSequenceEqual(self.dad.fathers_child_set.all(), [self.kid]) self.assertSequenceEqual(self.mom.mothers_child_set.all(), [self.kid]) self.assertSequenceEqual(self.kid.mothers_child_set.all(), []) self.assertSequenceEqual(self.kid.fathers_child_set.all(), [])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/fixtures_model_package/__init__.py
tests/fixtures_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/fixtures_model_package/tests.py
tests/fixtures_model_package/tests.py
from django.core import management from django.core.management import CommandError from django.test import TestCase from .models import Article class SampleTestCase(TestCase): fixtures = ["model_package_fixture1.json", "model_package_fixture2.json"] def test_class_fixtures(self): "Test cases can load fixture objects into models defined in packages" self.assertQuerySetEqual( Article.objects.all(), [ "Django conquers world!", "Copyright is fine the way it is", "Poker has no place on ESPN", ], lambda a: a.headline, ) class FixtureTestCase(TestCase): def test_loaddata(self): "Fixtures can load data into models defined in packages" # Load fixture 1. Single JSON file, with two objects management.call_command("loaddata", "model_package_fixture1.json", verbosity=0) self.assertQuerySetEqual( Article.objects.all(), [ "Time to reform copyright", "Poker has no place on ESPN", ], lambda a: a.headline, ) # Load fixture 2. JSON file imported by default. Overwrites some # existing objects management.call_command("loaddata", "model_package_fixture2.json", verbosity=0) self.assertQuerySetEqual( Article.objects.all(), [ "Django conquers world!", "Copyright is fine the way it is", "Poker has no place on ESPN", ], lambda a: a.headline, ) # Load a fixture that doesn't exist with self.assertRaisesMessage( CommandError, "No fixture named 'unknown' found." ): management.call_command("loaddata", "unknown.json", verbosity=0) self.assertQuerySetEqual( Article.objects.all(), [ "Django conquers world!", "Copyright is fine the way it is", "Poker has no place on ESPN", ], lambda a: a.headline, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/fixtures_model_package/models/__init__.py
tests/fixtures_model_package/models/__init__.py
from django.db import models class Article(models.Model): headline = models.CharField(max_length=100, default="Default headline") pub_date = models.DateTimeField() class Meta: app_label = "fixtures_model_package" ordering = ("-pub_date", "headline") def __str__(self): return self.headline
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/annotations/models.py
tests/annotations/models.py
from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() friends = models.ManyToManyField("self", blank=True) class Publisher(models.Model): name = models.CharField(max_length=255) num_awards = models.IntegerField() class Book(models.Model): isbn = models.CharField(max_length=9) name = models.CharField(max_length=255) pages = models.IntegerField() rating = models.FloatField() price = models.DecimalField(decimal_places=2, max_digits=6) authors = models.ManyToManyField(Author) contact = models.ForeignKey(Author, models.CASCADE, related_name="book_contact_set") publisher = models.ForeignKey(Publisher, models.CASCADE) pubdate = models.DateField() class Store(models.Model): name = models.CharField(max_length=255) books = models.ManyToManyField(Book) original_opening = models.DateTimeField() friday_night_closing = models.TimeField() area = models.IntegerField(null=True, db_column="surface") class DepartmentStore(Store): chain = models.CharField(max_length=255) class Employee(models.Model): # The order of these fields matter, do not change. Certain backends # rely on field ordering to perform database conversions, and this # model helps to test that. first_name = models.CharField(max_length=20) manager = models.BooleanField(default=False) last_name = models.CharField(max_length=20) store = models.ForeignKey(Store, models.CASCADE) age = models.IntegerField() salary = models.DecimalField(max_digits=8, decimal_places=2) class Company(models.Model): name = models.CharField(max_length=200) motto = models.CharField(max_length=200, null=True, blank=True) ticker_name = models.CharField(max_length=10, null=True, blank=True) description = models.CharField(max_length=200, null=True, blank=True) class Ticket(models.Model): active_at = models.DateTimeField() duration = models.DurationField() class JsonModel(models.Model): data = models.JSONField(default=dict, blank=True) id = models.IntegerField(primary_key=True) class Meta: required_db_features = {"supports_json_field"}
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/annotations/__init__.py
tests/annotations/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/annotations/tests.py
tests/annotations/tests.py
import datetime from decimal import Decimal from unittest import skipUnless from django.core.exceptions import FieldDoesNotExist, FieldError from django.db import connection from django.db.models import ( BooleanField, Case, CharField, Count, DateTimeField, DecimalField, Exists, ExpressionWrapper, F, FilteredRelation, FloatField, Func, IntegerField, JSONField, Max, OuterRef, Q, Subquery, Sum, Value, When, ) from django.db.models.expressions import RawSQL from django.db.models.functions import ( Cast, Coalesce, ExtractYear, Floor, Length, Lower, Trim, ) from django.db.models.sql.query import get_field_names_from_opts from django.test import TestCase, skipUnlessDBFeature from django.test.utils import register_lookup from django.utils.deprecation import RemovedInDjango70Warning from .models import ( Author, Book, Company, DepartmentStore, Employee, JsonModel, Publisher, Store, Ticket, ) class NonAggregateAnnotationTestCase(TestCase): @classmethod def setUpTestData(cls): cls.a1 = Author.objects.create(name="Adrian Holovaty", age=34) cls.a2 = Author.objects.create(name="Jacob Kaplan-Moss", age=35) cls.a3 = Author.objects.create(name="Brad Dayley", age=45) cls.a4 = Author.objects.create(name="James Bennett", age=29) cls.a5 = Author.objects.create(name="Jeffrey Forcier", age=37) cls.a6 = Author.objects.create(name="Paul Bissex", age=29) cls.a7 = Author.objects.create(name="Wesley J. Chun", age=25) cls.a8 = Author.objects.create(name="Peter Norvig", age=57) cls.a9 = Author.objects.create(name="Stuart Russell", age=46) cls.a1.friends.add(cls.a2, cls.a4) cls.a2.friends.add(cls.a1, cls.a7) cls.a4.friends.add(cls.a1) cls.a5.friends.add(cls.a6, cls.a7) cls.a6.friends.add(cls.a5, cls.a7) cls.a7.friends.add(cls.a2, cls.a5, cls.a6) cls.a8.friends.add(cls.a9) cls.a9.friends.add(cls.a8) cls.p1 = Publisher.objects.create(name="Apress", num_awards=3) cls.p2 = Publisher.objects.create(name="Sams", num_awards=1) cls.p3 = Publisher.objects.create(name="Prentice Hall", num_awards=7) cls.p4 = Publisher.objects.create(name="Morgan Kaufmann", num_awards=9) cls.p5 = Publisher.objects.create(name="Jonno's House of Books", num_awards=0) cls.b1 = Book.objects.create( isbn="159059725", name="The Definitive Guide to Django: Web Development Done Right", pages=447, rating=4.5, price=Decimal("30.00"), contact=cls.a1, publisher=cls.p1, pubdate=datetime.date(2007, 12, 6), ) cls.b2 = Book.objects.create( isbn="067232959", name="Sams Teach Yourself Django in 24 Hours", pages=528, rating=3.0, price=Decimal("23.09"), contact=cls.a3, publisher=cls.p2, pubdate=datetime.date(2008, 3, 3), ) cls.b3 = Book.objects.create( isbn="159059996", name="Practical Django Projects", pages=300, rating=4.0, price=Decimal("29.69"), contact=cls.a4, publisher=cls.p1, pubdate=datetime.date(2008, 6, 23), ) cls.b4 = Book.objects.create( isbn="013235613", name="Python Web Development with Django", pages=350, rating=4.0, price=Decimal("29.69"), contact=cls.a5, publisher=cls.p3, pubdate=datetime.date(2008, 11, 3), ) cls.b5 = Book.objects.create( isbn="013790395", name="Artificial Intelligence: A Modern Approach", pages=1132, rating=4.0, price=Decimal("82.80"), contact=cls.a8, publisher=cls.p3, pubdate=datetime.date(1995, 1, 15), ) cls.b6 = Book.objects.create( isbn="155860191", name=( "Paradigms of Artificial Intelligence Programming: Case Studies in " "Common Lisp" ), pages=946, rating=5.0, price=Decimal("75.00"), contact=cls.a8, publisher=cls.p4, pubdate=datetime.date(1991, 10, 15), ) cls.b1.authors.add(cls.a1, cls.a2) cls.b2.authors.add(cls.a3) cls.b3.authors.add(cls.a4) cls.b4.authors.add(cls.a5, cls.a6, cls.a7) cls.b5.authors.add(cls.a8, cls.a9) cls.b6.authors.add(cls.a8) cls.s1 = Store.objects.create( name="Amazon.com", original_opening=datetime.datetime(1994, 4, 23, 9, 17, 42), friday_night_closing=datetime.time(23, 59, 59), ) cls.s2 = Store.objects.create( name="Books.com", original_opening=datetime.datetime(2001, 3, 15, 11, 23, 37), friday_night_closing=datetime.time(23, 59, 59), ) cls.s3 = Store.objects.create( name="Mamma and Pappa's Books", original_opening=datetime.datetime(1945, 4, 25, 16, 24, 14), friday_night_closing=datetime.time(21, 30), ) cls.s1.books.add(cls.b1, cls.b2, cls.b3, cls.b4, cls.b5, cls.b6) cls.s2.books.add(cls.b1, cls.b3, cls.b5, cls.b6) cls.s3.books.add(cls.b3, cls.b4, cls.b6) def test_basic_annotation(self): books = Book.objects.annotate(is_book=Value(1)) for book in books: self.assertEqual(book.is_book, 1) def test_basic_f_annotation(self): books = Book.objects.annotate(another_rating=F("rating")) for book in books: self.assertEqual(book.another_rating, book.rating) def test_joined_annotation(self): books = Book.objects.select_related("publisher").annotate( num_awards=F("publisher__num_awards") ) for book in books: self.assertEqual(book.num_awards, book.publisher.num_awards) def test_joined_transformed_annotation(self): Employee.objects.bulk_create( [ Employee( first_name="John", last_name="Doe", age=18, store=self.s1, salary=15000, ), Employee( first_name="Jane", last_name="Jones", age=30, store=self.s2, salary=30000, ), Employee( first_name="Jo", last_name="Smith", age=55, store=self.s3, salary=50000, ), ] ) employees = Employee.objects.annotate( store_opened_year=F("store__original_opening__year"), ) for employee in employees: self.assertEqual( employee.store_opened_year, employee.store.original_opening.year, ) def test_custom_transform_annotation(self): with register_lookup(DecimalField, Floor): books = Book.objects.annotate(floor_price=F("price__floor")) self.assertCountEqual( books.values_list("pk", "floor_price"), [ (self.b1.pk, 30), (self.b2.pk, 23), (self.b3.pk, 29), (self.b4.pk, 29), (self.b5.pk, 82), (self.b6.pk, 75), ], ) def test_chaining_transforms(self): Company.objects.create(name=" Django Software Foundation ") Company.objects.create(name="Yahoo") with register_lookup(CharField, Trim), register_lookup(CharField, Length): for expr in [Length("name__trim"), F("name__trim__length")]: with self.subTest(expr=expr): self.assertCountEqual( Company.objects.annotate(length=expr).values("name", "length"), [ {"name": " Django Software Foundation ", "length": 26}, {"name": "Yahoo", "length": 5}, ], ) def test_mixed_type_annotation_date_interval(self): active = datetime.datetime(2015, 3, 20, 14, 0, 0) duration = datetime.timedelta(hours=1) expires = datetime.datetime(2015, 3, 20, 14, 0, 0) + duration Ticket.objects.create(active_at=active, duration=duration) t = Ticket.objects.annotate( expires=ExpressionWrapper( F("active_at") + F("duration"), output_field=DateTimeField() ) ).first() self.assertEqual(t.expires, expires) def test_mixed_type_annotation_numbers(self): test = self.b1 b = Book.objects.annotate( combined=ExpressionWrapper( F("pages") + F("rating"), output_field=IntegerField() ) ).get(isbn=test.isbn) combined = int(test.pages + test.rating) self.assertEqual(b.combined, combined) def test_empty_expression_annotation(self): books = Book.objects.annotate( selected=ExpressionWrapper(Q(pk__in=[]), output_field=BooleanField()) ) self.assertEqual(len(books), Book.objects.count()) self.assertTrue(all(not book.selected for book in books)) books = Book.objects.annotate( selected=ExpressionWrapper( Q(pk__in=Book.objects.none()), output_field=BooleanField() ) ) self.assertEqual(len(books), Book.objects.count()) self.assertTrue(all(not book.selected for book in books)) def test_full_expression_annotation(self): books = Book.objects.annotate( selected=ExpressionWrapper(~Q(pk__in=[]), output_field=BooleanField()), ) self.assertEqual(len(books), Book.objects.count()) self.assertTrue(all(book.selected for book in books)) def test_full_expression_wrapped_annotation(self): books = Book.objects.annotate( selected=Coalesce(~Q(pk__in=[]), True), ) self.assertEqual(len(books), Book.objects.count()) self.assertTrue(all(book.selected for book in books)) def test_full_expression_annotation_with_aggregation(self): qs = Book.objects.filter(isbn="159059725").annotate( selected=ExpressionWrapper(~Q(pk__in=[]), output_field=BooleanField()), rating_count=Count("rating"), ) self.assertEqual([book.rating_count for book in qs], [1]) def test_aggregate_over_full_expression_annotation(self): qs = Book.objects.annotate( selected=ExpressionWrapper(~Q(pk__in=[]), output_field=BooleanField()), ).aggregate(selected__sum=Sum(Cast("selected", IntegerField()))) self.assertEqual(qs["selected__sum"], Book.objects.count()) def test_empty_queryset_annotation(self): qs = Author.objects.annotate(empty=Subquery(Author.objects.values("id").none())) self.assertIsNone(qs.first().empty) def test_annotate_with_aggregation(self): books = Book.objects.annotate(is_book=Value(1), rating_count=Count("rating")) for book in books: self.assertEqual(book.is_book, 1) self.assertEqual(book.rating_count, 1) def test_combined_expression_annotation_with_aggregation(self): book = Book.objects.annotate( combined=ExpressionWrapper( Value(3) * Value(4), output_field=IntegerField() ), rating_count=Count("rating"), ).first() self.assertEqual(book.combined, 12) self.assertEqual(book.rating_count, 1) def test_combined_f_expression_annotation_with_aggregation(self): book = ( Book.objects.filter(isbn="159059725") .annotate( combined=ExpressionWrapper( F("price") * F("pages"), output_field=FloatField() ), rating_count=Count("rating"), ) .first() ) self.assertEqual(book.combined, 13410.0) self.assertEqual(book.rating_count, 1) @skipUnlessDBFeature("supports_boolean_expr_in_select_clause") def test_q_expression_annotation_with_aggregation(self): book = ( Book.objects.filter(isbn="159059725") .annotate( isnull_pubdate=ExpressionWrapper( Q(pubdate__isnull=True), output_field=BooleanField(), ), rating_count=Count("rating"), ) .first() ) self.assertIs(book.isnull_pubdate, False) self.assertEqual(book.rating_count, 1) @skipUnlessDBFeature("supports_boolean_expr_in_select_clause") def test_grouping_by_q_expression_annotation(self): authors = ( Author.objects.annotate( under_40=ExpressionWrapper(Q(age__lt=40), output_field=BooleanField()), ) .values("under_40") .annotate( count_id=Count("id"), ) .values("under_40", "count_id") ) self.assertCountEqual( authors, [ {"under_40": False, "count_id": 3}, {"under_40": True, "count_id": 6}, ], ) def test_aggregate_over_annotation(self): agg = Author.objects.annotate(other_age=F("age")).aggregate( otherage_sum=Sum("other_age") ) other_agg = Author.objects.aggregate(age_sum=Sum("age")) self.assertEqual(agg["otherage_sum"], other_agg["age_sum"]) @skipUnlessDBFeature("can_distinct_on_fields") def test_distinct_on_with_annotation(self): store = Store.objects.create( name="test store", original_opening=datetime.datetime.now(), friday_night_closing=datetime.time(21, 00, 00), ) names = [ "Theodore Roosevelt", "Eleanor Roosevelt", "Franklin Roosevelt", "Ned Stark", "Catelyn Stark", ] for name in names: Employee.objects.create( store=store, first_name=name.split()[0], last_name=name.split()[1], age=30, salary=2000, ) people = Employee.objects.annotate( name_lower=Lower("last_name"), ).distinct("name_lower") self.assertEqual({p.last_name for p in people}, {"Stark", "Roosevelt"}) self.assertEqual(len(people), 2) people2 = Employee.objects.annotate( test_alias=F("store__name"), ).distinct("test_alias") self.assertEqual(len(people2), 1) lengths = ( Employee.objects.annotate( name_len=Length("first_name"), ) .distinct("name_len") .values_list("name_len", flat=True) ) self.assertCountEqual(lengths, [3, 7, 8]) def test_filter_annotation(self): books = Book.objects.annotate(is_book=Value(1)).filter(is_book=1) for book in books: self.assertEqual(book.is_book, 1) def test_filter_annotation_with_f(self): books = Book.objects.annotate(other_rating=F("rating")).filter(other_rating=3.5) for book in books: self.assertEqual(book.other_rating, 3.5) def test_filter_annotation_with_double_f(self): books = Book.objects.annotate(other_rating=F("rating")).filter( other_rating=F("rating") ) for book in books: self.assertEqual(book.other_rating, book.rating) def test_filter_agg_with_double_f(self): books = Book.objects.annotate(sum_rating=Sum("rating")).filter( sum_rating=F("sum_rating") ) for book in books: self.assertEqual(book.sum_rating, book.rating) def test_filter_wrong_annotation(self): with self.assertRaisesMessage( FieldError, "Cannot resolve keyword 'nope' into field." ): list( Book.objects.annotate(sum_rating=Sum("rating")).filter( sum_rating=F("nope") ) ) def test_values_wrong_annotation(self): expected_message = ( "Cannot resolve keyword 'annotation_typo' into field. Choices are: %s" ) article_fields = ", ".join( ["annotation"] + sorted(get_field_names_from_opts(Book._meta)) ) with self.assertRaisesMessage(FieldError, expected_message % article_fields): Book.objects.annotate(annotation=Value(1)).values_list("annotation_typo") def test_decimal_annotation(self): salary = Decimal(10) ** -Employee._meta.get_field("salary").decimal_places Employee.objects.create( first_name="Max", last_name="Paine", store=Store.objects.first(), age=23, salary=salary, ) self.assertEqual( Employee.objects.annotate(new_salary=F("salary") / 10).get().new_salary, salary / 10, ) def test_filter_decimal_annotation(self): qs = ( Book.objects.annotate(new_price=F("price") + 1) .filter(new_price=Decimal(31)) .values_list("new_price") ) self.assertEqual(qs.get(), (Decimal(31),)) def test_combined_annotation_commutative(self): book1 = Book.objects.annotate(adjusted_rating=F("rating") + 2).get( pk=self.b1.pk ) book2 = Book.objects.annotate(adjusted_rating=2 + F("rating")).get( pk=self.b1.pk ) self.assertEqual(book1.adjusted_rating, book2.adjusted_rating) book1 = Book.objects.annotate(adjusted_rating=F("rating") + None).get( pk=self.b1.pk ) book2 = Book.objects.annotate(adjusted_rating=None + F("rating")).get( pk=self.b1.pk ) self.assertIs(book1.adjusted_rating, None) self.assertEqual(book1.adjusted_rating, book2.adjusted_rating) def test_update_with_annotation(self): book_preupdate = Book.objects.get(pk=self.b2.pk) Book.objects.annotate(other_rating=F("rating") - 1).update( rating=F("other_rating") ) book_postupdate = Book.objects.get(pk=self.b2.pk) self.assertEqual(book_preupdate.rating - 1, book_postupdate.rating) def test_annotation_with_m2m(self): books = ( Book.objects.annotate(author_age=F("authors__age")) .filter(pk=self.b1.pk) .order_by("author_age") ) self.assertEqual(books[0].author_age, 34) self.assertEqual(books[1].author_age, 35) def test_annotation_reverse_m2m(self): books = ( Book.objects.annotate( store_name=F("store__name"), ) .filter( name="Practical Django Projects", ) .order_by("store_name") ) self.assertQuerySetEqual( books, ["Amazon.com", "Books.com", "Mamma and Pappa's Books"], lambda b: b.store_name, ) def test_values_annotation(self): """ Annotations can reference fields in a values clause, and contribute to an existing values clause. """ # annotate references a field in values() qs = Book.objects.values("rating").annotate(other_rating=F("rating") - 1) book = qs.get(pk=self.b1.pk) self.assertEqual(book["rating"] - 1, book["other_rating"]) # filter refs the annotated value book = qs.get(other_rating=4) self.assertEqual(book["other_rating"], 4) # can annotate an existing values with a new field book = qs.annotate(other_isbn=F("isbn")).get(other_rating=4) self.assertEqual(book["other_rating"], 4) self.assertEqual(book["other_isbn"], "155860191") def test_values_fields_annotations_order(self): qs = Book.objects.annotate(other_rating=F("rating") - 1).values( "other_rating", "rating" ) book = qs.get(pk=self.b1.pk) self.assertEqual( list(book.items()), [("other_rating", self.b1.rating - 1), ("rating", self.b1.rating)], ) def test_values_with_pk_annotation(self): # annotate references a field in values() with pk publishers = Publisher.objects.values("id", "book__rating").annotate( total=Sum("book__rating") ) for publisher in publishers.filter(pk=self.p1.pk): self.assertEqual(publisher["book__rating"], publisher["total"]) def test_defer_annotation(self): """ Deferred attributes can be referenced by an annotation, but they are not themselves deferred, and cannot be deferred. """ qs = Book.objects.defer("rating").annotate(other_rating=F("rating") - 1) with self.assertNumQueries(2): book = qs.get(other_rating=4) self.assertEqual(book.rating, 5) self.assertEqual(book.other_rating, 4) with self.assertRaisesMessage( FieldDoesNotExist, "Book has no field named 'other_rating'" ): book = qs.defer("other_rating").get(other_rating=4) def test_mti_annotations(self): """ Fields on an inherited model can be referenced by an annotated field. """ d = DepartmentStore.objects.create( name="Angus & Robinson", original_opening=datetime.date(2014, 3, 8), friday_night_closing=datetime.time(21, 00, 00), chain="Westfield", ) books = Book.objects.filter(rating__gt=4) for b in books: d.books.add(b) qs = ( DepartmentStore.objects.annotate( other_name=F("name"), other_chain=F("chain"), is_open=Value(True, BooleanField()), book_isbn=F("books__isbn"), ) .order_by("book_isbn") .filter(chain="Westfield") ) self.assertQuerySetEqual( qs, [ ("Angus & Robinson", "Westfield", True, "155860191"), ("Angus & Robinson", "Westfield", True, "159059725"), ], lambda d: (d.other_name, d.other_chain, d.is_open, d.book_isbn), ) def test_null_annotation(self): """ Annotating None onto a model round-trips """ book = Book.objects.annotate( no_value=Value(None, output_field=IntegerField()) ).first() self.assertIsNone(book.no_value) def test_order_by_annotation(self): authors = Author.objects.annotate(other_age=F("age")).order_by("other_age") self.assertQuerySetEqual( authors, [ 25, 29, 29, 34, 35, 37, 45, 46, 57, ], lambda a: a.other_age, ) def test_order_by_aggregate(self): authors = ( Author.objects.values("age") .annotate(age_count=Count("age")) .order_by("age_count", "age") ) self.assertQuerySetEqual( authors, [ (25, 1), (34, 1), (35, 1), (37, 1), (45, 1), (46, 1), (57, 1), (29, 2), ], lambda a: (a["age"], a["age_count"]), ) def test_raw_sql_with_inherited_field(self): DepartmentStore.objects.create( name="Angus & Robinson", original_opening=datetime.date(2014, 3, 8), friday_night_closing=datetime.time(21), chain="Westfield", area=123, ) tests = ( ("name", "Angus & Robinson"), ("surface", 123), ("case when name='Angus & Robinson' then chain else name end", "Westfield"), ) for sql, expected_result in tests: with self.subTest(sql=sql): self.assertSequenceEqual( DepartmentStore.objects.annotate( annotation=RawSQL(sql, ()), ).values_list("annotation", flat=True), [expected_result], ) def test_annotate_exists(self): authors = Author.objects.annotate(c=Count("id")).filter(c__gt=1) self.assertFalse(authors.exists()) def test_column_field_ordering(self): """ Columns are aligned in the correct order for resolve_columns. This test will fail on MySQL if column ordering is out. Column fields should be aligned as: 1. extra_select 2. model_fields 3. annotation_fields 4. model_related_fields """ store = Store.objects.first() Employee.objects.create( id=1, first_name="Max", manager=True, last_name="Paine", store=store, age=23, salary=Decimal(50000.00), ) Employee.objects.create( id=2, first_name="Buffy", manager=False, last_name="Summers", store=store, age=18, salary=Decimal(40000.00), ) qs = ( Employee.objects.extra(select={"random_value": "42"}) .select_related("store") .annotate( annotated_value=Value(17), ) ) rows = [ (1, "Max", True, 42, "Paine", 23, Decimal(50000.00), store.name, 17), (2, "Buffy", False, 42, "Summers", 18, Decimal(40000.00), store.name, 17), ] self.assertQuerySetEqual( qs.order_by("id"), rows, lambda e: ( e.id, e.first_name, e.manager, e.random_value, e.last_name, e.age, e.salary, e.store.name, e.annotated_value, ), ) def test_column_field_ordering_with_deferred(self): store = Store.objects.first() Employee.objects.create( id=1, first_name="Max", manager=True, last_name="Paine", store=store, age=23, salary=Decimal(50000.00), ) Employee.objects.create( id=2, first_name="Buffy", manager=False, last_name="Summers", store=store, age=18, salary=Decimal(40000.00), ) qs = ( Employee.objects.extra(select={"random_value": "42"}) .select_related("store") .annotate( annotated_value=Value(17), ) ) rows = [ (1, "Max", True, 42, "Paine", 23, Decimal(50000.00), store.name, 17), (2, "Buffy", False, 42, "Summers", 18, Decimal(40000.00), store.name, 17), ] # and we respect deferred columns! self.assertQuerySetEqual( qs.defer("age").order_by("id"), rows, lambda e: ( e.id, e.first_name, e.manager, e.random_value, e.last_name, e.age, e.salary, e.store.name, e.annotated_value, ), ) def test_custom_functions(self): Company( name="Apple", motto=None, ticker_name="APPL", description="Beautiful Devices", ).save() Company( name="Django Software Foundation", motto=None, ticker_name=None, description=None, ).save() Company( name="Google", motto="Do No Evil", ticker_name="GOOG", description="Internet Company", ).save() Company( name="Yahoo", motto=None, ticker_name=None, description="Internet Company" ).save() qs = Company.objects.annotate( tagline=Func( F("motto"), F("ticker_name"), F("description"), Value("No Tag"), function="COALESCE", ) ).order_by("name") self.assertQuerySetEqual( qs, [ ("Apple", "APPL"), ("Django Software Foundation", "No Tag"), ("Google", "Do No Evil"), ("Yahoo", "Internet Company"), ], lambda c: (c.name, c.tagline), ) def test_custom_functions_can_ref_other_functions(self): Company( name="Apple", motto=None, ticker_name="APPL", description="Beautiful Devices", ).save() Company( name="Django Software Foundation", motto=None, ticker_name=None, description=None, ).save() Company( name="Google", motto="Do No Evil", ticker_name="GOOG", description="Internet Company", ).save() Company( name="Yahoo", motto=None, ticker_name=None, description="Internet Company" ).save() class Lower(Func): function = "LOWER" qs = ( Company.objects.annotate( tagline=Func( F("motto"), F("ticker_name"), F("description"), Value("No Tag"), function="COALESCE", ) ) .annotate( tagline_lower=Lower(F("tagline")), ) .order_by("name") ) # LOWER function supported by: # oracle, postgres, mysql, sqlite, sqlserver self.assertQuerySetEqual( qs, [ ("Apple", "APPL".lower()), ("Django Software Foundation", "No Tag".lower()), ("Google", "Do No Evil".lower()), ("Yahoo", "Internet Company".lower()), ], lambda c: (c.name, c.tagline_lower), ) def test_boolean_value_annotation(self): books = Book.objects.annotate( is_book=Value(True, output_field=BooleanField()), is_pony=Value(False, output_field=BooleanField()), is_none=Value(None, output_field=BooleanField(null=True)), ) self.assertGreater(len(books), 0) for book in books: self.assertIs(book.is_book, True) self.assertIs(book.is_pony, False) self.assertIsNone(book.is_none) def test_annotation_in_f_grouped_by_annotation(self): qs = ( Publisher.objects.annotate(multiplier=Value(3)) # group by option => sum of value * multiplier .values("name") .annotate(multiplied_value_sum=Sum(F("multiplier") * F("num_awards"))) .order_by() ) self.assertCountEqual( qs, [ {"multiplied_value_sum": 9, "name": "Apress"}, {"multiplied_value_sum": 0, "name": "Jonno's House of Books"}, {"multiplied_value_sum": 27, "name": "Morgan Kaufmann"}, {"multiplied_value_sum": 21, "name": "Prentice Hall"}, {"multiplied_value_sum": 3, "name": "Sams"}, ], ) def test_arguments_must_be_expressions(self): msg = "QuerySet.annotate() received non-expression(s): %s." with self.assertRaisesMessage(TypeError, msg % BooleanField()): Book.objects.annotate(BooleanField()) with self.assertRaisesMessage(TypeError, msg % True): Book.objects.annotate(is_book=True)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/test_checks.py
tests/staticfiles_tests/test_checks.py
from pathlib import Path from unittest import mock from django.conf import DEFAULT_STORAGE_ALIAS, STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles.checks import E005, check_finders, check_storages from django.contrib.staticfiles.finders import BaseFinder, get_finder from django.core.checks import Error, Warning from django.test import SimpleTestCase, override_settings from .cases import CollectionTestCase from .settings import TEST_ROOT class FindersCheckTests(CollectionTestCase): run_collectstatic_in_setUp = False def test_base_finder_check_not_implemented(self): finder = BaseFinder() msg = ( "subclasses may provide a check() method to verify the finder is " "configured correctly." ) with self.assertRaisesMessage(NotImplementedError, msg): finder.check() def test_check_finders(self): """check_finders() concatenates all errors.""" error1 = Error("1") error2 = Error("2") error3 = Error("3") def get_finders(): class Finder1(BaseFinder): def check(self, **kwargs): return [error1] class Finder2(BaseFinder): def check(self, **kwargs): return [] class Finder3(BaseFinder): def check(self, **kwargs): return [error2, error3] class Finder4(BaseFinder): pass return [Finder1(), Finder2(), Finder3(), Finder4()] with mock.patch("django.contrib.staticfiles.checks.get_finders", get_finders): errors = check_finders(None) self.assertEqual(errors, [error1, error2, error3]) def test_no_errors_with_test_settings(self): self.assertEqual(check_finders(None), []) @override_settings(STATICFILES_DIRS="a string") def test_dirs_not_tuple_or_list(self): self.assertEqual( check_finders(None), [ Error( "The STATICFILES_DIRS setting is not a tuple or list.", hint="Perhaps you forgot a trailing comma?", id="staticfiles.E001", ) ], ) def test_dirs_contains_static_root(self): with self.settings(STATICFILES_DIRS=[settings.STATIC_ROOT]): self.assertEqual( check_finders(None), [ Error( "The STATICFILES_DIRS setting should not contain the " "STATIC_ROOT setting.", id="staticfiles.E002", ) ], ) def test_dirs_contains_static_root_in_tuple(self): with self.settings(STATICFILES_DIRS=[("prefix", settings.STATIC_ROOT)]): self.assertEqual( check_finders(None), [ Error( "The STATICFILES_DIRS setting should not contain the " "STATIC_ROOT setting.", id="staticfiles.E002", ) ], ) def test_prefix_contains_trailing_slash(self): static_dir = Path(TEST_ROOT) / "project" / "documents" with self.settings(STATICFILES_DIRS=[("prefix/", static_dir)]): self.assertEqual( check_finders(None), [ Error( "The prefix 'prefix/' in the STATICFILES_DIRS setting must " "not end with a slash.", id="staticfiles.E003", ), ], ) def test_nonexistent_directories(self): with self.settings( STATICFILES_DIRS=[ "/fake/path", ("prefix", "/fake/prefixed/path"), ] ): self.assertEqual( check_finders(None), [ Warning( "The directory '/fake/path' in the STATICFILES_DIRS " "setting does not exist.", id="staticfiles.W004", ), Warning( "The directory '/fake/prefixed/path' in the " "STATICFILES_DIRS setting does not exist.", id="staticfiles.W004", ), ], ) # Nonexistent directories are skipped. finder = get_finder("django.contrib.staticfiles.finders.FileSystemFinder") self.assertEqual(list(finder.list(None)), []) class StoragesCheckTests(SimpleTestCase): @override_settings(STORAGES={}) def test_error_empty_storages(self): errors = check_storages(None) self.assertEqual(errors, [E005]) @override_settings( STORAGES={ DEFAULT_STORAGE_ALIAS: { "BACKEND": "django.core.files.storage.FileSystemStorage", }, "example": { "BACKEND": "ignore.me", }, } ) def test_error_missing_staticfiles(self): errors = check_storages(None) self.assertEqual(errors, [E005]) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage", }, } ) def test_staticfiles_no_errors(self): errors = check_storages(None) self.assertEqual(errors, [])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/test_finders.py
tests/staticfiles_tests/test_finders.py
import os from django.conf import settings from django.contrib.staticfiles import finders, storage from django.core.exceptions import ImproperlyConfigured from django.test import SimpleTestCase, override_settings from .cases import StaticFilesTestCase from .settings import TEST_ROOT class TestFinders: """ Base finder test mixin. On Windows, sometimes the case of the path we ask the finders for and the path(s) they find can differ. Compare them using os.path.normcase() to avoid false negatives. """ def test_find_first(self): src, dst = self.find_first found = self.finder.find(src) self.assertEqual(os.path.normcase(found), os.path.normcase(dst)) def test_find_all(self): src, dst = self.find_all found = self.finder.find(src, find_all=True) found = [os.path.normcase(f) for f in found] dst = [os.path.normcase(d) for d in dst] self.assertEqual(found, dst) class TestFileSystemFinder(TestFinders, StaticFilesTestCase): """ Test FileSystemFinder. """ def setUp(self): super().setUp() self.finder = finders.FileSystemFinder() test_file_path = os.path.join( TEST_ROOT, "project", "documents", "test", "file.txt" ) self.find_first = (os.path.join("test", "file.txt"), test_file_path) self.find_all = (os.path.join("test", "file.txt"), [test_file_path]) class TestAppDirectoriesFinder(TestFinders, StaticFilesTestCase): """ Test AppDirectoriesFinder. """ def setUp(self): super().setUp() self.finder = finders.AppDirectoriesFinder() test_file_path = os.path.join( TEST_ROOT, "apps", "test", "static", "test", "file1.txt" ) self.find_first = (os.path.join("test", "file1.txt"), test_file_path) self.find_all = (os.path.join("test", "file1.txt"), [test_file_path]) class TestDefaultStorageFinder(TestFinders, StaticFilesTestCase): """ Test DefaultStorageFinder. """ def setUp(self): super().setUp() self.finder = finders.DefaultStorageFinder( storage=storage.StaticFilesStorage(location=settings.MEDIA_ROOT) ) test_file_path = os.path.join(settings.MEDIA_ROOT, "media-file.txt") self.find_first = ("media-file.txt", test_file_path) self.find_all = ("media-file.txt", [test_file_path]) @override_settings( STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "documents")], ) class TestMiscFinder(SimpleTestCase): """ A few misc finder tests. """ def test_get_finder(self): self.assertIsInstance( finders.get_finder("django.contrib.staticfiles.finders.FileSystemFinder"), finders.FileSystemFinder, ) def test_get_finder_bad_classname(self): with self.assertRaises(ImportError): finders.get_finder("django.contrib.staticfiles.finders.FooBarFinder") def test_get_finder_bad_module(self): with self.assertRaises(ImportError): finders.get_finder("foo.bar.FooBarFinder") def test_cache(self): finders.get_finder.cache_clear() for n in range(10): finders.get_finder("django.contrib.staticfiles.finders.FileSystemFinder") cache_info = finders.get_finder.cache_info() self.assertEqual(cache_info.hits, 9) self.assertEqual(cache_info.currsize, 1) def test_searched_locations(self): finders.find("spam") self.assertEqual( finders.searched_locations, [os.path.join(TEST_ROOT, "project", "documents")], ) def test_searched_locations_find_all(self): finders.find("spam", find_all=True) self.assertEqual( finders.searched_locations, [os.path.join(TEST_ROOT, "project", "documents")], ) @override_settings(MEDIA_ROOT="") def test_location_empty(self): msg = ( "The storage backend of the staticfiles finder " "<class 'django.contrib.staticfiles.finders.DefaultStorageFinder'> " "doesn't have a valid location." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): finders.DefaultStorageFinder()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/cases.py
tests/staticfiles_tests/cases.py
import os import shutil import tempfile from django.conf import settings from django.core.management import call_command from django.template import Context, Template from django.test import SimpleTestCase, override_settings from .settings import TEST_SETTINGS class BaseStaticFilesMixin: """ Test case with a couple utility assertions. """ def assertFileContains(self, filepath, text): self.assertIn( text, self._get_file(filepath), "'%s' not in '%s'" % (text, filepath), ) def assertFileNotFound(self, filepath): with self.assertRaises(OSError): self._get_file(filepath) def render_template(self, template, **kwargs): if isinstance(template, str): template = Template(template) return template.render(Context(**kwargs)).strip() def static_template_snippet(self, path, asvar=False): if asvar: return ( "{%% load static from static %%}{%% static '%s' as var %%}{{ var }}" % path ) return "{%% load static from static %%}{%% static '%s' %%}" % path def assertStaticRenders(self, path, result, asvar=False, **kwargs): template = self.static_template_snippet(path, asvar) self.assertEqual(self.render_template(template, **kwargs), result) def assertStaticRaises(self, exc, path, result, asvar=False, **kwargs): with self.assertRaises(exc): self.assertStaticRenders(path, result, **kwargs) @override_settings(**TEST_SETTINGS) class StaticFilesTestCase(BaseStaticFilesMixin, SimpleTestCase): pass @override_settings(**TEST_SETTINGS) class CollectionTestCase(BaseStaticFilesMixin, SimpleTestCase): """ Tests shared by all file finding features (collectstatic, findstatic, and static serve view). This relies on the asserts defined in BaseStaticFilesTestCase, but is separated because some test cases need those asserts without all these tests. """ run_collectstatic_in_setUp = True def setUp(self): super().setUp() temp_dir = self.mkdtemp() # Override the STATIC_ROOT for all tests from setUp to tearDown # rather than as a context manager patched_settings = self.settings(STATIC_ROOT=temp_dir) patched_settings.enable() if self.run_collectstatic_in_setUp: self.run_collectstatic() # Same comment as in runtests.teardown. self.addCleanup(shutil.rmtree, temp_dir) self.addCleanup(patched_settings.disable) def mkdtemp(self): return tempfile.mkdtemp() def run_collectstatic(self, *, verbosity=0, **kwargs): call_command( "collectstatic", interactive=False, verbosity=verbosity, ignore_patterns=["*.ignoreme"], **kwargs, ) def _get_file(self, filepath): assert filepath, "filepath is empty." filepath = os.path.join(settings.STATIC_ROOT, filepath) with open(filepath, encoding="utf-8") as f: return f.read() class TestDefaults: """ A few standard test cases. """ def test_staticfiles_dirs(self): """ Can find a file in a STATICFILES_DIRS directory. """ self.assertFileContains("test.txt", "Can we find") self.assertFileContains(os.path.join("prefix", "test.txt"), "Prefix") def test_staticfiles_dirs_subdir(self): """ Can find a file in a subdirectory of a STATICFILES_DIRS directory. """ self.assertFileContains("subdir/test.txt", "Can we find") def test_staticfiles_dirs_priority(self): """ File in STATICFILES_DIRS has priority over file in app. """ self.assertFileContains("test/file.txt", "STATICFILES_DIRS") def test_app_files(self): """ Can find a file in an app static/ directory. """ self.assertFileContains("test/file1.txt", "file1 in the app dir") def test_nonascii_filenames(self): """ Can find a file with non-ASCII character in an app static/ directory. """ self.assertFileContains("test/⊗.txt", "⊗ in the app dir") def test_camelcase_filenames(self): """ Can find a file with capital letters. """ self.assertFileContains("test/camelCase.txt", "camelCase") def test_filename_with_percent_sign(self): self.assertFileContains("test/%2F.txt", "%2F content")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/storage.py
tests/staticfiles_tests/storage.py
import os from datetime import UTC, datetime, timedelta from django.conf import settings from django.contrib.staticfiles.storage import ManifestStaticFilesStorage from django.core.files import storage class DummyStorage(storage.Storage): """ A storage class that implements get_modified_time() but raises NotImplementedError for path(). """ def _save(self, name, content): return "dummy" def delete(self, name): pass def exists(self, name): pass def get_modified_time(self, name): return datetime(1970, 1, 1, tzinfo=UTC) class PathNotImplementedStorage(storage.Storage): def _save(self, name, content): return "dummy" def _path(self, name): return os.path.join(settings.STATIC_ROOT, name) def exists(self, name): return os.path.exists(self._path(name)) def listdir(self, path): path = self._path(path) directories, files = [], [] with os.scandir(path) as entries: for entry in entries: if entry.is_dir(): directories.append(entry.name) else: files.append(entry.name) return directories, files def delete(self, name): name = self._path(name) try: os.remove(name) except FileNotFoundError: pass def path(self, name): raise NotImplementedError class NeverCopyRemoteStorage(PathNotImplementedStorage): """ Return a future modified time for all files so that nothing is collected. """ def get_modified_time(self, name): return datetime.now() + timedelta(days=30) class QueryStringStorage(storage.Storage): def url(self, path): return path + "?a=b&c=d" class SimpleStorage(ManifestStaticFilesStorage): def file_hash(self, name, content=None): return "deploy12345" class ExtraPatternsStorage(ManifestStaticFilesStorage): """ A storage class to test pattern substitutions with more than one pattern entry. The added pattern rewrites strings like "url(...)" to JS_URL("..."). """ patterns = tuple(ManifestStaticFilesStorage.patterns) + ( ( "*.js", ( ( r"""(?P<matched>url\(['"]{0,1}\s*(?P<url>.*?)["']{0,1}\))""", 'JS_URL("%(url)s")', ), ), ), ) class NoneHashStorage(ManifestStaticFilesStorage): def file_hash(self, name, content=None): return None class NoPostProcessReplacedPathStorage(ManifestStaticFilesStorage): max_post_process_passes = 0
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/test_forms.py
tests/staticfiles_tests/test_forms.py
from urllib.parse import urljoin from django.conf import STATICFILES_STORAGE_ALIAS from django.contrib.staticfiles import storage from django.forms import Media from django.templatetags.static import static from django.test import SimpleTestCase, override_settings class StaticTestStorage(storage.StaticFilesStorage): def url(self, name): return urljoin("https://example.com/assets/", name) @override_settings( INSTALLED_APPS=("django.contrib.staticfiles",), STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.test_forms.StaticTestStorage", "OPTIONS": {"location": "http://media.example.com/static/"}, } }, ) class StaticFilesFormsMediaTestCase(SimpleTestCase): def test_absolute_url(self): m = Media( css={"all": ("path/to/css1", "/path/to/css2")}, js=( "/path/to/js1", "http://media.other.com/path/to/js2", "https://secure.other.com/path/to/js3", static("relative/path/to/js4"), ), ) self.assertEqual( str(m), '<link href="https://example.com/assets/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>\n' '<script src="https://example.com/assets/relative/path/to/js4"></script>', )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/test_utils.py
tests/staticfiles_tests/test_utils.py
from django.contrib.staticfiles.utils import check_settings from django.core.exceptions import ImproperlyConfigured from django.test import SimpleTestCase, override_settings class CheckSettingsTests(SimpleTestCase): @override_settings(DEBUG=True, MEDIA_URL="static/media/", STATIC_URL="static/") def test_media_url_in_static_url(self): msg = "runserver can't serve media if MEDIA_URL is within STATIC_URL." with self.assertRaisesMessage(ImproperlyConfigured, msg): check_settings() with self.settings(DEBUG=False): # Check disabled if DEBUG=False. check_settings()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/test_views.py
tests/staticfiles_tests/test_views.py
import posixpath from urllib.parse import quote from django.conf import settings from django.test import override_settings from .cases import StaticFilesTestCase, TestDefaults @override_settings(ROOT_URLCONF="staticfiles_tests.urls.default") class TestServeStatic(StaticFilesTestCase): """ Test static asset serving view. """ def _response(self, filepath): return self.client.get(quote(posixpath.join(settings.STATIC_URL, filepath))) def assertFileContains(self, filepath, text): self.assertContains(self._response(filepath), text) def assertFileNotFound(self, filepath): self.assertEqual(self._response(filepath).status_code, 404) @override_settings(DEBUG=False) class TestServeDisabled(TestServeStatic): """ Test serving static files disabled when DEBUG is False. """ def test_disabled_serving(self): self.assertFileNotFound("test.txt") @override_settings(DEBUG=True) class TestServeStaticWithDefaultURL(TestDefaults, TestServeStatic): """ Test static asset serving view with manually configured URLconf. """ @override_settings(DEBUG=True, ROOT_URLCONF="staticfiles_tests.urls.helper") class TestServeStaticWithURLHelper(TestDefaults, TestServeStatic): """ Test static asset serving view with staticfiles_urlpatterns helper. """
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/test_templatetags.py
tests/staticfiles_tests/test_templatetags.py
from django.conf import STATICFILES_STORAGE_ALIAS from django.test import override_settings from .cases import StaticFilesTestCase class TestTemplateTag(StaticFilesTestCase): def test_template_tag(self): self.assertStaticRenders("does/not/exist.png", "/static/does/not/exist.png") self.assertStaticRenders("testfile.txt", "/static/testfile.txt") self.assertStaticRenders( "special?chars&quoted.html", "/static/special%3Fchars%26quoted.html" ) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.QueryStringStorage" }, } ) def test_template_tag_escapes(self): """ Storage.url() should return an encoded path and might be overridden to also include a querystring. {% static %} escapes the URL to avoid raw '&', for example. """ self.assertStaticRenders("a.html", "a.html?a=b&amp;c=d") self.assertStaticRenders("a.html", "a.html?a=b&c=d", autoescape=False)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/test_management.py
tests/staticfiles_tests/test_management.py
import datetime import os import shutil import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from admin_scripts.tests import AdminScriptTestCase from django.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles import storage from django.contrib.staticfiles.management.commands import collectstatic, runserver from django.core.exceptions import ImproperlyConfigured from django.core.management import CommandError, call_command from django.core.management.base import SystemCheckError from django.test import RequestFactory, override_settings from django.test.utils import extend_sys_path from django.utils._os import symlinks_supported from django.utils.functional import empty from .cases import CollectionTestCase, StaticFilesTestCase, TestDefaults from .settings import TEST_ROOT, TEST_SETTINGS from .storage import DummyStorage class TestNoFilesCreated: def test_no_files_created(self): """ Make sure no files were create in the destination directory. """ self.assertEqual(os.listdir(settings.STATIC_ROOT), []) class TestRunserver(StaticFilesTestCase): @override_settings(MIDDLEWARE=["django.middleware.common.CommonMiddleware"]) def test_middleware_loaded_only_once(self): command = runserver.Command() with mock.patch("django.middleware.common.CommonMiddleware") as mocked: command.get_handler(use_static_handler=True, insecure_serving=True) self.assertEqual(mocked.call_count, 1) def test_404_response(self): command = runserver.Command() handler = command.get_handler(use_static_handler=True, insecure_serving=True) missing_static_file = os.path.join(settings.STATIC_URL, "unknown.css") req = RequestFactory().get(missing_static_file) with override_settings(DEBUG=False): response = handler.get_response(req) self.assertEqual(response.status_code, 404) with override_settings(DEBUG=True): response = handler.get_response(req) self.assertEqual(response.status_code, 404) class TestFindStatic(TestDefaults, CollectionTestCase): """ Test ``findstatic`` management command. """ def _get_file(self, filepath): path = call_command( "findstatic", filepath, all=False, verbosity=0, stdout=StringIO() ) with open(path, encoding="utf-8") as f: return f.read() def test_all_files(self): """ findstatic returns all candidate files if run without --first and -v1. """ result = call_command( "findstatic", "test/file.txt", verbosity=1, stdout=StringIO() ) lines = [line.strip() for line in result.split("\n")] self.assertEqual( len(lines), 3 ) # three because there is also the "Found <file> here" line self.assertIn("project", lines[1]) self.assertIn("apps", lines[2]) def test_all_files_less_verbose(self): """ findstatic returns all candidate files if run without --first and -v0. """ result = call_command( "findstatic", "test/file.txt", verbosity=0, stdout=StringIO() ) lines = [line.strip() for line in result.split("\n")] self.assertEqual(len(lines), 2) self.assertIn("project", lines[0]) self.assertIn("apps", lines[1]) def test_all_files_more_verbose(self): """ findstatic returns all candidate files if run without --first and -v2. Also, test that findstatic returns the searched locations with -v2. """ result = call_command( "findstatic", "test/file.txt", verbosity=2, stdout=StringIO() ) lines = [line.strip() for line in result.split("\n")] self.assertIn("project", lines[1]) self.assertIn("apps", lines[2]) self.assertIn("Looking in the following locations:", lines[3]) searched_locations = ", ".join(lines[4:]) # AppDirectoriesFinder searched locations self.assertIn( os.path.join("staticfiles_tests", "apps", "test", "static"), searched_locations, ) self.assertIn( os.path.join("staticfiles_tests", "apps", "no_label", "static"), searched_locations, ) # FileSystemFinder searched locations self.assertIn(TEST_SETTINGS["STATICFILES_DIRS"][1][1], searched_locations) self.assertIn(TEST_SETTINGS["STATICFILES_DIRS"][0], searched_locations) self.assertIn(str(TEST_SETTINGS["STATICFILES_DIRS"][2]), searched_locations) # DefaultStorageFinder searched locations self.assertIn( os.path.join("staticfiles_tests", "project", "site_media", "media"), searched_locations, ) def test_missing_args_message(self): msg = "Enter at least one staticfile." with self.assertRaisesMessage(CommandError, msg): call_command("findstatic") class TestConfiguration(StaticFilesTestCase): def test_location_empty(self): msg = "without having set the STATIC_ROOT setting to a filesystem path" err = StringIO() for root in ["", None]: with override_settings(STATIC_ROOT=root): with self.assertRaisesMessage(ImproperlyConfigured, msg): call_command( "collectstatic", interactive=False, verbosity=0, stderr=err ) def test_local_storage_detection_helper(self): staticfiles_storage = storage.staticfiles_storage try: storage.staticfiles_storage._wrapped = empty with self.settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": ( "django.contrib.staticfiles.storage.StaticFilesStorage" ) }, } ): command = collectstatic.Command() self.assertTrue(command.is_local_storage()) storage.staticfiles_storage._wrapped = empty with self.settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.DummyStorage" }, } ): command = collectstatic.Command() self.assertFalse(command.is_local_storage()) collectstatic.staticfiles_storage = storage.FileSystemStorage() command = collectstatic.Command() self.assertTrue(command.is_local_storage()) collectstatic.staticfiles_storage = DummyStorage() command = collectstatic.Command() self.assertFalse(command.is_local_storage()) finally: staticfiles_storage._wrapped = empty collectstatic.staticfiles_storage = staticfiles_storage storage.staticfiles_storage = staticfiles_storage @override_settings(STATICFILES_DIRS=("test")) def test_collectstatis_check(self): msg = "The STATICFILES_DIRS setting is not a tuple or list." with self.assertRaisesMessage(SystemCheckError, msg): call_command("collectstatic", skip_checks=False) class TestCollectionHelpSubcommand(AdminScriptTestCase): @override_settings(STATIC_ROOT=None) def test_missing_settings_dont_prevent_help(self): """ Even if the STATIC_ROOT setting is not set, one can still call the `manage.py help collectstatic` command. """ self.write_settings("settings.py", apps=["django.contrib.staticfiles"]) out, err = self.run_manage(["help", "collectstatic"]) self.assertNoOutput(err) class TestCollection(TestDefaults, CollectionTestCase): """ Test ``collectstatic`` management command. """ def test_ignore(self): """ -i patterns are ignored. """ self.assertFileNotFound("test/test.ignoreme") def test_common_ignore_patterns(self): """ Common ignore patterns (*~, .*, CVS) are ignored. """ self.assertFileNotFound("test/.hidden") self.assertFileNotFound("test/backup~") self.assertFileNotFound("test/CVS") def test_pathlib(self): self.assertFileContains("pathlib.txt", "pathlib") class TestCollectionPathLib(TestCollection): def mkdtemp(self): tmp_dir = super().mkdtemp() return Path(tmp_dir) class TestCollectionVerbosity(CollectionTestCase): copying_msg = "Copying " run_collectstatic_in_setUp = False post_process_msg = "Post-processed" staticfiles_copied_msg = "static files copied to" def test_verbosity_0(self): stdout = StringIO() self.run_collectstatic(verbosity=0, stdout=stdout) self.assertEqual(stdout.getvalue(), "") def test_verbosity_1(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout) output = stdout.getvalue() self.assertIn(self.staticfiles_copied_msg, output) self.assertNotIn(self.copying_msg, output) def test_verbosity_2(self): stdout = StringIO() self.run_collectstatic(verbosity=2, stdout=stdout) output = stdout.getvalue() self.assertIn(self.staticfiles_copied_msg, output) self.assertIn(self.copying_msg, output) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": ( "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" ) }, } ) def test_verbosity_1_with_post_process(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout, post_process=True) self.assertNotIn(self.post_process_msg, stdout.getvalue()) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": ( "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" ) }, } ) def test_verbosity_2_with_post_process(self): stdout = StringIO() self.run_collectstatic(verbosity=2, stdout=stdout, post_process=True) self.assertIn(self.post_process_msg, stdout.getvalue()) class TestCollectionClear(CollectionTestCase): """ Test the ``--clear`` option of the ``collectstatic`` management command. """ run_collectstatic_in_setUp = False def run_collectstatic(self, **kwargs): clear_filepath = os.path.join(settings.STATIC_ROOT, "cleared.txt") with open(clear_filepath, "w") as f: f.write("should be cleared") super().run_collectstatic(clear=True, **kwargs) def test_cleared_not_found(self): self.assertFileNotFound("cleared.txt") def test_dir_not_exists(self, **kwargs): shutil.rmtree(settings.STATIC_ROOT) super().run_collectstatic(clear=True) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.PathNotImplementedStorage" }, } ) def test_handle_path_notimplemented(self): self.run_collectstatic() self.assertFileNotFound("cleared.txt") def test_verbosity_0(self): for kwargs in [{}, {"dry_run": True}]: with self.subTest(kwargs=kwargs): stdout = StringIO() self.run_collectstatic(verbosity=0, stdout=stdout, **kwargs) self.assertEqual(stdout.getvalue(), "") def test_verbosity_1(self): for deletion_message, kwargs in [ ("Deleting", {}), ("Pretending to delete", {"dry_run": True}), ]: with self.subTest(kwargs=kwargs): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout, **kwargs) output = stdout.getvalue() self.assertIn("static file", output) self.assertIn("deleted", output) self.assertNotIn(deletion_message, output) def test_verbosity_2(self): for deletion_message, kwargs in [ ("Deleting", {}), ("Pretending to delete", {"dry_run": True}), ]: with self.subTest(kwargs=kwargs): stdout = StringIO() self.run_collectstatic(verbosity=2, stdout=stdout, **kwargs) output = stdout.getvalue() self.assertIn("static file", output) self.assertIn("deleted", output) self.assertIn(deletion_message, output) class TestInteractiveMessages(CollectionTestCase): overwrite_warning_msg = "This will overwrite existing files!" delete_warning_msg = "This will DELETE ALL FILES in this location!" files_copied_msg = "static files copied" @staticmethod def mock_input(stdout): def _input(msg): stdout.write(msg) return "yes" return _input def test_warning_when_clearing_staticdir(self): stdout = StringIO() self.run_collectstatic() with mock.patch("builtins.input", side_effect=self.mock_input(stdout)): call_command("collectstatic", interactive=True, clear=True, stdout=stdout) output = stdout.getvalue() self.assertNotIn(self.overwrite_warning_msg, output) self.assertIn(self.delete_warning_msg, output) def test_warning_when_overwriting_files_in_staticdir(self): stdout = StringIO() self.run_collectstatic() with mock.patch("builtins.input", side_effect=self.mock_input(stdout)): call_command("collectstatic", interactive=True, stdout=stdout) output = stdout.getvalue() self.assertIn(self.overwrite_warning_msg, output) self.assertNotIn(self.delete_warning_msg, output) def test_no_warning_when_staticdir_does_not_exist(self): stdout = StringIO() shutil.rmtree(settings.STATIC_ROOT) call_command("collectstatic", interactive=True, stdout=stdout) output = stdout.getvalue() self.assertNotIn(self.overwrite_warning_msg, output) self.assertNotIn(self.delete_warning_msg, output) self.assertIn(self.files_copied_msg, output) def test_no_warning_for_empty_staticdir(self): stdout = StringIO() with tempfile.TemporaryDirectory( prefix="collectstatic_empty_staticdir_test" ) as static_dir: with override_settings(STATIC_ROOT=static_dir): call_command("collectstatic", interactive=True, stdout=stdout) output = stdout.getvalue() self.assertNotIn(self.overwrite_warning_msg, output) self.assertNotIn(self.delete_warning_msg, output) self.assertIn(self.files_copied_msg, output) def test_cancelled(self): self.run_collectstatic() with mock.patch("builtins.input", side_effect=lambda _: "no"): with self.assertRaisesMessage( CommandError, "Collecting static files cancelled" ): call_command("collectstatic", interactive=True) class TestCollectionNoDefaultIgnore(TestDefaults, CollectionTestCase): """ The ``--no-default-ignore`` option of the ``collectstatic`` management command. """ def run_collectstatic(self): super().run_collectstatic(use_default_ignore_patterns=False) def test_no_common_ignore_patterns(self): """ With --no-default-ignore, common ignore patterns (*~, .*, CVS) are not ignored. """ self.assertFileContains("test/.hidden", "should be ignored") self.assertFileContains("test/backup~", "should be ignored") self.assertFileContains("test/CVS", "should be ignored") @override_settings( INSTALLED_APPS=[ "staticfiles_tests.apps.staticfiles_config.IgnorePatternsAppConfig", "staticfiles_tests.apps.test", ] ) class TestCollectionCustomIgnorePatterns(CollectionTestCase): def test_custom_ignore_patterns(self): """ A custom ignore_patterns list, ['*.css', '*/vendor/*.js'] in this case, can be specified in an AppConfig definition. """ self.assertFileNotFound("test/nonascii.css") self.assertFileContains("test/.hidden", "should be ignored") self.assertFileNotFound(os.path.join("test", "vendor", "module.js")) class TestCollectionDryRun(TestNoFilesCreated, CollectionTestCase): """ Test ``--dry-run`` option for ``collectstatic`` management command. """ def run_collectstatic(self): super().run_collectstatic(dry_run=True) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" }, } ) class TestCollectionDryRunManifestStaticFilesStorage(TestCollectionDryRun): pass class TestCollectionFilesOverride(CollectionTestCase): """ Test overriding duplicated files by ``collectstatic`` management command. Check for proper handling of apps order in installed apps even if file modification dates are in different order: 'staticfiles_test_app', 'staticfiles_tests.apps.no_label', """ def setUp(self): self.temp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.temp_dir) # get modification and access times for no_label/static/file2.txt self.orig_path = os.path.join( TEST_ROOT, "apps", "no_label", "static", "file2.txt" ) self.orig_mtime = os.path.getmtime(self.orig_path) self.orig_atime = os.path.getatime(self.orig_path) # prepare duplicate of file2.txt from a temporary app # this file will have modification time older than # no_label/static/file2.txt anyway it should be taken to STATIC_ROOT # because the temporary app is before 'no_label' app in installed apps self.temp_app_path = os.path.join(self.temp_dir, "staticfiles_test_app") self.testfile_path = os.path.join(self.temp_app_path, "static", "file2.txt") os.makedirs(self.temp_app_path) with open(os.path.join(self.temp_app_path, "__init__.py"), "w+"): pass os.makedirs(os.path.dirname(self.testfile_path)) with open(self.testfile_path, "w+") as f: f.write("duplicate of file2.txt") os.utime(self.testfile_path, (self.orig_atime - 1, self.orig_mtime - 1)) settings_with_test_app = self.modify_settings( INSTALLED_APPS={"prepend": "staticfiles_test_app"}, ) with extend_sys_path(self.temp_dir): settings_with_test_app.enable() self.addCleanup(settings_with_test_app.disable) super().setUp() def test_ordering_override(self): """ Test if collectstatic takes files in proper order """ self.assertFileContains("file2.txt", "duplicate of file2.txt") # run collectstatic again self.run_collectstatic() self.assertFileContains("file2.txt", "duplicate of file2.txt") # The collectstatic test suite already has conflicting files since both # project/test/file.txt and apps/test/static/test/file.txt are collected. To # properly test for the warning not happening unless we tell it to explicitly, # we remove the project directory and will add back a conflicting file later. @override_settings(STATICFILES_DIRS=[]) class TestCollectionOverwriteWarning(CollectionTestCase): """ Test warning in ``collectstatic`` output when a file is skipped because a previous file was already written to the same path. """ # If this string is in the collectstatic output, it means the warning we're # looking for was emitted. warning_string = "Found another file" def _collectstatic_output(self, verbosity=3, **kwargs): """ Run collectstatic, and capture and return the output. """ out = StringIO() call_command( "collectstatic", interactive=False, verbosity=verbosity, stdout=out, **kwargs, ) return out.getvalue() def test_no_warning(self): """ There isn't a warning if there isn't a duplicate destination. """ output = self._collectstatic_output(clear=True) self.assertNotIn(self.warning_string, output) def test_warning_at_verbosity_2(self): """ There is a warning when there are duplicate destinations at verbosity 2+. """ with tempfile.TemporaryDirectory() as static_dir: duplicate = os.path.join(static_dir, "test", "file.txt") os.mkdir(os.path.dirname(duplicate)) with open(duplicate, "w+") as f: f.write("duplicate of file.txt") with self.settings(STATICFILES_DIRS=[static_dir]): output = self._collectstatic_output(clear=True, verbosity=2) self.assertIn(self.warning_string, output) def test_no_warning_at_verbosity_1(self): """ There is no individual warning at verbosity 1, but summary is shown. """ with tempfile.TemporaryDirectory() as static_dir: duplicate = os.path.join(static_dir, "test", "file.txt") os.mkdir(os.path.dirname(duplicate)) with open(duplicate, "w+") as f: f.write("duplicate of file.txt") with self.settings(STATICFILES_DIRS=[static_dir]): output = self._collectstatic_output(clear=True, verbosity=1) self.assertNotIn(self.warning_string, output) self.assertIn("1 skipped due to conflict", output) def test_summary_multiple_conflicts(self): """ Summary shows correct count for multiple conflicts. """ with tempfile.TemporaryDirectory() as static_dir: duplicate1 = os.path.join(static_dir, "test", "file.txt") os.makedirs(os.path.dirname(duplicate1)) with open(duplicate1, "w+") as f: f.write("duplicate of file.txt") duplicate2 = os.path.join(static_dir, "test", "file1.txt") with open(duplicate2, "w+") as f: f.write("duplicate of file1.txt") duplicate3 = os.path.join(static_dir, "test", "nonascii.css") shutil.copy2(duplicate1, duplicate3) with self.settings(STATICFILES_DIRS=[static_dir]): output = self._collectstatic_output(clear=True, verbosity=1) self.assertIn("3 skipped due to conflict", output) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.DummyStorage" }, } ) class TestCollectionNonLocalStorage(TestNoFilesCreated, CollectionTestCase): """ Tests for a Storage that implements get_modified_time() but not path() (#15035). """ def test_storage_properties(self): # Properties of the Storage as described in the ticket. storage = DummyStorage() self.assertEqual( storage.get_modified_time("name"), datetime.datetime(1970, 1, 1, tzinfo=datetime.UTC), ) with self.assertRaisesMessage( NotImplementedError, "This backend doesn't support absolute paths." ): storage.path("name") class TestCollectionNeverCopyStorage(CollectionTestCase): @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.NeverCopyRemoteStorage" }, } ) def test_skips_newer_files_in_remote_storage(self): """ collectstatic skips newer files in a remote storage. run_collectstatic() in setUp() copies the static files, then files are always skipped after NeverCopyRemoteStorage is activated since NeverCopyRemoteStorage.get_modified_time() returns a datetime in the future to simulate an unmodified file. """ stdout = StringIO() self.run_collectstatic(stdout=stdout, verbosity=2) output = stdout.getvalue() self.assertIn("Skipping 'test.txt' (not modified)", output) @unittest.skipUnless(symlinks_supported(), "Must be able to symlink to run this test.") class TestCollectionLinks(TestDefaults, CollectionTestCase): """ Test ``--link`` option for ``collectstatic`` management command. Note that by inheriting ``TestDefaults`` we repeat all the standard file resolving tests here, to make sure using ``--link`` does not change the file-selection semantics. """ def run_collectstatic(self, clear=False, link=True, **kwargs): super().run_collectstatic(link=link, clear=clear, **kwargs) def test_links_created(self): """ With ``--link``, symbolic links are created. """ self.assertTrue(os.path.islink(os.path.join(settings.STATIC_ROOT, "test.txt"))) def test_broken_symlink(self): """ Test broken symlink gets deleted. """ path = os.path.join(settings.STATIC_ROOT, "test.txt") os.unlink(path) self.run_collectstatic() self.assertTrue(os.path.islink(path)) def test_symlinks_and_files_replaced(self): """ Running collectstatic in non-symlink mode replaces symlinks with files, while symlink mode replaces files with symlinks. """ path = os.path.join(settings.STATIC_ROOT, "test.txt") self.assertTrue(os.path.islink(path)) self.run_collectstatic(link=False) self.assertFalse(os.path.islink(path)) self.run_collectstatic(link=True) self.assertTrue(os.path.islink(path)) def test_clear_broken_symlink(self): """ With ``--clear``, broken symbolic links are deleted. """ nonexistent_file_path = os.path.join(settings.STATIC_ROOT, "nonexistent.txt") broken_symlink_path = os.path.join(settings.STATIC_ROOT, "symlink.txt") os.symlink(nonexistent_file_path, broken_symlink_path) self.run_collectstatic(clear=True) self.assertFalse(os.path.lexists(broken_symlink_path)) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.PathNotImplementedStorage" }, } ) def test_no_remote_link(self): with self.assertRaisesMessage( CommandError, "Can't symlink to a remote destination." ): self.run_collectstatic()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/settings.py
tests/staticfiles_tests/settings.py
import os.path from pathlib import Path TEST_ROOT = os.path.dirname(__file__) TEST_SETTINGS = { "MEDIA_URL": "media/", "STATIC_URL": "static/", "MEDIA_ROOT": os.path.join(TEST_ROOT, "project", "site_media", "media"), "STATIC_ROOT": os.path.join(TEST_ROOT, "project", "site_media", "static"), "STATICFILES_DIRS": [ os.path.join(TEST_ROOT, "project", "documents"), ("prefix", os.path.join(TEST_ROOT, "project", "prefixed")), Path(TEST_ROOT) / "project" / "pathlib", ], "STATICFILES_FINDERS": [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", "django.contrib.staticfiles.finders.DefaultStorageFinder", ], "INSTALLED_APPS": [ "django.contrib.staticfiles", "staticfiles_tests", "staticfiles_tests.apps.test", "staticfiles_tests.apps.no_label", ], # In particular, AuthenticationMiddleware can't be used because # contrib.auth isn't in INSTALLED_APPS. "MIDDLEWARE": [], }
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/test_liveserver.py
tests/staticfiles_tests/test_liveserver.py
""" A subset of the tests in tests/servers/tests exercising django.contrib.staticfiles.testing.StaticLiveServerTestCase instead of django.test.LiveServerTestCase. """ import os from urllib.request import urlopen from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.core.exceptions import ImproperlyConfigured from django.test import modify_settings, override_settings TEST_ROOT = os.path.dirname(__file__) TEST_SETTINGS = { "MEDIA_URL": "media/", "STATIC_URL": "static/", "MEDIA_ROOT": os.path.join(TEST_ROOT, "project", "site_media", "media"), "STATIC_ROOT": os.path.join(TEST_ROOT, "project", "site_media", "static"), } class LiveServerBase(StaticLiveServerTestCase): available_apps = [] @classmethod def setUpClass(cls): cls.enterClassContext(override_settings(**TEST_SETTINGS)) super().setUpClass() class StaticLiveServerChecks(LiveServerBase): @classmethod def setUpClass(cls): # If contrib.staticfiles isn't configured properly, the exception # should bubble up to the main thread. old_STATIC_URL = TEST_SETTINGS["STATIC_URL"] TEST_SETTINGS["STATIC_URL"] = None try: cls.raises_exception() finally: TEST_SETTINGS["STATIC_URL"] = old_STATIC_URL @classmethod def tearDownClass(cls): # skip it, as setUpClass doesn't call its parent either pass @classmethod def raises_exception(cls): try: super().setUpClass() except ImproperlyConfigured: # This raises ImproperlyConfigured("You're using the staticfiles # app without having set the required STATIC_URL setting.") pass else: raise Exception("setUpClass() should have raised an exception.") def test_test_test(self): # Intentionally empty method so that the test is picked up by the # test runner and the overridden setUpClass() method is executed. pass class StaticLiveServerView(LiveServerBase): def urlopen(self, url): return urlopen(self.live_server_url + url) # The test is going to access a static file stored in this application. @modify_settings(INSTALLED_APPS={"append": "staticfiles_tests.apps.test"}) def test_collectstatic_emulation(self): """ StaticLiveServerTestCase use of staticfiles' serve() allows it to discover app's static assets without having to collectstatic first. """ with self.urlopen("/static/test/file.txt") as f: self.assertEqual(f.read().rstrip(b"\r\n"), b"In static directory.")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/__init__.py
tests/staticfiles_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/staticfiles_tests/test_storage.py
tests/staticfiles_tests/test_storage.py
import json import os import shutil import sys import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from django.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles import finders, storage from django.contrib.staticfiles.management.commands.collectstatic import ( Command as CollectstaticCommand, ) from django.core.management import call_command from django.test import SimpleTestCase, override_settings from .cases import CollectionTestCase from .settings import TEST_ROOT def hashed_file_path(test, path): fullpath = test.render_template(test.static_template_snippet(path)) return fullpath.removeprefix(settings.STATIC_URL) class TestHashedFiles: hashed_file_path = hashed_file_path def tearDown(self): # Clear hashed files to avoid side effects among tests. storage.staticfiles_storage.hashed_files.clear() def assertPostCondition(self): """ Assert post conditions for a test are met. Must be manually called at the end of each test. """ pass def test_template_tag_return(self): self.assertStaticRaises( ValueError, "does/not/exist.png", "/static/does/not/exist.png" ) self.assertStaticRenders("test/file.txt", "/static/test/file.dad0999e4f8f.txt") self.assertStaticRenders( "test/file.txt", "/static/test/file.dad0999e4f8f.txt", asvar=True ) self.assertStaticRenders( "cached/styles.css", "/static/cached/styles.5e0040571e1a.css" ) self.assertStaticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") self.assertPostCondition() def test_template_tag_simple_content(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_ignored_completely(self): relpath = self.hashed_file_path("cached/css/ignored.css") self.assertEqual(relpath, "cached/css/ignored.55e7c226dda1.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"#foobar", content) self.assertIn(b"http:foobar", content) self.assertIn(b"https:foobar", content) self.assertIn(b"data:foobar", content) self.assertIn(b"chrome:foobar", content) self.assertIn(b"//foobar", content) self.assertIn(b"url()", content) self.assertPostCondition() def test_path_with_querystring(self): relpath = self.hashed_file_path("cached/styles.css?spam=eggs") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css?spam=eggs") with storage.staticfiles_storage.open( "cached/styles.5e0040571e1a.css" ) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_with_fragment(self): relpath = self.hashed_file_path("cached/styles.css#eggs") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css#eggs") with storage.staticfiles_storage.open( "cached/styles.5e0040571e1a.css" ) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_with_querystring_and_fragment(self): relpath = self.hashed_file_path("cached/css/fragments.css") self.assertEqual(relpath, "cached/css/fragments.7fe344dee895.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"fonts/font.b9b105392eb8.eot?#iefix", content) self.assertIn(b"fonts/font.b8d603e42714.svg#webfontIyfZbseF", content) self.assertIn( b"fonts/font.b8d603e42714.svg#path/to/../../fonts/font.svg", content ) self.assertIn( b"data:font/woff;charset=utf-8;" b"base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA", content, ) self.assertIn(b"#default#VML", content) self.assertPostCondition() def test_template_tag_absolute(self): relpath = self.hashed_file_path("cached/absolute.css") self.assertEqual(relpath, "cached/absolute.eb04def9f9a4.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/static/cached/styles.css", content) self.assertIn(b"/static/cached/styles.5e0040571e1a.css", content) self.assertNotIn(b"/static/styles_root.css", content) self.assertIn(b"/static/styles_root.401f2509a628.css", content) self.assertIn(b"/static/cached/img/relative.acae32e4532b.png", content) self.assertPostCondition() def test_template_tag_absolute_root(self): """ Like test_template_tag_absolute, but for a file in STATIC_ROOT (#26249). """ relpath = self.hashed_file_path("absolute_root.css") self.assertEqual(relpath, "absolute_root.f821df1b64f7.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/static/styles_root.css", content) self.assertIn(b"/static/styles_root.401f2509a628.css", content) self.assertPostCondition() def test_template_tag_relative(self): relpath = self.hashed_file_path("cached/relative.css") self.assertEqual(relpath, "cached/relative.c3e9e1ea6f2e.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"../cached/styles.css", content) self.assertNotIn(b'@import "styles.css"', content) self.assertNotIn(b"url(img/relative.png)", content) self.assertIn(b'url("img/relative.acae32e4532b.png")', content) self.assertIn(b"../cached/styles.5e0040571e1a.css", content) self.assertPostCondition() def test_import_replacement(self): "See #18050" relpath = self.hashed_file_path("cached/import.css") self.assertEqual(relpath, "cached/import.f53576679e5a.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b"""import url("styles.5e0040571e1a.css")""", relfile.read()) self.assertPostCondition() def test_template_tag_deep_relative(self): relpath = self.hashed_file_path("cached/css/window.css") self.assertEqual(relpath, "cached/css/window.5d5c10836967.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"url(img/window.png)", content) self.assertIn(b'url("img/window.acae32e4532b.png")', content) self.assertPostCondition() def test_template_tag_url(self): relpath = self.hashed_file_path("cached/url.css") self.assertEqual(relpath, "cached/url.902310b73412.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b"https://", relfile.read()) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "loop")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_import_loop(self): finders.get_finder.cache_clear() err = StringIO() with self.assertRaisesMessage(RuntimeError, "Max post-process passes exceeded"): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual( "Post-processing 'bar.css, foo.css' failed!\n\n", err.getvalue() ) self.assertPostCondition() def test_post_processing(self): """ post_processing behaves correctly. Files that are alterable should always be post-processed; files that aren't should be skipped. collectstatic has already been called once in setUp() for this testcase, therefore we check by verifying behavior on a second run. """ collectstatic_args = { "interactive": False, "verbosity": 0, "link": False, "clear": False, "dry_run": False, "post_process": True, "use_default_ignore_patterns": True, "ignore_patterns": ["*.ignoreme"], } collectstatic_cmd = CollectstaticCommand() collectstatic_cmd.set_options(**collectstatic_args) stats = collectstatic_cmd.collect() self.assertIn( os.path.join("cached", "css", "window.css"), stats["post_processed"] ) self.assertIn( os.path.join("cached", "css", "img", "window.png"), stats["unmodified"] ) self.assertIn(os.path.join("test", "nonascii.css"), stats["post_processed"]) # No file should be yielded twice. self.assertCountEqual(stats["post_processed"], set(stats["post_processed"])) self.assertPostCondition() def test_css_import_case_insensitive(self): relpath = self.hashed_file_path("cached/styles_insensitive.css") self.assertEqual(relpath, "cached/styles_insensitive.3fa427592a53.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_css_data_uri_with_nested_url(self): relpath = self.hashed_file_path("cached/data_uri_with_nested_url.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b'url("data:image/svg+xml,url(%23b) url(%23c)")', content) self.assertPostCondition() def test_css_source_map(self): relpath = self.hashed_file_path("cached/source_map.css") self.assertEqual(relpath, "cached/source_map.b2fceaf426aa.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/*# sourceMappingURL=source_map.css.map*/", content) self.assertIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_tabs(self): relpath = self.hashed_file_path("cached/source_map_tabs.css") self.assertEqual(relpath, "cached/source_map_tabs.b2fceaf426aa.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/*#\tsourceMappingURL=source_map.css.map\t*/", content) self.assertIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_sensitive(self): relpath = self.hashed_file_path("cached/source_map_sensitive.css") self.assertEqual(relpath, "cached/source_map_sensitive.456683f2106f.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"/*# sOuRcEMaPpInGURL=source_map.css.map */", content) self.assertNotIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_data_uri(self): relpath = self.hashed_file_path("cached/source_map_data_uri.css") self.assertEqual(relpath, "cached/source_map_data_uri.3166be10260d.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() source_map_data_uri = ( b"/*# sourceMappingURL=data:application/json;charset=utf8;base64," b"eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMv*/" ) self.assertIn(source_map_data_uri, content) self.assertPostCondition() def test_js_source_map(self): relpath = self.hashed_file_path("cached/source_map.js") self.assertEqual(relpath, "cached/source_map.cd45b8534a87.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"//# sourceMappingURL=source_map.js.map", content) self.assertIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_trailing_whitespace(self): relpath = self.hashed_file_path("cached/source_map_trailing_whitespace.js") self.assertEqual( relpath, "cached/source_map_trailing_whitespace.cd45b8534a87.js" ) with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"//# sourceMappingURL=source_map.js.map\t ", content) self.assertIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_sensitive(self): relpath = self.hashed_file_path("cached/source_map_sensitive.js") self.assertEqual(relpath, "cached/source_map_sensitive.5da96fdd3cb3.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"//# sOuRcEMaPpInGURL=source_map.js.map", content) self.assertNotIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_data_uri(self): relpath = self.hashed_file_path("cached/source_map_data_uri.js") self.assertEqual(relpath, "cached/source_map_data_uri.a68d23cbf6dd.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() source_map_data_uri = ( b"//# sourceMappingURL=data:application/json;charset=utf8;base64," b"eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMv" ) self.assertIn(source_map_data_uri, content) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "faulty")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_post_processing_failure(self): """ post_processing indicates the origin of the error when it fails. """ finders.get_finder.cache_clear() err = StringIO() with self.assertRaises(Exception): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'faulty.css' failed!\n\n", err.getvalue()) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "nonutf8")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_post_processing_nonutf8(self): finders.get_finder.cache_clear() err = StringIO() with self.assertRaises(UnicodeDecodeError): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'nonutf8.css' failed!\n\n", err.getvalue()) self.assertPostCondition() @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.ExtraPatternsStorage", }, } ) class TestExtraPatternsStorage(CollectionTestCase): def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference super().setUp() def cached_file_path(self, path): fullpath = self.render_template(self.static_template_snippet(path)) return fullpath.replace(settings.STATIC_URL, "") def test_multi_extension_patterns(self): """ With storage classes having several file extension patterns, only the files matching a specific file pattern should be affected by the substitution (#19670). """ # CSS files shouldn't be touched by JS patterns. relpath = self.cached_file_path("cached/import.css") self.assertEqual(relpath, "cached/import.f53576679e5a.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b'import url("styles.5e0040571e1a.css")', relfile.read()) # Confirm JS patterns have been applied to JS files. relpath = self.cached_file_path("cached/test.js") self.assertEqual(relpath, "cached/test.388d7a790d46.js") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b'JS_URL("import.f53576679e5a.css")', relfile.read()) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, } ) class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase): """ Tests for the Cache busting storage """ def setUp(self): super().setUp() temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, "test")) self._clear_filename = os.path.join(temp_dir, "test", "cleared.txt") with open(self._clear_filename, "w") as f: f.write("to be deleted in one test") patched_settings = self.settings( STATICFILES_DIRS=settings.STATICFILES_DIRS + [temp_dir], ) patched_settings.enable() self.addCleanup(patched_settings.disable) self.addCleanup(shutil.rmtree, temp_dir) self._manifest_strict = storage.staticfiles_storage.manifest_strict def tearDown(self): if os.path.exists(self._clear_filename): os.unlink(self._clear_filename) storage.staticfiles_storage.manifest_strict = self._manifest_strict super().tearDown() def assertPostCondition(self): hashed_files = storage.staticfiles_storage.hashed_files # The in-memory version of the manifest matches the one on disk # since a properly created manifest should cover all filenames. if hashed_files: manifest, _ = storage.staticfiles_storage.load_manifest() self.assertEqual(hashed_files, manifest) def test_manifest_exists(self): filename = storage.staticfiles_storage.manifest_name path = storage.staticfiles_storage.path(filename) self.assertTrue(os.path.exists(path)) def test_manifest_does_not_exist(self): storage.staticfiles_storage.manifest_name = "does.not.exist.json" self.assertIsNone(storage.staticfiles_storage.read_manifest()) def test_manifest_does_not_ignore_permission_error(self): with mock.patch("builtins.open", side_effect=PermissionError): with self.assertRaises(PermissionError): storage.staticfiles_storage.read_manifest() def test_loaded_cache(self): self.assertNotEqual(storage.staticfiles_storage.hashed_files, {}) manifest_content = storage.staticfiles_storage.read_manifest() self.assertIn( '"version": "%s"' % storage.staticfiles_storage.manifest_version, manifest_content, ) def test_parse_cache(self): hashed_files = storage.staticfiles_storage.hashed_files manifest, _ = storage.staticfiles_storage.load_manifest() self.assertEqual(hashed_files, manifest) def test_clear_empties_manifest(self): cleared_file_name = storage.staticfiles_storage.clean_name( os.path.join("test", "cleared.txt") ) # collect the additional file self.run_collectstatic() hashed_files = storage.staticfiles_storage.hashed_files self.assertIn(cleared_file_name, hashed_files) manifest_content, _ = storage.staticfiles_storage.load_manifest() self.assertIn(cleared_file_name, manifest_content) original_path = storage.staticfiles_storage.path(cleared_file_name) self.assertTrue(os.path.exists(original_path)) # delete the original file form the app, collect with clear os.unlink(self._clear_filename) self.run_collectstatic(clear=True) self.assertFileNotFound(original_path) hashed_files = storage.staticfiles_storage.hashed_files self.assertNotIn(cleared_file_name, hashed_files) manifest_content, _ = storage.staticfiles_storage.load_manifest() self.assertNotIn(cleared_file_name, manifest_content) def test_missing_entry(self): missing_file_name = "cached/missing.css" configured_storage = storage.staticfiles_storage self.assertNotIn(missing_file_name, configured_storage.hashed_files) # File name not found in manifest with self.assertRaisesMessage( ValueError, "Missing staticfiles manifest entry for '%s'" % missing_file_name, ): self.hashed_file_path(missing_file_name) configured_storage.manifest_strict = False # File doesn't exist on disk err_msg = "The file '%s' could not be found with %r." % ( missing_file_name, configured_storage._wrapped, ) with self.assertRaisesMessage(ValueError, err_msg): self.hashed_file_path(missing_file_name) content = StringIO() content.write("Found") configured_storage.save(missing_file_name, content) # File exists on disk self.hashed_file_path(missing_file_name) def test_intermediate_files(self): cached_files = os.listdir(os.path.join(settings.STATIC_ROOT, "cached")) # Intermediate files shouldn't be created for reference. self.assertEqual( len( [ cached_file for cached_file in cached_files if cached_file.startswith("relative.") ] ), 2, ) def test_manifest_hash(self): # Collect the additional file. self.run_collectstatic() _, manifest_hash_orig = storage.staticfiles_storage.load_manifest() self.assertNotEqual(manifest_hash_orig, "") self.assertEqual(storage.staticfiles_storage.manifest_hash, manifest_hash_orig) # Saving doesn't change the hash. storage.staticfiles_storage.save_manifest() self.assertEqual(storage.staticfiles_storage.manifest_hash, manifest_hash_orig) # Delete the original file from the app, collect with clear. os.unlink(self._clear_filename) self.run_collectstatic(clear=True) # Hash is changed. _, manifest_hash = storage.staticfiles_storage.load_manifest() self.assertNotEqual(manifest_hash, manifest_hash_orig) def test_manifest_hash_v1(self): storage.staticfiles_storage.manifest_name = "staticfiles_v1.json" manifest_content, manifest_hash = storage.staticfiles_storage.load_manifest() self.assertEqual(manifest_hash, "") self.assertEqual(manifest_content, {"dummy.txt": "dummy.txt"}) def test_manifest_file_consistent_content(self): original_manifest_content = storage.staticfiles_storage.read_manifest() hashed_files = storage.staticfiles_storage.hashed_files # Force a change in the order of the hashed files. with mock.patch.object( storage.staticfiles_storage, "hashed_files", dict(reversed(hashed_files.items())), ): storage.staticfiles_storage.save_manifest() manifest_file_content = storage.staticfiles_storage.read_manifest() # The manifest file content should not change. self.assertEqual(original_manifest_content, manifest_file_content) @override_settings( STATIC_URL="/", STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, }, ) class TestCollectionManifestStorageStaticUrlSlash(CollectionTestCase): run_collectstatic_in_setUp = False hashed_file_path = hashed_file_path def test_protocol_relative_url_ignored(self): with override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "static_url_slash")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ): self.run_collectstatic() relpath = self.hashed_file_path("ignored.css") self.assertEqual(relpath, "ignored.61707f5f4942.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"//foobar", content) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.NoneHashStorage", }, } ) class TestCollectionNoneHashStorage(CollectionTestCase): hashed_file_path = hashed_file_path def test_hashed_name(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.css") @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.NoPostProcessReplacedPathStorage", }, } ) class TestCollectionNoPostProcessReplacedPaths(CollectionTestCase): run_collectstatic_in_setUp = False def test_collectstatistic_no_post_process_replaced_paths(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout) self.assertIn("post-processed", stdout.getvalue()) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.SimpleStorage", }, } ) class TestCollectionSimpleStorage(CollectionTestCase): hashed_file_path = hashed_file_path def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference super().setUp() def test_template_tag_return(self): self.assertStaticRaises( ValueError, "does/not/exist.png", "/static/does/not/exist.png" ) self.assertStaticRenders("test/file.txt", "/static/test/file.deploy12345.txt") self.assertStaticRenders( "cached/styles.css", "/static/cached/styles.deploy12345.css" ) self.assertStaticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") def test_template_tag_simple_content(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.deploy12345.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.deploy12345.css", content) class JSModuleImportAggregationManifestStorage(storage.ManifestStaticFilesStorage): support_js_module_import_aggregation = True @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": ( "staticfiles_tests.test_storage." "JSModuleImportAggregationManifestStorage" ), }, } ) class TestCollectionJSModuleImportAggregationManifestStorage(CollectionTestCase): hashed_file_path = hashed_file_path def test_module_import(self): relpath = self.hashed_file_path("cached/module.js") self.assertEqual(relpath, "cached/module.4326210cf0bd.js") tests = [ # Relative imports. b'import testConst from "./module_test.477bbebe77f0.js";', b'import relativeModule from "../nested/js/nested.866475c46bb4.js";', b'import { firstConst, secondConst } from "./module_test.477bbebe77f0.js";', # Absolute import. b'import rootConst from "/static/absolute_root.5586327fe78c.js";', # Dynamic import. b'const dynamicModule = import("./module_test.477bbebe77f0.js");', # Creating a module object. b'import * as NewModule from "./module_test.477bbebe77f0.js";', # Creating a minified module object. b'import*as m from "./module_test.477bbebe77f0.js";', b'import* as m from "./module_test.477bbebe77f0.js";', b'import *as m from "./module_test.477bbebe77f0.js";', b'import* as m from "./module_test.477bbebe77f0.js";', # Aliases. b'import { testConst as alias } from "./module_test.477bbebe77f0.js";', b"import {\n" b" firstVar1 as firstVarAlias,\n" b" $second_var_2 as secondVarAlias\n" b'} from "./module_test.477bbebe77f0.js";', ] with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() for module_import in tests: with self.subTest(module_import=module_import): self.assertIn(module_import, content) def test_aggregating_modules(self): relpath = self.hashed_file_path("cached/module.js") self.assertEqual(relpath, "cached/module.4326210cf0bd.js") tests = [ b'export * from "./module_test.477bbebe77f0.js";', b'export { testConst } from "./module_test.477bbebe77f0.js";', b"export {\n" b" firstVar as firstVarAlias,\n" b" secondVar as secondVarAlias\n" b'} from "./module_test.477bbebe77f0.js";', ] with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() for module_import in tests: with self.subTest(module_import=module_import): self.assertIn(module_import, content) class CustomManifestStorage(storage.ManifestStaticFilesStorage): def __init__(self, *args, manifest_storage=None, **kwargs): manifest_storage = storage.StaticFilesStorage( location=kwargs.pop("manifest_location"), ) super().__init__(*args, manifest_storage=manifest_storage, **kwargs) class TestCustomManifestStorage(SimpleTestCase): def setUp(self): manifest_path = Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, manifest_path) self.staticfiles_storage = CustomManifestStorage( manifest_location=manifest_path, ) self.manifest_file = manifest_path / self.staticfiles_storage.manifest_name # Manifest without paths. self.manifest = {"version": self.staticfiles_storage.manifest_version} with self.manifest_file.open("w") as manifest_file: json.dump(self.manifest, manifest_file) def test_read_manifest(self): self.assertEqual( self.staticfiles_storage.read_manifest(), json.dumps(self.manifest), ) def test_read_manifest_nonexistent(self): os.remove(self.manifest_file) self.assertIsNone(self.staticfiles_storage.read_manifest()) def test_save_manifest_override(self): self.assertIs(self.manifest_file.exists(), True) self.staticfiles_storage.save_manifest() self.assertIs(self.manifest_file.exists(), True) new_manifest = json.loads(self.staticfiles_storage.read_manifest()) self.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) def test_save_manifest_create(self):
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/test_handlers.py
tests/staticfiles_tests/test_handlers.py
from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler from django.core.handlers.asgi import ASGIHandler from django.test import AsyncRequestFactory from .cases import StaticFilesTestCase class MockApplication: """ASGI application that returns a string indicating that it was called.""" async def __call__(self, scope, receive, send): return "Application called" class TestASGIStaticFilesHandler(StaticFilesTestCase): async_request_factory = AsyncRequestFactory() async def test_get_async_response(self): request = self.async_request_factory.get("/static/test/file.txt") handler = ASGIStaticFilesHandler(ASGIHandler()) response = await handler.get_response_async(request) response.close() self.assertEqual(response.status_code, 200) async def test_get_async_response_not_found(self): request = self.async_request_factory.get("/static/test/not-found.txt") handler = ASGIStaticFilesHandler(ASGIHandler()) response = await handler.get_response_async(request) self.assertEqual(response.status_code, 404) async def test_non_http_requests_passed_to_the_wrapped_application(self): tests = [ "/static/path.txt", "/non-static/path.txt", ] for path in tests: with self.subTest(path=path): scope = {"type": "websocket", "path": path} handler = ASGIStaticFilesHandler(MockApplication()) response = await handler(scope, None, None) self.assertEqual(response, "Application called")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/apps/staticfiles_config.py
tests/staticfiles_tests/apps/staticfiles_config.py
from django.contrib.staticfiles.apps import StaticFilesConfig class IgnorePatternsAppConfig(StaticFilesConfig): ignore_patterns = ["*.css", "*/vendor/*.js"]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/apps/__init__.py
tests/staticfiles_tests/apps/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/apps/test/__init__.py
tests/staticfiles_tests/apps/test/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/apps/no_label/__init__.py
tests/staticfiles_tests/apps/no_label/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/urls/helper.py
tests/staticfiles_tests/urls/helper.py
from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = staticfiles_urlpatterns()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/urls/default.py
tests/staticfiles_tests/urls/default.py
from django.contrib.staticfiles import views from django.urls import re_path urlpatterns = [ re_path("^static/(?P<path>.*)$", views.serve), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/staticfiles_tests/urls/__init__.py
tests/staticfiles_tests/urls/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/xor_lookups/models.py
tests/xor_lookups/models.py
from django.db import models class Number(models.Model): num = models.IntegerField() def __str__(self): return str(self.num)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/xor_lookups/__init__.py
tests/xor_lookups/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/xor_lookups/tests.py
tests/xor_lookups/tests.py
from django.db.models import Q from django.test import TestCase from .models import Number class XorLookupsTests(TestCase): @classmethod def setUpTestData(cls): cls.numbers = [Number.objects.create(num=i) for i in range(10)] def test_filter(self): self.assertCountEqual( Number.objects.filter(num__lte=7) ^ Number.objects.filter(num__gte=3), self.numbers[:3] + self.numbers[8:], ) self.assertCountEqual( Number.objects.filter(Q(num__lte=7) ^ Q(num__gte=3)), self.numbers[:3] + self.numbers[8:], ) def test_filter_multiple(self): qs = Number.objects.filter( Q(num__gte=1) ^ Q(num__gte=3) ^ Q(num__gte=5) ^ Q(num__gte=7) ^ Q(num__gte=9) ) self.assertCountEqual( qs, self.numbers[1:3] + self.numbers[5:7] + self.numbers[9:], ) self.assertCountEqual( qs.values_list("num", flat=True), [ i for i in range(10) if (i >= 1) ^ (i >= 3) ^ (i >= 5) ^ (i >= 7) ^ (i >= 9) ], ) def test_filter_negated(self): self.assertCountEqual( Number.objects.filter(Q(num__lte=7) ^ ~Q(num__lt=3)), self.numbers[:3] + self.numbers[8:], ) self.assertCountEqual( Number.objects.filter(~Q(num__gt=7) ^ ~Q(num__lt=3)), self.numbers[:3] + self.numbers[8:], ) self.assertCountEqual( Number.objects.filter(Q(num__lte=7) ^ ~Q(num__lt=3) ^ Q(num__lte=1)), [self.numbers[2]] + self.numbers[8:], ) self.assertCountEqual( Number.objects.filter(~(Q(num__lte=7) ^ ~Q(num__lt=3) ^ Q(num__lte=1))), self.numbers[:2] + self.numbers[3:8], ) def test_exclude(self): self.assertCountEqual( Number.objects.exclude(Q(num__lte=7) ^ Q(num__gte=3)), self.numbers[3:8], ) def test_stages(self): numbers = Number.objects.all() self.assertSequenceEqual( numbers.filter(num__gte=0) ^ numbers.filter(num__lte=11), [], ) self.assertSequenceEqual( numbers.filter(num__gt=0) ^ numbers.filter(num__lt=11), [self.numbers[0]], ) def test_pk_q(self): self.assertCountEqual( Number.objects.filter(Q(pk=self.numbers[0].pk) ^ Q(pk=self.numbers[1].pk)), self.numbers[:2], ) def test_empty_in(self): self.assertCountEqual( Number.objects.filter(Q(pk__in=[]) ^ Q(num__gte=5)), self.numbers[5:], )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_indexes/models.py
tests/model_indexes/models.py
from django.db import models class Book(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) pages = models.IntegerField(db_column="page_count") shortcut = models.CharField(max_length=50, db_tablespace="idx_tbls") isbn = models.CharField(max_length=50, db_tablespace="idx_tbls") barcode = models.CharField(max_length=31) class Meta: indexes = [ models.Index(fields=["title"]), models.Index(fields=["isbn", "id"]), models.Index( fields=["barcode"], name="%(app_label)s_%(class)s_barcode_idx" ), ] class AbstractModel(models.Model): name = models.CharField(max_length=50) shortcut = models.CharField(max_length=3) class Meta: abstract = True indexes = [ models.Index(fields=["name"]), models.Index(fields=["shortcut"], name="%(app_label)s_%(class)s_idx"), ] class ChildModel1(AbstractModel): pass class ChildModel2(AbstractModel): pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_indexes/__init__.py
tests/model_indexes/__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_indexes/tests.py
tests/model_indexes/tests.py
from unittest import mock from django.conf import settings from django.db import connection, models from django.db.models.functions import Lower, Upper from django.test import SimpleTestCase, TestCase, override_settings, skipUnlessDBFeature from django.test.utils import isolate_apps from .models import Book, ChildModel1, ChildModel2 class SimpleIndexesTests(SimpleTestCase): def test_suffix(self): self.assertEqual(models.Index.suffix, "idx") def test_repr(self): index = models.Index(fields=["title"]) named_index = models.Index(fields=["title"], name="title_idx") multi_col_index = models.Index(fields=["title", "author"]) partial_index = models.Index( fields=["title"], name="long_books_idx", condition=models.Q(pages__gt=400) ) covering_index = models.Index( fields=["title"], name="include_idx", include=["author", "pages"], ) opclasses_index = models.Index( fields=["headline", "body"], name="opclasses_idx", opclasses=["varchar_pattern_ops", "text_pattern_ops"], ) func_index = models.Index(Lower("title"), "subtitle", name="book_func_idx") tablespace_index = models.Index( fields=["title"], db_tablespace="idx_tbls", name="book_tablespace_idx", ) self.assertEqual(repr(index), "<Index: fields=['title']>") self.assertEqual( repr(named_index), "<Index: fields=['title'] name='title_idx'>", ) self.assertEqual(repr(multi_col_index), "<Index: fields=['title', 'author']>") self.assertEqual( repr(partial_index), "<Index: fields=['title'] name='long_books_idx' " "condition=(AND: ('pages__gt', 400))>", ) self.assertEqual( repr(covering_index), "<Index: fields=['title'] name='include_idx' " "include=('author', 'pages')>", ) self.assertEqual( repr(opclasses_index), "<Index: fields=['headline', 'body'] name='opclasses_idx' " "opclasses=['varchar_pattern_ops', 'text_pattern_ops']>", ) self.assertEqual( repr(func_index), "<Index: expressions=(Lower(F(title)), F(subtitle)) " "name='book_func_idx'>", ) self.assertEqual( repr(tablespace_index), "<Index: fields=['title'] name='book_tablespace_idx' " "db_tablespace='idx_tbls'>", ) def test_eq(self): index = models.Index(fields=["title"]) same_index = models.Index(fields=["title"]) another_index = models.Index(fields=["title", "author"]) index.model = Book same_index.model = Book another_index.model = Book self.assertEqual(index, same_index) self.assertEqual(index, mock.ANY) self.assertNotEqual(index, another_index) def test_eq_func(self): index = models.Index(Lower("title"), models.F("author"), name="book_func_idx") same_index = models.Index(Lower("title"), "author", name="book_func_idx") another_index = models.Index(Lower("title"), name="book_func_idx") self.assertEqual(index, same_index) self.assertEqual(index, mock.ANY) self.assertNotEqual(index, another_index) def test_index_fields_type(self): with self.assertRaisesMessage( ValueError, "Index.fields must be a list or tuple." ): models.Index(fields="title") def test_index_fields_strings(self): msg = "Index.fields must contain only strings with field names." with self.assertRaisesMessage(ValueError, msg): models.Index(fields=[models.F("title")]) def test_fields_tuple(self): self.assertEqual(models.Index(fields=("title",)).fields, ["title"]) def test_requires_field_or_expression(self): msg = "At least one field or expression is required to define an index." with self.assertRaisesMessage(ValueError, msg): models.Index() def test_expressions_and_fields_mutually_exclusive(self): msg = "Index.fields and expressions are mutually exclusive." with self.assertRaisesMessage(ValueError, msg): models.Index(Upper("foo"), fields=["field"]) def test_opclasses_requires_index_name(self): with self.assertRaisesMessage( ValueError, "An index must be named to use opclasses." ): models.Index(opclasses=["jsonb_path_ops"]) def test_opclasses_requires_list_or_tuple(self): with self.assertRaisesMessage( ValueError, "Index.opclasses must be a list or tuple." ): models.Index( name="test_opclass", fields=["field"], opclasses="jsonb_path_ops" ) def test_opclasses_and_fields_same_length(self): msg = "Index.fields and Index.opclasses must have the same number of elements." with self.assertRaisesMessage(ValueError, msg): models.Index( name="test_opclass", fields=["field", "other"], opclasses=["jsonb_path_ops"], ) def test_condition_requires_index_name(self): with self.assertRaisesMessage( ValueError, "An index must be named to use condition." ): models.Index(condition=models.Q(pages__gt=400)) def test_expressions_requires_index_name(self): msg = "An index must be named to use expressions." with self.assertRaisesMessage(ValueError, msg): models.Index(Lower("field")) def test_expressions_with_opclasses(self): msg = ( "Index.opclasses cannot be used with expressions. Use " "django.contrib.postgres.indexes.OpClass() instead." ) with self.assertRaisesMessage(ValueError, msg): models.Index( Lower("field"), name="test_func_opclass", opclasses=["jsonb_path_ops"], ) def test_condition_must_be_q(self): with self.assertRaisesMessage( ValueError, "Index.condition must be a Q instance." ): models.Index(condition="invalid", name="long_book_idx") def test_include_requires_list_or_tuple(self): msg = "Index.include must be a list or tuple." with self.assertRaisesMessage(ValueError, msg): models.Index(name="test_include", fields=["field"], include="other") def test_include_requires_index_name(self): msg = "A covering index must be named." with self.assertRaisesMessage(ValueError, msg): models.Index(fields=["field"], include=["other"]) def test_name_auto_generation(self): index = models.Index(fields=["author"]) index.set_name_with_model(Book) self.assertEqual(index.name, "model_index_author_0f5565_idx") # '-' for DESC columns should be accounted for in the index name. index = models.Index(fields=["-author"]) index.set_name_with_model(Book) self.assertEqual(index.name, "model_index_author_708765_idx") # fields may be truncated in the name. db_column is used for naming. long_field_index = models.Index(fields=["pages"]) long_field_index.set_name_with_model(Book) self.assertEqual(long_field_index.name, "model_index_page_co_69235a_idx") # suffix can't be longer than 3 characters. long_field_index.suffix = "suff" msg = ( "Index too long for multiple database support. Is self.suffix " "longer than 3 characters?" ) with self.assertRaisesMessage(ValueError, msg): long_field_index.set_name_with_model(Book) @isolate_apps("model_indexes") def test_name_auto_generation_with_quoted_db_table(self): class QuotedDbTable(models.Model): name = models.CharField(max_length=50) class Meta: db_table = '"t_quoted"' index = models.Index(fields=["name"]) index.set_name_with_model(QuotedDbTable) self.assertEqual(index.name, "t_quoted_name_e4ed1b_idx") def test_deconstruction(self): index = models.Index(fields=["title"], db_tablespace="idx_tbls") index.set_name_with_model(Book) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.db.models.Index") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": ["title"], "name": "model_index_title_196f42_idx", "db_tablespace": "idx_tbls", }, ) def test_deconstruct_with_condition(self): index = models.Index( name="big_book_index", fields=["title"], condition=models.Q(pages__gt=400), ) index.set_name_with_model(Book) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.db.models.Index") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": ["title"], "name": "model_index_title_196f42_idx", "condition": models.Q(pages__gt=400), }, ) def test_deconstruct_with_include(self): index = models.Index( name="book_include_idx", fields=["title"], include=["author"], ) index.set_name_with_model(Book) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.db.models.Index") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": ["title"], "name": "model_index_title_196f42_idx", "include": ("author",), }, ) def test_deconstruct_with_expressions(self): index = models.Index(Upper("title"), name="book_func_idx") path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.db.models.Index") self.assertEqual(args, (Upper("title"),)) self.assertEqual(kwargs, {"name": "book_func_idx"}) def test_clone(self): index = models.Index(fields=["title"]) new_index = index.clone() self.assertIsNot(index, new_index) self.assertEqual(index.fields, new_index.fields) def test_clone_with_expressions(self): index = models.Index(Upper("title"), name="book_func_idx") new_index = index.clone() self.assertIsNot(index, new_index) self.assertEqual(index.expressions, new_index.expressions) def test_name_set(self): index_names = [index.name for index in Book._meta.indexes] self.assertCountEqual( index_names, [ "model_index_title_196f42_idx", "model_index_isbn_34f975_idx", "model_indexes_book_barcode_idx", ], ) def test_abstract_children(self): index_names = [index.name for index in ChildModel1._meta.indexes] self.assertEqual( index_names, ["model_index_name_440998_idx", "model_indexes_childmodel1_idx"], ) index_names = [index.name for index in ChildModel2._meta.indexes] self.assertEqual( index_names, ["model_index_name_b6c374_idx", "model_indexes_childmodel2_idx"], ) @override_settings(DEFAULT_TABLESPACE=None) class IndexesTests(TestCase): @skipUnlessDBFeature("supports_tablespaces") def test_db_tablespace(self): editor = connection.schema_editor() # Index with db_tablespace attribute. for fields in [ # Field with db_tablespace specified on model. ["shortcut"], # Field without db_tablespace specified on model. ["author"], # Multi-column with db_tablespaces specified on model. ["shortcut", "isbn"], # Multi-column without db_tablespace specified on model. ["title", "author"], ]: with self.subTest(fields=fields): index = models.Index(fields=fields, db_tablespace="idx_tbls2") self.assertIn( '"idx_tbls2"', str(index.create_sql(Book, editor)).lower() ) # Indexes without db_tablespace attribute. for fields in [["author"], ["shortcut", "isbn"], ["title", "author"]]: with self.subTest(fields=fields): index = models.Index(fields=fields) # The DEFAULT_INDEX_TABLESPACE setting can't be tested because # it's evaluated when the model class is defined. As a # consequence, @override_settings doesn't work. if settings.DEFAULT_INDEX_TABLESPACE: self.assertIn( '"%s"' % settings.DEFAULT_INDEX_TABLESPACE, str(index.create_sql(Book, editor)).lower(), ) else: self.assertNotIn("TABLESPACE", str(index.create_sql(Book, editor))) # Field with db_tablespace specified on the model and an index without # db_tablespace. index = models.Index(fields=["shortcut"]) self.assertIn('"idx_tbls"', str(index.create_sql(Book, editor)).lower()) @skipUnlessDBFeature("supports_tablespaces") def test_func_with_tablespace(self): # Functional index with db_tablespace attribute. index = models.Index( Lower("shortcut").desc(), name="functional_tbls", db_tablespace="idx_tbls2", ) with connection.schema_editor() as editor: sql = str(index.create_sql(Book, editor)) self.assertIn(editor.quote_name("idx_tbls2"), sql) # Functional index without db_tablespace attribute. index = models.Index(Lower("shortcut").desc(), name="functional_no_tbls") with connection.schema_editor() as editor: sql = str(index.create_sql(Book, editor)) # The DEFAULT_INDEX_TABLESPACE setting can't be tested because it's # evaluated when the model class is defined. As a consequence, # @override_settings doesn't work. if settings.DEFAULT_INDEX_TABLESPACE: self.assertIn( editor.quote_name(settings.DEFAULT_INDEX_TABLESPACE), sql, ) else: self.assertNotIn("TABLESPACE", sql)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/get_or_create/models.py
tests/get_or_create/models.py
from django.db import models class Person(models.Model): first_name = models.CharField(max_length=100, unique=True) last_name = models.CharField(max_length=100) birthday = models.DateField() defaults = models.TextField() create_defaults = models.TextField() class DefaultPerson(models.Model): first_name = models.CharField(max_length=100, default="Anonymous") class ManualPrimaryKeyTest(models.Model): id = models.IntegerField(primary_key=True) data = models.CharField(max_length=100) class Profile(models.Model): person = models.ForeignKey(Person, models.CASCADE, primary_key=True) class Tag(models.Model): text = models.CharField(max_length=255, unique=True) class Thing(models.Model): name = models.CharField(max_length=255) tags = models.ManyToManyField(Tag) @property def capitalized_name_property(self): return self.name @capitalized_name_property.setter def capitalized_name_property(self, val): self.name = val.capitalize() @property def name_in_all_caps(self): return self.name.upper() class Publisher(models.Model): name = models.CharField(max_length=100) class Author(models.Model): name = models.CharField(max_length=100) class Journalist(Author): specialty = models.CharField(max_length=100) class Book(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Author, related_name="books") publisher = models.ForeignKey( Publisher, models.CASCADE, related_name="books", db_column="publisher_id_column", ) updated = models.DateTimeField(auto_now=True)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/get_or_create/__init__.py
tests/get_or_create/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/get_or_create/tests.py
tests/get_or_create/tests.py
import time import traceback from datetime import date, datetime, timedelta from threading import Event, Thread, Timer from unittest.mock import patch from django.core.exceptions import FieldError from django.db import DatabaseError, IntegrityError, connection from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from django.utils.functional import lazy from .models import ( Author, Book, DefaultPerson, Journalist, ManualPrimaryKeyTest, Person, Profile, Publisher, Tag, Thing, ) class GetOrCreateTests(TestCase): @classmethod def setUpTestData(cls): Person.objects.create( first_name="John", last_name="Lennon", birthday=date(1940, 10, 9) ) def test_get_or_create_method_with_get(self): created = Person.objects.get_or_create( first_name="John", last_name="Lennon", defaults={"birthday": date(1940, 10, 9)}, )[1] self.assertFalse(created) self.assertEqual(Person.objects.count(), 1) def test_get_or_create_method_with_create(self): created = Person.objects.get_or_create( first_name="George", last_name="Harrison", defaults={"birthday": date(1943, 2, 25)}, )[1] self.assertTrue(created) self.assertEqual(Person.objects.count(), 2) def test_get_or_create_redundant_instance(self): """ If we execute the exact same statement twice, the second time, it won't create a Person. """ Person.objects.get_or_create( first_name="George", last_name="Harrison", defaults={"birthday": date(1943, 2, 25)}, ) created = Person.objects.get_or_create( first_name="George", last_name="Harrison", defaults={"birthday": date(1943, 2, 25)}, )[1] self.assertFalse(created) self.assertEqual(Person.objects.count(), 2) def test_get_or_create_invalid_params(self): """ If you don't specify a value or default value for all required fields, you will get an error. """ with self.assertRaises(IntegrityError): Person.objects.get_or_create(first_name="Tom", last_name="Smith") def test_get_or_create_with_pk_property(self): """ Using the pk property of a model is allowed. """ Thing.objects.get_or_create(pk=1) def test_get_or_create_with_model_property_defaults(self): """Using a property with a setter implemented is allowed.""" t, _ = Thing.objects.get_or_create( defaults={"capitalized_name_property": "annie"}, pk=1 ) self.assertEqual(t.name, "Annie") def test_get_or_create_on_related_manager(self): p = Publisher.objects.create(name="Acme Publishing") # Create a book through the publisher. book, created = p.books.get_or_create(name="The Book of Ed & Fred") self.assertTrue(created) # The publisher should have one book. self.assertEqual(p.books.count(), 1) # Try get_or_create again, this time nothing should be created. book, created = p.books.get_or_create(name="The Book of Ed & Fred") self.assertFalse(created) # And the publisher should still have one book. self.assertEqual(p.books.count(), 1) # Add an author to the book. ed, created = book.authors.get_or_create(name="Ed") self.assertTrue(created) # The book should have one author. self.assertEqual(book.authors.count(), 1) # Try get_or_create again, this time nothing should be created. ed, created = book.authors.get_or_create(name="Ed") self.assertFalse(created) # And the book should still have one author. self.assertEqual(book.authors.count(), 1) # Add a second author to the book. fred, created = book.authors.get_or_create(name="Fred") self.assertTrue(created) # The book should have two authors now. self.assertEqual(book.authors.count(), 2) # Create an Author not tied to any books. Author.objects.create(name="Ted") # There should be three Authors in total. The book object should have # two. self.assertEqual(Author.objects.count(), 3) self.assertEqual(book.authors.count(), 2) # Try creating a book through an author. _, created = ed.books.get_or_create(name="Ed's Recipes", publisher=p) self.assertTrue(created) # Now Ed has two Books, Fred just one. self.assertEqual(ed.books.count(), 2) self.assertEqual(fred.books.count(), 1) # Use the publisher's primary key value instead of a model instance. _, created = ed.books.get_or_create( name="The Great Book of Ed", publisher_id=p.id ) self.assertTrue(created) # Try get_or_create again, this time nothing should be created. _, created = ed.books.get_or_create( name="The Great Book of Ed", publisher_id=p.id ) self.assertFalse(created) # The publisher should have three books. self.assertEqual(p.books.count(), 3) def test_defaults_exact(self): """ If you have a field named defaults and want to use it as an exact lookup, you need to use 'defaults__exact'. """ obj, created = Person.objects.get_or_create( first_name="George", last_name="Harrison", defaults__exact="testing", defaults={ "birthday": date(1943, 2, 25), "defaults": "testing", }, ) self.assertTrue(created) self.assertEqual(obj.defaults, "testing") obj2, created = Person.objects.get_or_create( first_name="George", last_name="Harrison", defaults__exact="testing", defaults={ "birthday": date(1943, 2, 25), "defaults": "testing", }, ) self.assertFalse(created) self.assertEqual(obj, obj2) def test_callable_defaults(self): """ Callables in `defaults` are evaluated if the instance is created. """ obj, created = Person.objects.get_or_create( first_name="George", defaults={"last_name": "Harrison", "birthday": lambda: date(1943, 2, 25)}, ) self.assertTrue(created) self.assertEqual(date(1943, 2, 25), obj.birthday) def test_callable_defaults_not_called(self): def raise_exception(): raise AssertionError obj, created = Person.objects.get_or_create( first_name="John", last_name="Lennon", defaults={"birthday": lambda: raise_exception()}, ) def test_defaults_not_evaluated_unless_needed(self): """`defaults` aren't evaluated if the instance isn't created.""" def raise_exception(): raise AssertionError obj, created = Person.objects.get_or_create( first_name="John", defaults=lazy(raise_exception, object)(), ) self.assertFalse(created) class GetOrCreateTestsWithManualPKs(TestCase): @classmethod def setUpTestData(cls): ManualPrimaryKeyTest.objects.create(id=1, data="Original") def test_create_with_duplicate_primary_key(self): """ If you specify an existing primary key, but different other fields, then you will get an error and data will not be updated. """ with self.assertRaises(IntegrityError): ManualPrimaryKeyTest.objects.get_or_create(id=1, data="Different") self.assertEqual(ManualPrimaryKeyTest.objects.get(id=1).data, "Original") def test_savepoint_rollback(self): """ The database connection is still usable after a DatabaseError in get_or_create() (#20463). """ Tag.objects.create(text="foo") with self.assertRaises(DatabaseError): # pk 123456789 doesn't exist, so the tag object will be created. # Saving triggers a unique constraint violation on 'text'. Tag.objects.get_or_create(pk=123456789, defaults={"text": "foo"}) # Tag objects can be created after the error. Tag.objects.create(text="bar") def test_get_or_create_empty(self): """ If all the attributes on a model have defaults, get_or_create() doesn't require any arguments. """ DefaultPerson.objects.get_or_create() class GetOrCreateTransactionTests(TransactionTestCase): available_apps = ["get_or_create"] def test_get_or_create_integrityerror(self): """ Regression test for #15117. Requires a TransactionTestCase on databases that delay integrity checks until the end of transactions, otherwise the exception is never raised. """ try: Profile.objects.get_or_create(person=Person(id=1)) except IntegrityError: pass else: self.skipTest("This backend does not support integrity checks.") class GetOrCreateThroughManyToMany(TestCase): def test_get_get_or_create(self): tag = Tag.objects.create(text="foo") a_thing = Thing.objects.create(name="a") a_thing.tags.add(tag) obj, created = a_thing.tags.get_or_create(text="foo") self.assertFalse(created) self.assertEqual(obj.pk, tag.pk) def test_create_get_or_create(self): a_thing = Thing.objects.create(name="a") obj, created = a_thing.tags.get_or_create(text="foo") self.assertTrue(created) self.assertEqual(obj.text, "foo") self.assertIn(obj, a_thing.tags.all()) def test_something(self): Tag.objects.create(text="foo") a_thing = Thing.objects.create(name="a") with self.assertRaises(IntegrityError): a_thing.tags.get_or_create(text="foo") class UpdateOrCreateTests(TestCase): def test_update(self): Person.objects.create( first_name="John", last_name="Lennon", birthday=date(1940, 10, 9) ) p, created = Person.objects.update_or_create( first_name="John", last_name="Lennon", defaults={"birthday": date(1940, 10, 10)}, ) self.assertFalse(created) self.assertEqual(p.first_name, "John") self.assertEqual(p.last_name, "Lennon") self.assertEqual(p.birthday, date(1940, 10, 10)) def test_create(self): p, created = Person.objects.update_or_create( first_name="John", last_name="Lennon", defaults={"birthday": date(1940, 10, 10)}, ) self.assertTrue(created) self.assertEqual(p.first_name, "John") self.assertEqual(p.last_name, "Lennon") self.assertEqual(p.birthday, date(1940, 10, 10)) def test_create_twice(self): p, created = Person.objects.update_or_create( first_name="John", last_name="Lennon", create_defaults={"birthday": date(1940, 10, 10)}, defaults={"birthday": date(1950, 2, 2)}, ) self.assertIs(created, True) self.assertEqual(p.birthday, date(1940, 10, 10)) # If we execute the exact same statement, it won't create a Person, but # will update the birthday. p, created = Person.objects.update_or_create( first_name="John", last_name="Lennon", create_defaults={"birthday": date(1940, 10, 10)}, defaults={"birthday": date(1950, 2, 2)}, ) self.assertIs(created, False) self.assertEqual(p.birthday, date(1950, 2, 2)) def test_integrity(self): """ If you don't specify a value or default value for all required fields, you will get an error. """ with self.assertRaises(IntegrityError): Person.objects.update_or_create(first_name="Tom", last_name="Smith") def test_manual_primary_key_test(self): """ If you specify an existing primary key, but different other fields, then you will get an error and data will not be updated. """ ManualPrimaryKeyTest.objects.create(id=1, data="Original") with self.assertRaises(IntegrityError): ManualPrimaryKeyTest.objects.update_or_create(id=1, data="Different") self.assertEqual(ManualPrimaryKeyTest.objects.get(id=1).data, "Original") def test_with_pk_property(self): """ Using the pk property of a model is allowed. """ Thing.objects.update_or_create(pk=1) def test_update_or_create_with_model_property_defaults(self): """Using a property with a setter implemented is allowed.""" t, _ = Thing.objects.update_or_create( defaults={"capitalized_name_property": "annie"}, pk=1 ) self.assertEqual(t.name, "Annie") def test_error_contains_full_traceback(self): """ update_or_create should raise IntegrityErrors with the full traceback. This is tested by checking that a known method call is in the traceback. We cannot use assertRaises/assertRaises here because we need to inspect the actual traceback. Refs #16340. """ try: ManualPrimaryKeyTest.objects.update_or_create(id=1, data="Different") except IntegrityError: formatted_traceback = traceback.format_exc() self.assertIn("obj.save", formatted_traceback) def test_create_with_related_manager(self): """ Should be able to use update_or_create from the related manager to create a book. Refs #23611. """ p = Publisher.objects.create(name="Acme Publishing") book, created = p.books.update_or_create(name="The Book of Ed & Fred") self.assertIs(created, True) self.assertEqual(p.books.count(), 1) book, created = p.books.update_or_create( name="Basics of Django", create_defaults={"name": "Advanced Django"} ) self.assertIs(created, True) self.assertEqual(book.name, "Advanced Django") self.assertEqual(p.books.count(), 2) def test_update_with_related_manager(self): """ Should be able to use update_or_create from the related manager to update a book. Refs #23611. """ p = Publisher.objects.create(name="Acme Publishing") book = Book.objects.create(name="The Book of Ed & Fred", publisher=p) self.assertEqual(p.books.count(), 1) name = "The Book of Django" book, created = p.books.update_or_create(defaults={"name": name}, id=book.id) self.assertFalse(created) self.assertEqual(book.name, name) # create_defaults should be ignored. book, created = p.books.update_or_create( create_defaults={"name": "Basics of Django"}, defaults={"name": name}, id=book.id, ) self.assertIs(created, False) self.assertEqual(book.name, name) self.assertEqual(p.books.count(), 1) def test_create_with_many(self): """ Should be able to use update_or_create from the m2m related manager to create a book. Refs #23611. """ p = Publisher.objects.create(name="Acme Publishing") author = Author.objects.create(name="Ted") book, created = author.books.update_or_create( name="The Book of Ed & Fred", publisher=p ) self.assertIs(created, True) self.assertEqual(author.books.count(), 1) book, created = author.books.update_or_create( name="Basics of Django", publisher=p, create_defaults={"name": "Advanced Django"}, ) self.assertIs(created, True) self.assertEqual(book.name, "Advanced Django") self.assertEqual(author.books.count(), 2) def test_update_with_many(self): """ Should be able to use update_or_create from the m2m related manager to update a book. Refs #23611. """ p = Publisher.objects.create(name="Acme Publishing") author = Author.objects.create(name="Ted") book = Book.objects.create(name="The Book of Ed & Fred", publisher=p) book.authors.add(author) self.assertEqual(author.books.count(), 1) name = "The Book of Django" book, created = author.books.update_or_create( defaults={"name": name}, id=book.id ) self.assertFalse(created) self.assertEqual(book.name, name) # create_defaults should be ignored. book, created = author.books.update_or_create( create_defaults={"name": "Basics of Django"}, defaults={"name": name}, id=book.id, ) self.assertIs(created, False) self.assertEqual(book.name, name) self.assertEqual(author.books.count(), 1) def test_defaults_exact(self): """ If you have a field named defaults and want to use it as an exact lookup, you need to use 'defaults__exact'. """ obj, created = Person.objects.update_or_create( first_name="George", last_name="Harrison", defaults__exact="testing", defaults={ "birthday": date(1943, 2, 25), "defaults": "testing", }, ) self.assertTrue(created) self.assertEqual(obj.defaults, "testing") obj, created = Person.objects.update_or_create( first_name="George", last_name="Harrison", defaults__exact="testing", defaults={ "birthday": date(1943, 2, 25), "defaults": "another testing", }, ) self.assertFalse(created) self.assertEqual(obj.defaults, "another testing") def test_create_defaults_exact(self): """ If you have a field named create_defaults and want to use it as an exact lookup, you need to use 'create_defaults__exact'. """ obj, created = Person.objects.update_or_create( first_name="George", last_name="Harrison", create_defaults__exact="testing", create_defaults={ "birthday": date(1943, 2, 25), "create_defaults": "testing", }, ) self.assertIs(created, True) self.assertEqual(obj.create_defaults, "testing") obj, created = Person.objects.update_or_create( first_name="George", last_name="Harrison", create_defaults__exact="testing", create_defaults={ "birthday": date(1943, 2, 25), "create_defaults": "another testing", }, ) self.assertIs(created, False) self.assertEqual(obj.create_defaults, "testing") def test_create_callable_default(self): obj, created = Person.objects.update_or_create( first_name="George", last_name="Harrison", defaults={"birthday": lambda: date(1943, 2, 25)}, ) self.assertIs(created, True) self.assertEqual(obj.birthday, date(1943, 2, 25)) def test_create_callable_create_defaults(self): obj, created = Person.objects.update_or_create( first_name="George", last_name="Harrison", defaults={}, create_defaults={"birthday": lambda: date(1943, 2, 25)}, ) self.assertIs(created, True) self.assertEqual(obj.birthday, date(1943, 2, 25)) def test_update_callable_default(self): Person.objects.update_or_create( first_name="George", last_name="Harrison", birthday=date(1942, 2, 25), ) obj, created = Person.objects.update_or_create( first_name="George", defaults={"last_name": lambda: "NotHarrison"}, ) self.assertIs(created, False) self.assertEqual(obj.last_name, "NotHarrison") def test_defaults_not_evaluated_unless_needed(self): """`defaults` aren't evaluated if the instance isn't created.""" Person.objects.create( first_name="John", last_name="Lennon", birthday=date(1940, 10, 9) ) def raise_exception(): raise AssertionError obj, created = Person.objects.get_or_create( first_name="John", defaults=lazy(raise_exception, object)(), ) self.assertFalse(created) def test_mti_update_non_local_concrete_fields(self): journalist = Journalist.objects.create(name="Jane", specialty="Politics") journalist, created = Journalist.objects.update_or_create( pk=journalist.pk, defaults={"name": "John"}, ) self.assertIs(created, False) self.assertEqual(journalist.name, "John") def test_update_only_defaults_and_pre_save_fields_when_local_fields(self): publisher = Publisher.objects.create(name="Acme Publishing") book = Book.objects.create(publisher=publisher, name="The Book of Ed & Fred") for defaults in [{"publisher": publisher}, {"publisher_id": publisher}]: with self.subTest(defaults=defaults): with CaptureQueriesContext(connection) as captured_queries: book, created = Book.objects.update_or_create( pk=book.pk, defaults=defaults, ) self.assertIs(created, False) update_sqls = [ q["sql"] for q in captured_queries if q["sql"].startswith("UPDATE") ] self.assertEqual(len(update_sqls), 1) update_sql = update_sqls[0] self.assertIsNotNone(update_sql) self.assertIn( connection.ops.quote_name("publisher_id_column"), update_sql ) self.assertIn(connection.ops.quote_name("updated"), update_sql) # Name should not be updated. self.assertNotIn(connection.ops.quote_name("name"), update_sql) class UpdateOrCreateTestsWithManualPKs(TestCase): def test_create_with_duplicate_primary_key(self): """ If an existing primary key is specified with different values for other fields, then IntegrityError is raised and data isn't updated. """ ManualPrimaryKeyTest.objects.create(id=1, data="Original") with self.assertRaises(IntegrityError): ManualPrimaryKeyTest.objects.update_or_create(id=1, data="Different") self.assertEqual(ManualPrimaryKeyTest.objects.get(id=1).data, "Original") class UpdateOrCreateTransactionTests(TransactionTestCase): available_apps = ["get_or_create"] @skipUnlessDBFeature("has_select_for_update") @skipUnlessDBFeature("supports_transactions") def test_updates_in_transaction(self): """ Objects are selected and updated in a transaction to avoid race conditions. This test forces update_or_create() to hold the lock in another thread for a relatively long time so that it can update while it holds the lock. The updated field isn't a field in 'defaults', so update_or_create() shouldn't have an effect on it. """ lock_status = {"has_grabbed_lock": False} def birthday_sleep(): lock_status["has_grabbed_lock"] = True time.sleep(0.5) return date(1940, 10, 10) def update_birthday_slowly(): Person.objects.update_or_create( first_name="John", defaults={"birthday": birthday_sleep} ) # Avoid leaking connection for Oracle connection.close() def lock_wait(): # timeout after ~0.5 seconds for i in range(20): time.sleep(0.025) if lock_status["has_grabbed_lock"]: return True return False Person.objects.create( first_name="John", last_name="Lennon", birthday=date(1940, 10, 9) ) # update_or_create in a separate thread t = Thread(target=update_birthday_slowly) before_start = datetime.now() t.start() if not lock_wait(): self.skipTest("Database took too long to lock the row") # Update during lock Person.objects.filter(first_name="John").update(last_name="NotLennon") after_update = datetime.now() # Wait for thread to finish t.join() # The update remains and it blocked. updated_person = Person.objects.get(first_name="John") self.assertGreater(after_update - before_start, timedelta(seconds=0.5)) self.assertEqual(updated_person.last_name, "NotLennon") @skipUnlessDBFeature("has_select_for_update") @skipUnlessDBFeature("supports_transactions") def test_creation_in_transaction(self): """ Objects are selected and updated in a transaction to avoid race conditions. This test checks the behavior of update_or_create() when the object doesn't already exist, but another thread creates the object before update_or_create() does and then attempts to update the object, also before update_or_create(). It forces update_or_create() to hold the lock in another thread for a relatively long time so that it can update while it holds the lock. The updated field isn't a field in 'defaults', so update_or_create() shouldn't have an effect on it. """ locked_for_update = Event() save_allowed = Event() def wait_or_fail(event, message): if not event.wait(5): raise AssertionError(message) def birthday_yield(): # At this point the row should be locked as create or update # defaults are only called once the SELECT FOR UPDATE is issued. locked_for_update.set() # Yield back the execution to the main thread until it allows # save() to proceed. save_allowed.clear() return date(1940, 10, 10) person_save = Person.save def wait_for_allowed_save(*args, **kwargs): wait_or_fail(save_allowed, "Test took too long to allow save") return person_save(*args, **kwargs) def update_person(): try: with patch.object(Person, "save", wait_for_allowed_save): Person.objects.update_or_create( first_name="John", defaults={"last_name": "Doe", "birthday": birthday_yield}, ) finally: # Avoid leaking connection for Oracle. connection.close() t = Thread(target=update_person) t.start() wait_or_fail(locked_for_update, "Database took too long to lock row") # Create object *after* initial attempt by update_or_create to get obj # but before creation attempt. person = Person( first_name="John", last_name="Lennon", birthday=date(1940, 10, 9) ) # Don't use person.save() as it's gated by the save_allowed event. person_save(person, force_insert=True) # Now that the row is created allow the update_or_create() logic to # attempt a save(force_insert) that will inevitably fail and wait # until it yields back execution after performing a subsequent # locked select for update with an intent to save(force_update). locked_for_update.clear() save_allowed.set() wait_or_fail(locked_for_update, "Database took too long to lock row") allow_save = Timer(0.5, save_allowed.set) before_start = datetime.now() allow_save.start() # The following update() should block until the update_or_create() # initiated save() is allowed to proceed by the `allow_save` timer # setting `save_allowed` after 0.5 seconds. Person.objects.filter(first_name="John").update(last_name="NotLennon") after_update = datetime.now() # Wait for thread to finish. t.join() # Check call to update_or_create() succeeded and the subsequent # (blocked) call to update(). updated_person = Person.objects.get(first_name="John") # Confirm update_or_create() performed an update. self.assertEqual(updated_person.birthday, date(1940, 10, 10)) # Confirm update() was the last statement to run. self.assertEqual(updated_person.last_name, "NotLennon") # Confirm update() blocked at least the duration of the timer. self.assertGreater(after_update - before_start, timedelta(seconds=0.5)) class InvalidCreateArgumentsTests(TransactionTestCase): available_apps = ["get_or_create"] msg = "Invalid field name(s) for model Thing: 'nonexistent'." bad_field_msg = ( "Cannot resolve keyword 'nonexistent' into field. Choices are: id, name, tags" ) def test_get_or_create_with_invalid_defaults(self): with self.assertRaisesMessage(FieldError, self.msg): Thing.objects.get_or_create(name="a", defaults={"nonexistent": "b"}) def test_get_or_create_with_invalid_kwargs(self): with self.assertRaisesMessage(FieldError, self.bad_field_msg): Thing.objects.get_or_create(name="a", nonexistent="b") def test_update_or_create_with_invalid_defaults(self): with self.assertRaisesMessage(FieldError, self.msg): Thing.objects.update_or_create(name="a", defaults={"nonexistent": "b"}) def test_update_or_create_with_invalid_create_defaults(self): with self.assertRaisesMessage(FieldError, self.msg): Thing.objects.update_or_create( name="a", create_defaults={"nonexistent": "b"} ) def test_update_or_create_with_invalid_kwargs(self): with self.assertRaisesMessage(FieldError, self.bad_field_msg): Thing.objects.update_or_create(name="a", nonexistent="b") def test_multiple_invalid_fields(self): with self.assertRaisesMessage(FieldError, self.bad_field_msg): Thing.objects.update_or_create( name="a", nonexistent="b", defaults={"invalid": "c"} ) def test_property_attribute_without_setter_defaults(self): with self.assertRaisesMessage( FieldError, "Invalid field name(s) for model Thing: 'name_in_all_caps'" ): Thing.objects.update_or_create( name="a", defaults={"name_in_all_caps": "FRANK"} ) def test_property_attribute_without_setter_kwargs(self): msg = ( "Cannot resolve keyword 'name_in_all_caps' into field. Choices are: id, " "name, tags" ) with self.assertRaisesMessage(FieldError, msg): Thing.objects.update_or_create( name_in_all_caps="FRANK", defaults={"name": "Frank"} )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/sessions_tests/models.py
tests/sessions_tests/models.py
""" This custom Session model adds an extra column to store an account ID. In real-world applications, it gives you the option of querying the database for all active sessions for a particular account. """ from django.contrib.sessions.backends.db import SessionStore as DBStore from django.contrib.sessions.base_session import AbstractBaseSession from django.db import models class CustomSession(AbstractBaseSession): """ A session model with a column for an account ID. """ account_id = models.IntegerField(null=True, db_index=True) @classmethod def get_session_store_class(cls): return SessionStore class SessionStore(DBStore): """ A database session store, that handles updating the account ID column inside the custom session model. """ @classmethod def get_model_class(cls): return CustomSession def create_model_instance(self, data): obj = super().create_model_instance(data) try: account_id = int(data.get("_auth_user_id")) except (ValueError, TypeError): account_id = None obj.account_id = account_id return obj def get_session_cookie_age(self): return 60 * 60 * 24 # One day.
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/sessions_tests/__init__.py
tests/sessions_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/sessions_tests/no_clear_expired.py
tests/sessions_tests/no_clear_expired.py
from django.contrib.sessions.backends.base import SessionBase class SessionStore(SessionBase): """Session store without support for clearing expired sessions.""" pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/sessions_tests/tests.py
tests/sessions_tests/tests.py
import base64 import os import shutil import string import tempfile import unittest from datetime import timedelta from http import cookies from pathlib import Path from unittest import mock from django.conf import settings from django.contrib.sessions.backends.base import SessionBase, UpdateError from django.contrib.sessions.backends.cache import SessionStore as CacheSession from django.contrib.sessions.backends.cached_db import SessionStore as CacheDBSession from django.contrib.sessions.backends.db import SessionStore as DatabaseSession from django.contrib.sessions.backends.file import SessionStore as FileSession from django.contrib.sessions.backends.signed_cookies import ( SessionStore as CookieSession, ) from django.contrib.sessions.exceptions import InvalidSessionKey, SessionInterrupted from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.sessions.models import Session from django.contrib.sessions.serializers import JSONSerializer from django.core import management from django.core.cache import caches from django.core.cache.backends.base import InvalidCacheBackendError from django.core.exceptions import ImproperlyConfigured from django.core.signing import TimestampSigner from django.http import HttpResponse from django.test import ( RequestFactory, SimpleTestCase, TestCase, ignore_warnings, override_settings, ) from django.utils import timezone from .models import SessionStore as CustomDatabaseSession class SessionTestsMixin: # This does not inherit from TestCase to avoid any tests being run with # this class, which wouldn't work, and to allow different TestCase # subclasses to be used. backend = None # subclasses must specify def setUp(self): self.session = self.backend() # NB: be careful to delete any sessions created; stale sessions fill up # the /tmp (with some backends) and eventually overwhelm it after lots # of runs (think buildbots) self.addCleanup(self.session.delete) def test_new_session(self): self.assertIs(self.session.modified, False) self.assertIs(self.session.accessed, False) def test_get_empty(self): self.assertIsNone(self.session.get("cat")) async def test_get_empty_async(self): self.assertIsNone(await self.session.aget("cat")) def test_store(self): self.session["cat"] = "dog" self.assertIs(self.session.modified, True) self.assertEqual(self.session.pop("cat"), "dog") async def test_store_async(self): await self.session.aset("cat", "dog") self.assertIs(self.session.modified, True) self.assertEqual(await self.session.apop("cat"), "dog") def test_pop(self): self.session["some key"] = "exists" # Need to reset these to pretend we haven't accessed it: self.accessed = False self.modified = False self.assertEqual(self.session.pop("some key"), "exists") self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, True) self.assertIsNone(self.session.get("some key")) async def test_pop_async(self): await self.session.aset("some key", "exists") # Need to reset these to pretend we haven't accessed it: self.accessed = False self.modified = False self.assertEqual(await self.session.apop("some key"), "exists") self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, True) self.assertIsNone(await self.session.aget("some key")) def test_pop_default(self): self.assertEqual( self.session.pop("some key", "does not exist"), "does not exist" ) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) async def test_pop_default_async(self): self.assertEqual( await self.session.apop("some key", "does not exist"), "does not exist" ) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_pop_default_named_argument(self): self.assertEqual( self.session.pop("some key", default="does not exist"), "does not exist" ) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) async def test_pop_default_named_argument_async(self): self.assertEqual( await self.session.apop("some key", default="does not exist"), "does not exist", ) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_pop_no_default_keyerror_raised(self): with self.assertRaises(KeyError): self.session.pop("some key") async def test_pop_no_default_keyerror_raised_async(self): with self.assertRaises(KeyError): await self.session.apop("some key") def test_setdefault(self): self.assertEqual(self.session.setdefault("foo", "bar"), "bar") self.assertEqual(self.session.setdefault("foo", "baz"), "bar") self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, True) async def test_setdefault_async(self): self.assertEqual(await self.session.asetdefault("foo", "bar"), "bar") self.assertEqual(await self.session.asetdefault("foo", "baz"), "bar") self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, True) def test_update(self): self.session.update({"update key": 1}) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, True) self.assertEqual(self.session.get("update key", None), 1) async def test_update_async(self): await self.session.aupdate({"update key": 1}) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, True) self.assertEqual(await self.session.aget("update key", None), 1) def test_has_key(self): self.session["some key"] = 1 self.session.modified = False self.session.accessed = False self.assertIn("some key", self.session) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) async def test_has_key_async(self): await self.session.aset("some key", 1) self.session.modified = False self.session.accessed = False self.assertIs(await self.session.ahas_key("some key"), True) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_values(self): self.assertEqual(list(self.session.values()), []) self.assertIs(self.session.accessed, True) self.session["some key"] = 1 self.session.modified = False self.session.accessed = False self.assertEqual(list(self.session.values()), [1]) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) async def test_values_async(self): self.assertEqual(list(await self.session.avalues()), []) self.assertIs(self.session.accessed, True) await self.session.aset("some key", 1) self.session.modified = False self.session.accessed = False self.assertEqual(list(await self.session.avalues()), [1]) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_keys(self): self.session["x"] = 1 self.session.modified = False self.session.accessed = False self.assertEqual(list(self.session.keys()), ["x"]) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) async def test_keys_async(self): await self.session.aset("x", 1) self.session.modified = False self.session.accessed = False self.assertEqual(list(await self.session.akeys()), ["x"]) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_items(self): self.session["x"] = 1 self.session.modified = False self.session.accessed = False self.assertEqual(list(self.session.items()), [("x", 1)]) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) async def test_items_async(self): await self.session.aset("x", 1) self.session.modified = False self.session.accessed = False self.assertEqual(list(await self.session.aitems()), [("x", 1)]) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_clear(self): self.session["x"] = 1 self.session.modified = False self.session.accessed = False self.assertEqual(list(self.session.items()), [("x", 1)]) self.session.clear() self.assertEqual(list(self.session.items()), []) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, True) def test_save(self): self.session.save() self.assertIs(self.session.exists(self.session.session_key), True) async def test_save_async(self): await self.session.asave() self.assertIs(await self.session.aexists(self.session.session_key), True) def test_delete(self): self.session.save() self.session.delete(self.session.session_key) self.assertIs(self.session.exists(self.session.session_key), False) async def test_delete_async(self): await self.session.asave() await self.session.adelete(self.session.session_key) self.assertIs(await self.session.aexists(self.session.session_key), False) def test_flush(self): self.session["foo"] = "bar" self.session.save() prev_key = self.session.session_key self.session.flush() self.assertIs(self.session.exists(prev_key), False) self.assertNotEqual(self.session.session_key, prev_key) self.assertIsNone(self.session.session_key) self.assertIs(self.session.modified, True) self.assertIs(self.session.accessed, True) async def test_flush_async(self): await self.session.aset("foo", "bar") await self.session.asave() prev_key = self.session.session_key await self.session.aflush() self.assertIs(await self.session.aexists(prev_key), False) self.assertNotEqual(self.session.session_key, prev_key) self.assertIsNone(self.session.session_key) self.assertIs(self.session.modified, True) self.assertIs(self.session.accessed, True) def test_cycle(self): self.session["a"], self.session["b"] = "c", "d" self.session.save() prev_key = self.session.session_key prev_data = list(self.session.items()) self.session.cycle_key() self.assertIs(self.session.exists(prev_key), False) self.assertNotEqual(self.session.session_key, prev_key) self.assertEqual(list(self.session.items()), prev_data) async def test_cycle_async(self): await self.session.aset("a", "c") await self.session.aset("b", "d") await self.session.asave() prev_key = self.session.session_key prev_data = list(await self.session.aitems()) await self.session.acycle_key() self.assertIs(await self.session.aexists(prev_key), False) self.assertNotEqual(self.session.session_key, prev_key) self.assertEqual(list(await self.session.aitems()), prev_data) def test_cycle_with_no_session_cache(self): self.session["a"], self.session["b"] = "c", "d" self.session.save() prev_data = self.session.items() self.session = self.backend(self.session.session_key) self.assertIs(hasattr(self.session, "_session_cache"), False) self.session.cycle_key() self.assertCountEqual(self.session.items(), prev_data) async def test_cycle_with_no_session_cache_async(self): await self.session.aset("a", "c") await self.session.aset("b", "d") await self.session.asave() prev_data = await self.session.aitems() self.session = self.backend(self.session.session_key) self.assertIs(hasattr(self.session, "_session_cache"), False) await self.session.acycle_key() self.assertCountEqual(await self.session.aitems(), prev_data) def test_save_doesnt_clear_data(self): self.session["a"] = "b" self.session.save() self.assertEqual(self.session["a"], "b") async def test_save_doesnt_clear_data_async(self): await self.session.aset("a", "b") await self.session.asave() self.assertEqual(await self.session.aget("a"), "b") def test_invalid_key(self): # Submitting an invalid session key (either by guessing, or if the db # has removed the key) results in a new key being generated. try: session = self.backend("1") session.save() self.assertNotEqual(session.session_key, "1") self.assertIsNone(session.get("cat")) session.delete() finally: # Some backends leave a stale cache entry for the invalid # session key; make sure that entry is manually deleted session.delete("1") async def test_invalid_key_async(self): # Submitting an invalid session key (either by guessing, or if the db # has removed the key) results in a new key being generated. try: session = self.backend("1") await session.asave() self.assertNotEqual(session.session_key, "1") self.assertIsNone(await session.aget("cat")) await session.adelete() finally: # Some backends leave a stale cache entry for the invalid # session key; make sure that entry is manually deleted await session.adelete("1") def test_session_key_empty_string_invalid(self): """Falsey values (Such as an empty string) are rejected.""" self.session._session_key = "" self.assertIsNone(self.session.session_key) def test_session_key_too_short_invalid(self): """Strings shorter than 8 characters are rejected.""" self.session._session_key = "1234567" self.assertIsNone(self.session.session_key) def test_session_key_valid_string_saved(self): """Strings of length 8 and up are accepted and stored.""" self.session._session_key = "12345678" self.assertEqual(self.session.session_key, "12345678") def test_session_key_is_read_only(self): def set_session_key(session): session.session_key = session._get_new_session_key() with self.assertRaises(AttributeError): set_session_key(self.session) # Custom session expiry def test_default_expiry(self): # A normal session has a max age equal to settings self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) # So does a custom session with an idle expiration time of 0 (but it'll # expire at browser close) self.session.set_expiry(0) self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) async def test_default_expiry_async(self): # A normal session has a max age equal to settings. self.assertEqual( await self.session.aget_expiry_age(), settings.SESSION_COOKIE_AGE ) # So does a custom session with an idle expiration time of 0 (but it'll # expire at browser close). await self.session.aset_expiry(0) self.assertEqual( await self.session.aget_expiry_age(), settings.SESSION_COOKIE_AGE ) def test_custom_expiry_seconds(self): modification = timezone.now() self.session.set_expiry(10) date = self.session.get_expiry_date(modification=modification) self.assertEqual(date, modification + timedelta(seconds=10)) age = self.session.get_expiry_age(modification=modification) self.assertEqual(age, 10) async def test_custom_expiry_seconds_async(self): modification = timezone.now() await self.session.aset_expiry(10) date = await self.session.aget_expiry_date(modification=modification) self.assertEqual(date, modification + timedelta(seconds=10)) age = await self.session.aget_expiry_age(modification=modification) self.assertEqual(age, 10) def test_custom_expiry_timedelta(self): modification = timezone.now() # Mock timezone.now, because set_expiry calls it on this code path. original_now = timezone.now try: timezone.now = lambda: modification self.session.set_expiry(timedelta(seconds=10)) finally: timezone.now = original_now date = self.session.get_expiry_date(modification=modification) self.assertEqual(date, modification + timedelta(seconds=10)) age = self.session.get_expiry_age(modification=modification) self.assertEqual(age, 10) async def test_custom_expiry_timedelta_async(self): modification = timezone.now() # Mock timezone.now, because set_expiry calls it on this code path. original_now = timezone.now try: timezone.now = lambda: modification await self.session.aset_expiry(timedelta(seconds=10)) finally: timezone.now = original_now date = await self.session.aget_expiry_date(modification=modification) self.assertEqual(date, modification + timedelta(seconds=10)) age = await self.session.aget_expiry_age(modification=modification) self.assertEqual(age, 10) def test_custom_expiry_datetime(self): modification = timezone.now() self.session.set_expiry(modification + timedelta(seconds=10)) date = self.session.get_expiry_date(modification=modification) self.assertEqual(date, modification + timedelta(seconds=10)) age = self.session.get_expiry_age(modification=modification) self.assertEqual(age, 10) async def test_custom_expiry_datetime_async(self): modification = timezone.now() await self.session.aset_expiry(modification + timedelta(seconds=10)) date = await self.session.aget_expiry_date(modification=modification) self.assertEqual(date, modification + timedelta(seconds=10)) age = await self.session.aget_expiry_age(modification=modification) self.assertEqual(age, 10) def test_custom_expiry_reset(self): self.session.set_expiry(None) self.session.set_expiry(10) self.session.set_expiry(None) self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) async def test_custom_expiry_reset_async(self): await self.session.aset_expiry(None) await self.session.aset_expiry(10) await self.session.aset_expiry(None) self.assertEqual( await self.session.aget_expiry_age(), settings.SESSION_COOKIE_AGE ) def test_get_expire_at_browser_close(self): # Tests get_expire_at_browser_close with different settings and # different set_expiry calls with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=False): self.session.set_expiry(10) self.assertIs(self.session.get_expire_at_browser_close(), False) self.session.set_expiry(0) self.assertIs(self.session.get_expire_at_browser_close(), True) self.session.set_expiry(None) self.assertIs(self.session.get_expire_at_browser_close(), False) with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=True): self.session.set_expiry(10) self.assertIs(self.session.get_expire_at_browser_close(), False) self.session.set_expiry(0) self.assertIs(self.session.get_expire_at_browser_close(), True) self.session.set_expiry(None) self.assertIs(self.session.get_expire_at_browser_close(), True) async def test_get_expire_at_browser_close_async(self): # Tests get_expire_at_browser_close with different settings and # different set_expiry calls with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=False): await self.session.aset_expiry(10) self.assertIs(await self.session.aget_expire_at_browser_close(), False) await self.session.aset_expiry(0) self.assertIs(await self.session.aget_expire_at_browser_close(), True) await self.session.aset_expiry(None) self.assertIs(await self.session.aget_expire_at_browser_close(), False) with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=True): await self.session.aset_expiry(10) self.assertIs(await self.session.aget_expire_at_browser_close(), False) await self.session.aset_expiry(0) self.assertIs(await self.session.aget_expire_at_browser_close(), True) await self.session.aset_expiry(None) self.assertIs(await self.session.aget_expire_at_browser_close(), True) def test_decode(self): # Ensure we can decode what we encode data = {"a test key": "a test value"} encoded = self.session.encode(data) self.assertEqual(self.session.decode(encoded), data) def test_decode_failure_logged_to_security(self): tests = [ base64.b64encode(b"flaskdj:alkdjf").decode("ascii"), "bad:encoded:value", ] for encoded in tests: with self.subTest(encoded=encoded): with self.assertLogs( "django.security.SuspiciousSession", "WARNING" ) as cm: self.assertEqual(self.session.decode(encoded), {}) # The failed decode is logged. self.assertIn("Session data corrupted", cm.output[0]) def test_decode_serializer_exception(self): signer = TimestampSigner(salt=self.session.key_salt) encoded = signer.sign(b"invalid data") self.assertEqual(self.session.decode(encoded), {}) def test_actual_expiry(self): old_session_key = None new_session_key = None try: self.session["foo"] = "bar" self.session.set_expiry(-timedelta(seconds=10)) self.session.save() old_session_key = self.session.session_key # With an expiry date in the past, the session expires instantly. new_session = self.backend(self.session.session_key) new_session_key = new_session.session_key self.assertNotIn("foo", new_session) finally: self.session.delete(old_session_key) self.session.delete(new_session_key) async def test_actual_expiry_async(self): old_session_key = None new_session_key = None try: await self.session.aset("foo", "bar") await self.session.aset_expiry(-timedelta(seconds=10)) await self.session.asave() old_session_key = self.session.session_key # With an expiry date in the past, the session expires instantly. new_session = self.backend(self.session.session_key) new_session_key = new_session.session_key self.assertIs(await new_session.ahas_key("foo"), False) finally: await self.session.adelete(old_session_key) await self.session.adelete(new_session_key) def test_session_load_does_not_create_record(self): """ Loading an unknown session key does not create a session record. Creating session records on load is a DOS vulnerability. """ session = self.backend("someunknownkey") session.load() self.assertIsNone(session.session_key) self.assertIs(session.exists(session.session_key), False) # provided unknown key was cycled, not reused self.assertNotEqual(session.session_key, "someunknownkey") async def test_session_load_does_not_create_record_async(self): session = self.backend("someunknownkey") await session.aload() self.assertIsNone(session.session_key) self.assertIs(await session.aexists(session.session_key), False) # Provided unknown key was cycled, not reused. self.assertNotEqual(session.session_key, "someunknownkey") def test_session_save_does_not_resurrect_session_logged_out_in_other_context(self): """ Sessions shouldn't be resurrected by a concurrent request. """ # Create new session. s1 = self.backend() s1["test_data"] = "value1" s1.save(must_create=True) # Logout in another context. s2 = self.backend(s1.session_key) s2.delete() # Modify session in first context. s1["test_data"] = "value2" with self.assertRaises(UpdateError): # This should throw an exception as the session is deleted, not # resurrect the session. s1.save() self.assertEqual(s1.load(), {}) async def test_session_asave_does_not_resurrect_session_logged_out_in_other_context( self, ): """Sessions shouldn't be resurrected by a concurrent request.""" # Create new session. s1 = self.backend() await s1.aset("test_data", "value1") await s1.asave(must_create=True) # Logout in another context. s2 = self.backend(s1.session_key) await s2.adelete() # Modify session in first context. await s1.aset("test_data", "value2") with self.assertRaises(UpdateError): # This should throw an exception as the session is deleted, not # resurrect the session. await s1.asave() self.assertEqual(await s1.aload(), {}) class DatabaseSessionTests(SessionTestsMixin, TestCase): backend = DatabaseSession session_engine = "django.contrib.sessions.backends.db" @property def model(self): return self.backend.get_model_class() def test_session_str(self): "Session repr should be the session key." self.session["x"] = 1 self.session.save() session_key = self.session.session_key s = self.model.objects.get(session_key=session_key) self.assertEqual(str(s), session_key) def test_session_get_decoded(self): """ Test we can use Session.get_decoded to retrieve data stored in normal way """ self.session["x"] = 1 self.session.save() s = self.model.objects.get(session_key=self.session.session_key) self.assertEqual(s.get_decoded(), {"x": 1}) def test_sessionmanager_save(self): """ Test SessionManager.save method """ # Create a session self.session["y"] = 1 self.session.save() s = self.model.objects.get(session_key=self.session.session_key) # Change it self.model.objects.save(s.session_key, {"y": 2}, s.expire_date) # Clear cache, so that it will be retrieved from DB del self.session._session_cache self.assertEqual(self.session["y"], 2) def test_clearsessions_command(self): """ Test clearsessions command for clearing expired sessions. """ self.assertEqual(0, self.model.objects.count()) # One object in the future self.session["foo"] = "bar" self.session.set_expiry(3600) self.session.save() # One object in the past other_session = self.backend() other_session["foo"] = "bar" other_session.set_expiry(-3600) other_session.save() # Two sessions are in the database before clearsessions... self.assertEqual(2, self.model.objects.count()) with override_settings(SESSION_ENGINE=self.session_engine): management.call_command("clearsessions") # ... and one is deleted. self.assertEqual(1, self.model.objects.count()) async def test_aclear_expired(self): self.assertEqual(await self.model.objects.acount(), 0) # Object in the future. await self.session.aset("key", "value") await self.session.aset_expiry(3600) await self.session.asave() # Object in the past. other_session = self.backend() await other_session.aset("key", "value") await other_session.aset_expiry(-3600) await other_session.asave() # Two sessions are in the database before clearing expired. self.assertEqual(await self.model.objects.acount(), 2) await self.session.aclear_expired() await other_session.aclear_expired() self.assertEqual(await self.model.objects.acount(), 1) @override_settings(USE_TZ=True) class DatabaseSessionWithTimeZoneTests(DatabaseSessionTests): pass class CustomDatabaseSessionTests(DatabaseSessionTests): backend = CustomDatabaseSession session_engine = "sessions_tests.models" custom_session_cookie_age = 60 * 60 * 24 # One day. def test_extra_session_field(self): # Set the account ID to be picked up by a custom session storage # and saved to a custom session model database column. self.session["_auth_user_id"] = 42 self.session.save() # Make sure that the customized create_model_instance() was called. s = self.model.objects.get(session_key=self.session.session_key) self.assertEqual(s.account_id, 42) # Make the session "anonymous". self.session.pop("_auth_user_id") self.session.save() # Make sure that save() on an existing session did the right job. s = self.model.objects.get(session_key=self.session.session_key) self.assertIsNone(s.account_id) def test_custom_expiry_reset(self): self.session.set_expiry(None) self.session.set_expiry(10) self.session.set_expiry(None) self.assertEqual(self.session.get_expiry_age(), self.custom_session_cookie_age) async def test_custom_expiry_reset_async(self): await self.session.aset_expiry(None) await self.session.aset_expiry(10) await self.session.aset_expiry(None) self.assertEqual( await self.session.aget_expiry_age(), self.custom_session_cookie_age ) def test_default_expiry(self): self.assertEqual(self.session.get_expiry_age(), self.custom_session_cookie_age) self.session.set_expiry(0) self.assertEqual(self.session.get_expiry_age(), self.custom_session_cookie_age) async def test_default_expiry_async(self): self.assertEqual( await self.session.aget_expiry_age(), self.custom_session_cookie_age ) await self.session.aset_expiry(0) self.assertEqual( await self.session.aget_expiry_age(), self.custom_session_cookie_age ) class CacheDBSessionTests(SessionTestsMixin, TestCase): backend = CacheDBSession def test_exists_searches_cache_first(self): self.session.save() with self.assertNumQueries(0): self.assertIs(self.session.exists(self.session.session_key), True) # Some backends might issue a warning @ignore_warnings(module="django.core.cache.backends.base") def test_load_overlong_key(self): self.session._session_key = (string.ascii_letters + string.digits) * 20 self.assertEqual(self.session.load(), {}) @override_settings(SESSION_CACHE_ALIAS="sessions") def test_non_default_cache(self): # 21000 - CacheDB backend should respect SESSION_CACHE_ALIAS. with self.assertRaises(InvalidCacheBackendError): self.backend() @override_settings( CACHES={"default": {"BACKEND": "cache.failing_cache.CacheClass"}} ) def test_cache_set_failure_non_fatal(self): """Failing to write to the cache does not raise errors.""" session = self.backend() session["key"] = "val" with self.assertLogs("django.contrib.sessions", "ERROR") as cm: session.save() # A proper ERROR log message was recorded. log = cm.records[-1] self.assertEqual(log.message, f"Error saving to cache ({session._cache})")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_utils/__init__.py
tests/model_utils/__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_utils/tests.py
tests/model_utils/tests.py
from django.db.models.utils import create_namedtuple_class from django.test import SimpleTestCase class NamedTupleClassTests(SimpleTestCase): def test_immutability(self): row_class = create_namedtuple_class("field1", "field2") row = row_class("value1", "value2") with self.assertRaises(AttributeError): row.field3 = "value3"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/custom_lookups/models.py
tests/custom_lookups/models.py
from django.db import models class Author(models.Model): name = models.CharField(max_length=20) alias = models.CharField(max_length=20) age = models.IntegerField(null=True) birthdate = models.DateField(null=True) average_rating = models.FloatField(null=True) def __str__(self): return self.name class Article(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) class MySQLUnixTimestamp(models.Model): timestamp = models.PositiveIntegerField()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/custom_lookups/__init__.py
tests/custom_lookups/__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_lookups/tests.py
tests/custom_lookups/tests.py
import time import unittest from datetime import date, datetime from django.core.exceptions import FieldError from django.db import connection, models from django.db.models.fields.related_lookups import RelatedGreaterThan from django.db.models.functions import Lower from django.db.models.lookups import EndsWith, StartsWith from django.test import SimpleTestCase, TestCase, override_settings from django.test.utils import register_lookup from django.utils import timezone from .models import Article, Author, MySQLUnixTimestamp class Div3Lookup(models.Lookup): lookup_name = "div3" def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = (*lhs_params, *rhs_params) return "(%s) %%%% 3 = %s" % (lhs, rhs), params def as_oracle(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = (*lhs_params, *rhs_params) return "mod(%s, 3) = %s" % (lhs, rhs), params class Div3Transform(models.Transform): lookup_name = "div3" def as_sql(self, compiler, connection): lhs, lhs_params = compiler.compile(self.lhs) return "(%s) %%%% 3" % lhs, lhs_params def as_oracle(self, compiler, connection, **extra_context): lhs, lhs_params = compiler.compile(self.lhs) return "mod(%s, 3)" % lhs, lhs_params class Div3BilateralTransform(Div3Transform): bilateral = True class Mult3BilateralTransform(models.Transform): bilateral = True lookup_name = "mult3" def as_sql(self, compiler, connection): lhs, lhs_params = compiler.compile(self.lhs) return "3 * (%s)" % lhs, lhs_params class LastDigitTransform(models.Transform): lookup_name = "lastdigit" def as_sql(self, compiler, connection): lhs, lhs_params = compiler.compile(self.lhs) return "SUBSTR(CAST(%s AS CHAR(2)), 2, 1)" % lhs, lhs_params class UpperBilateralTransform(models.Transform): bilateral = True lookup_name = "upper" def as_sql(self, compiler, connection): lhs, lhs_params = compiler.compile(self.lhs) return "UPPER(%s)" % lhs, lhs_params class YearTransform(models.Transform): # Use a name that avoids collision with the built-in year lookup. lookup_name = "testyear" def as_sql(self, compiler, connection): lhs_sql, params = compiler.compile(self.lhs) return connection.ops.date_extract_sql("year", lhs_sql, params) @property def output_field(self): return models.IntegerField() @YearTransform.register_lookup class YearExact(models.lookups.Lookup): lookup_name = "exact" def as_sql(self, compiler, connection): # We will need to skip the extract part, and instead go # directly with the originating field, that is self.lhs.lhs lhs_sql, lhs_params = self.process_lhs(compiler, connection, self.lhs.lhs) rhs_sql, rhs_params = self.process_rhs(compiler, connection) # Note that we must be careful so that we have params in the # same order as we have the parts in the SQL. params = lhs_params + rhs_params + lhs_params + rhs_params # We use PostgreSQL specific SQL here. Note that we must do the # conversions in SQL instead of in Python to support F() references. return ( "%(lhs)s >= (%(rhs)s || '-01-01')::date " "AND %(lhs)s <= (%(rhs)s || '-12-31')::date" % {"lhs": lhs_sql, "rhs": rhs_sql}, params, ) @YearTransform.register_lookup class YearLte(models.lookups.LessThanOrEqual): """ The purpose of this lookup is to efficiently compare the year of the field. """ def as_sql(self, compiler, connection): # Skip the YearTransform above us (no possibility for efficient # lookup otherwise). real_lhs = self.lhs.lhs lhs_sql, params = self.process_lhs(compiler, connection, real_lhs) rhs_sql, rhs_params = self.process_rhs(compiler, connection) params = (*params, *rhs_params) # Build SQL where the integer year is concatenated with last month # and day, then convert that to date. (We try to have SQL like: # WHERE somecol <= '2013-12-31') # but also make it work if the rhs_sql is field reference. return "%s <= (%s || '-12-31')::date" % (lhs_sql, rhs_sql), params class Exactly(models.lookups.Exact): """ This lookup is used to test lookup registration. """ lookup_name = "exactly" def get_rhs_op(self, connection, rhs): return connection.operators["exact"] % rhs class SQLFuncMixin: def as_sql(self, compiler, connection): return "%s()" % self.name, [] @property def output_field(self): return CustomField() class SQLFuncLookup(SQLFuncMixin, models.Lookup): def __init__(self, name, *args, **kwargs): super().__init__(*args, **kwargs) self.name = name class SQLFuncTransform(SQLFuncMixin, models.Transform): def __init__(self, name, *args, **kwargs): super().__init__(*args, **kwargs) self.name = name class SQLFuncFactory: def __init__(self, key, name): self.key = key self.name = name def __call__(self, *args, **kwargs): if self.key == "lookupfunc": return SQLFuncLookup(self.name, *args, **kwargs) return SQLFuncTransform(self.name, *args, **kwargs) class CustomField(models.TextField): def get_lookup(self, lookup_name): if lookup_name.startswith("lookupfunc_"): key, name = lookup_name.split("_", 1) return SQLFuncFactory(key, name) return super().get_lookup(lookup_name) def get_transform(self, lookup_name): if lookup_name.startswith("transformfunc_"): key, name = lookup_name.split("_", 1) return SQLFuncFactory(key, name) return super().get_transform(lookup_name) class CustomModel(models.Model): field = CustomField() # We will register this class temporarily in the test method. class InMonth(models.lookups.Lookup): """ InMonth matches if the column's month is the same as value's month. """ lookup_name = "inmonth" def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) # We need to be careful so that we get the params in right # places. params = lhs_params + rhs_params + lhs_params + rhs_params return ( "%s >= date_trunc('month', %s) and " "%s < date_trunc('month', %s) + interval '1 months'" % (lhs, rhs, lhs, rhs), params, ) class DateTimeTransform(models.Transform): lookup_name = "as_datetime" @property def output_field(self): return models.DateTimeField() def as_sql(self, compiler, connection): lhs, params = compiler.compile(self.lhs) return "from_unixtime({})".format(lhs), params class CustomStartsWith(StartsWith): lookup_name = "sw" class CustomEndsWith(EndsWith): lookup_name = "ew" class RelatedMoreThan(RelatedGreaterThan): lookup_name = "rmt" class LookupTests(TestCase): def test_custom_name_lookup(self): a1 = Author.objects.create(name="a1", birthdate=date(1981, 2, 16)) Author.objects.create(name="a2", birthdate=date(2012, 2, 29)) with ( register_lookup(models.DateField, YearTransform), register_lookup(models.DateField, YearTransform, lookup_name="justtheyear"), register_lookup(YearTransform, Exactly), register_lookup(YearTransform, Exactly, lookup_name="isactually"), ): qs1 = Author.objects.filter(birthdate__testyear__exactly=1981) qs2 = Author.objects.filter(birthdate__justtheyear__isactually=1981) self.assertSequenceEqual(qs1, [a1]) self.assertSequenceEqual(qs2, [a1]) def test_custom_lookup_with_subquery(self): class NotEqual(models.Lookup): lookup_name = "ne" def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) # Although combining via (*lhs_params, *rhs_params) would be # more resilient, the "simple" way works too. params = lhs_params + rhs_params return "%s <> %s" % (lhs, rhs), params author = Author.objects.create(name="Isabella") with register_lookup(models.Field, NotEqual): qs = Author.objects.annotate( unknown_age=models.Subquery( Author.objects.filter(age__isnull=True) .order_by("name") .values("name")[:1] ) ).filter(unknown_age__ne="Plato") self.assertSequenceEqual(qs, [author]) qs = Author.objects.annotate( unknown_age=Lower( Author.objects.filter(age__isnull=True) .order_by("name") .values("name")[:1] ) ).filter(unknown_age__ne="plato") self.assertSequenceEqual(qs, [author]) def test_custom_exact_lookup_none_rhs(self): """ __exact=None is transformed to __isnull=True if a custom lookup class with lookup_name != 'exact' is registered as the `exact` lookup. """ field = Author._meta.get_field("birthdate") OldExactLookup = field.get_lookup("exact") author = Author.objects.create(name="author", birthdate=None) try: field.register_lookup(Exactly, "exact") self.assertEqual(Author.objects.get(birthdate__exact=None), author) finally: field.register_lookup(OldExactLookup, "exact") def test_basic_lookup(self): a1 = Author.objects.create(name="a1", age=1) a2 = Author.objects.create(name="a2", age=2) a3 = Author.objects.create(name="a3", age=3) a4 = Author.objects.create(name="a4", age=4) with register_lookup(models.IntegerField, Div3Lookup): self.assertSequenceEqual(Author.objects.filter(age__div3=0), [a3]) self.assertSequenceEqual( Author.objects.filter(age__div3=1).order_by("age"), [a1, a4] ) self.assertSequenceEqual(Author.objects.filter(age__div3=2), [a2]) self.assertSequenceEqual(Author.objects.filter(age__div3=3), []) @unittest.skipUnless( connection.vendor == "postgresql", "PostgreSQL specific SQL used" ) def test_birthdate_month(self): a1 = Author.objects.create(name="a1", birthdate=date(1981, 2, 16)) a2 = Author.objects.create(name="a2", birthdate=date(2012, 2, 29)) a3 = Author.objects.create(name="a3", birthdate=date(2012, 1, 31)) a4 = Author.objects.create(name="a4", birthdate=date(2012, 3, 1)) with register_lookup(models.DateField, InMonth): self.assertSequenceEqual( Author.objects.filter(birthdate__inmonth=date(2012, 1, 15)), [a3] ) self.assertSequenceEqual( Author.objects.filter(birthdate__inmonth=date(2012, 2, 1)), [a2] ) self.assertSequenceEqual( Author.objects.filter(birthdate__inmonth=date(1981, 2, 28)), [a1] ) self.assertSequenceEqual( Author.objects.filter(birthdate__inmonth=date(2012, 3, 12)), [a4] ) self.assertSequenceEqual( Author.objects.filter(birthdate__inmonth=date(2012, 4, 1)), [] ) def test_div3_extract(self): with register_lookup(models.IntegerField, Div3Transform): a1 = Author.objects.create(name="a1", age=1) a2 = Author.objects.create(name="a2", age=2) a3 = Author.objects.create(name="a3", age=3) a4 = Author.objects.create(name="a4", age=4) baseqs = Author.objects.order_by("name") self.assertSequenceEqual(baseqs.filter(age__div3=2), [a2]) self.assertSequenceEqual(baseqs.filter(age__div3__lte=3), [a1, a2, a3, a4]) self.assertSequenceEqual(baseqs.filter(age__div3__in=[0, 2]), [a2, a3]) self.assertSequenceEqual(baseqs.filter(age__div3__in=[2, 4]), [a2]) self.assertSequenceEqual(baseqs.filter(age__div3__gte=3), []) self.assertSequenceEqual( baseqs.filter(age__div3__range=(1, 2)), [a1, a2, a4] ) def test_foreignobject_lookup_registration(self): field = Article._meta.get_field("author") with register_lookup(models.ForeignObject, Exactly): self.assertIs(field.get_lookup("exactly"), Exactly) # ForeignObject should ignore regular Field lookups with register_lookup(models.Field, Exactly): self.assertIsNone(field.get_lookup("exactly")) def test_lookups_caching(self): field = Article._meta.get_field("author") # clear and re-cache field.get_class_lookups.cache_clear() self.assertNotIn("exactly", field.get_lookups()) # registration should bust the cache with register_lookup(models.ForeignObject, Exactly): # getting the lookups again should re-cache self.assertIn("exactly", field.get_lookups()) # Unregistration should bust the cache. self.assertNotIn("exactly", field.get_lookups()) class BilateralTransformTests(TestCase): def test_bilateral_upper(self): with register_lookup(models.CharField, UpperBilateralTransform): author1 = Author.objects.create(name="Doe") author2 = Author.objects.create(name="doe") author3 = Author.objects.create(name="Foo") self.assertCountEqual( Author.objects.filter(name__upper="doe"), [author1, author2], ) self.assertSequenceEqual( Author.objects.filter(name__upper__contains="f"), [author3], ) def test_bilateral_inner_qs(self): with register_lookup(models.CharField, UpperBilateralTransform): msg = "Bilateral transformations on nested querysets are not implemented." with self.assertRaisesMessage(NotImplementedError, msg): Author.objects.filter( name__upper__in=Author.objects.values_list("name") ) def test_bilateral_multi_value(self): with register_lookup(models.CharField, UpperBilateralTransform): Author.objects.bulk_create( [ Author(name="Foo"), Author(name="Bar"), Author(name="Ray"), ] ) self.assertQuerySetEqual( Author.objects.filter(name__upper__in=["foo", "bar", "doe"]).order_by( "name" ), ["Bar", "Foo"], lambda a: a.name, ) def test_div3_bilateral_extract(self): with register_lookup(models.IntegerField, Div3BilateralTransform): a1 = Author.objects.create(name="a1", age=1) a2 = Author.objects.create(name="a2", age=2) a3 = Author.objects.create(name="a3", age=3) a4 = Author.objects.create(name="a4", age=4) baseqs = Author.objects.order_by("name") self.assertSequenceEqual(baseqs.filter(age__div3=2), [a2]) self.assertSequenceEqual(baseqs.filter(age__div3__lte=3), [a3]) self.assertSequenceEqual(baseqs.filter(age__div3__in=[0, 2]), [a2, a3]) self.assertSequenceEqual(baseqs.filter(age__div3__in=[2, 4]), [a1, a2, a4]) self.assertSequenceEqual(baseqs.filter(age__div3__gte=3), [a1, a2, a3, a4]) self.assertSequenceEqual( baseqs.filter(age__div3__range=(1, 2)), [a1, a2, a4] ) def test_bilateral_order(self): with register_lookup( models.IntegerField, Mult3BilateralTransform, Div3BilateralTransform ): a1 = Author.objects.create(name="a1", age=1) a2 = Author.objects.create(name="a2", age=2) a3 = Author.objects.create(name="a3", age=3) a4 = Author.objects.create(name="a4", age=4) baseqs = Author.objects.order_by("name") # mult3__div3 always leads to 0 self.assertSequenceEqual( baseqs.filter(age__mult3__div3=42), [a1, a2, a3, a4] ) self.assertSequenceEqual(baseqs.filter(age__div3__mult3=42), [a3]) def test_transform_order_by(self): with register_lookup(models.IntegerField, LastDigitTransform): a1 = Author.objects.create(name="a1", age=11) a2 = Author.objects.create(name="a2", age=23) a3 = Author.objects.create(name="a3", age=32) a4 = Author.objects.create(name="a4", age=40) qs = Author.objects.order_by("age__lastdigit") self.assertSequenceEqual(qs, [a4, a1, a3, a2]) def test_bilateral_fexpr(self): with register_lookup(models.IntegerField, Mult3BilateralTransform): a1 = Author.objects.create(name="a1", age=1, average_rating=3.2) a2 = Author.objects.create(name="a2", age=2, average_rating=0.5) a3 = Author.objects.create(name="a3", age=3, average_rating=1.5) a4 = Author.objects.create(name="a4", age=4) baseqs = Author.objects.order_by("name") self.assertSequenceEqual( baseqs.filter(age__mult3=models.F("age")), [a1, a2, a3, a4] ) # Same as age >= average_rating self.assertSequenceEqual( baseqs.filter(age__mult3__gte=models.F("average_rating")), [a2, a3] ) @override_settings(USE_TZ=True) class DateTimeLookupTests(TestCase): @unittest.skipUnless(connection.vendor == "mysql", "MySQL specific SQL used") def test_datetime_output_field(self): with register_lookup(models.PositiveIntegerField, DateTimeTransform): ut = MySQLUnixTimestamp.objects.create(timestamp=time.time()) y2k = timezone.make_aware(datetime(2000, 1, 1)) self.assertSequenceEqual( MySQLUnixTimestamp.objects.filter(timestamp__as_datetime__gt=y2k), [ut] ) class YearLteTests(TestCase): @classmethod def setUpTestData(cls): cls.a1 = Author.objects.create(name="a1", birthdate=date(1981, 2, 16)) cls.a2 = Author.objects.create(name="a2", birthdate=date(2012, 2, 29)) cls.a3 = Author.objects.create(name="a3", birthdate=date(2012, 1, 31)) cls.a4 = Author.objects.create(name="a4", birthdate=date(2012, 3, 1)) def setUp(self): models.DateField.register_lookup(YearTransform) self.addCleanup(models.DateField._unregister_lookup, YearTransform) @unittest.skipUnless( connection.vendor == "postgresql", "PostgreSQL specific SQL used" ) def test_year_lte(self): baseqs = Author.objects.order_by("name") self.assertSequenceEqual( baseqs.filter(birthdate__testyear__lte=2012), [self.a1, self.a2, self.a3, self.a4], ) self.assertSequenceEqual( baseqs.filter(birthdate__testyear=2012), [self.a2, self.a3, self.a4] ) self.assertNotIn("BETWEEN", str(baseqs.filter(birthdate__testyear=2012).query)) self.assertSequenceEqual( baseqs.filter(birthdate__testyear__lte=2011), [self.a1] ) # The non-optimized version works, too. self.assertSequenceEqual(baseqs.filter(birthdate__testyear__lt=2012), [self.a1]) @unittest.skipUnless( connection.vendor == "postgresql", "PostgreSQL specific SQL used" ) def test_year_lte_fexpr(self): self.a2.age = 2011 self.a2.save() self.a3.age = 2012 self.a3.save() self.a4.age = 2013 self.a4.save() baseqs = Author.objects.order_by("name") self.assertSequenceEqual( baseqs.filter(birthdate__testyear__lte=models.F("age")), [self.a3, self.a4] ) self.assertSequenceEqual( baseqs.filter(birthdate__testyear__lt=models.F("age")), [self.a4] ) def test_year_lte_sql(self): # This test will just check the generated SQL for __lte. This # doesn't require running on PostgreSQL and spots the most likely # error - not running YearLte SQL at all. baseqs = Author.objects.order_by("name") self.assertIn( "<= (2011 || ", str(baseqs.filter(birthdate__testyear__lte=2011).query) ) self.assertIn("-12-31", str(baseqs.filter(birthdate__testyear__lte=2011).query)) def test_postgres_year_exact(self): baseqs = Author.objects.order_by("name") self.assertIn("= (2011 || ", str(baseqs.filter(birthdate__testyear=2011).query)) self.assertIn("-12-31", str(baseqs.filter(birthdate__testyear=2011).query)) def test_custom_implementation_year_exact(self): try: # Two ways to add a customized implementation for different # backends: # First is MonkeyPatch of the class. def as_custom_sql(self, compiler, connection): lhs_sql, lhs_params = self.process_lhs( compiler, connection, self.lhs.lhs ) rhs_sql, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params + lhs_params + rhs_params return ( "%(lhs)s >= " "str_to_date(concat(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') " "AND %(lhs)s <= " "str_to_date(concat(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')" % {"lhs": lhs_sql, "rhs": rhs_sql}, params, ) setattr(YearExact, "as_" + connection.vendor, as_custom_sql) self.assertIn( "concat(", str(Author.objects.filter(birthdate__testyear=2012).query) ) finally: delattr(YearExact, "as_" + connection.vendor) try: # The other way is to subclass the original lookup and register the # subclassed lookup instead of the original. class CustomYearExact(YearExact): # This method should be named "as_mysql" for MySQL, # "as_postgresql" for postgres and so on, but as we don't know # which DB we are running on, we need to use setattr. def as_custom_sql(self, compiler, connection): lhs_sql, lhs_params = self.process_lhs( compiler, connection, self.lhs.lhs ) rhs_sql, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params + lhs_params + rhs_params return ( "%(lhs)s >= " "str_to_date(CONCAT(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') " "AND %(lhs)s <= " "str_to_date(CONCAT(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')" % {"lhs": lhs_sql, "rhs": rhs_sql}, params, ) setattr( CustomYearExact, "as_" + connection.vendor, CustomYearExact.as_custom_sql, ) YearTransform.register_lookup(CustomYearExact) self.assertIn( "CONCAT(", str(Author.objects.filter(birthdate__testyear=2012).query) ) finally: YearTransform._unregister_lookup(CustomYearExact) YearTransform.register_lookup(YearExact) class TrackCallsYearTransform(YearTransform): # Use a name that avoids collision with the built-in year lookup. lookup_name = "testyear" call_order = [] def as_sql(self, compiler, connection): lhs_sql, params = compiler.compile(self.lhs) return connection.ops.date_extract_sql("year", lhs_sql), params @property def output_field(self): return models.IntegerField() def get_lookup(self, lookup_name): self.call_order.append("lookup") return super().get_lookup(lookup_name) def get_transform(self, lookup_name): self.call_order.append("transform") return super().get_transform(lookup_name) class LookupTransformCallOrderTests(SimpleTestCase): def test_call_order(self): with register_lookup(models.DateField, TrackCallsYearTransform): # junk lookup - tries lookup, then transform, then fails msg = ( "Unsupported lookup 'junk' for IntegerField or join on the field not " "permitted." ) with self.assertRaisesMessage(FieldError, msg): Author.objects.filter(birthdate__testyear__junk=2012) self.assertEqual( TrackCallsYearTransform.call_order, ["lookup", "transform"] ) TrackCallsYearTransform.call_order = [] # junk transform - tries transform only, then fails msg = ( "Unsupported lookup 'junk__more_junk' for IntegerField or join" " on the field not permitted." ) with self.assertRaisesMessage(FieldError, msg): Author.objects.filter(birthdate__testyear__junk__more_junk=2012) self.assertEqual(TrackCallsYearTransform.call_order, ["transform"]) TrackCallsYearTransform.call_order = [] # Just getting the year (implied __exact) - lookup only Author.objects.filter(birthdate__testyear=2012) self.assertEqual(TrackCallsYearTransform.call_order, ["lookup"]) TrackCallsYearTransform.call_order = [] # Just getting the year (explicit __exact) - lookup only Author.objects.filter(birthdate__testyear__exact=2012) self.assertEqual(TrackCallsYearTransform.call_order, ["lookup"]) class CustomizedMethodsTests(SimpleTestCase): def test_overridden_get_lookup(self): q = CustomModel.objects.filter(field__lookupfunc_monkeys=3) self.assertIn("monkeys()", str(q.query)) def test_overridden_get_transform(self): q = CustomModel.objects.filter(field__transformfunc_banana=3) self.assertIn("banana()", str(q.query)) def test_overridden_get_lookup_chain(self): q = CustomModel.objects.filter( field__transformfunc_banana__lookupfunc_elephants=3 ) self.assertIn("elephants()", str(q.query)) def test_overridden_get_transform_chain(self): q = CustomModel.objects.filter( field__transformfunc_banana__transformfunc_pear=3 ) self.assertIn("pear()", str(q.query)) class SubqueryTransformTests(TestCase): def test_subquery_usage(self): with register_lookup(models.IntegerField, Div3Transform): Author.objects.create(name="a1", age=1) a2 = Author.objects.create(name="a2", age=2) Author.objects.create(name="a3", age=3) Author.objects.create(name="a4", age=4) qs = Author.objects.order_by("name").filter( id__in=Author.objects.filter(age__div3=2) ) self.assertSequenceEqual(qs, [a2]) class RegisterLookupTests(SimpleTestCase): def test_class_lookup(self): author_name = Author._meta.get_field("name") with register_lookup(models.CharField, CustomStartsWith): self.assertEqual(author_name.get_lookup("sw"), CustomStartsWith) self.assertIsNone(author_name.get_lookup("sw")) def test_instance_lookup(self): author_name = Author._meta.get_field("name") author_alias = Author._meta.get_field("alias") with register_lookup(author_name, CustomStartsWith): self.assertEqual(author_name.instance_lookups, {"sw": CustomStartsWith}) self.assertEqual(author_name.get_lookup("sw"), CustomStartsWith) self.assertIsNone(author_alias.get_lookup("sw")) self.assertIsNone(author_name.get_lookup("sw")) self.assertEqual(author_name.instance_lookups, {}) self.assertIsNone(author_alias.get_lookup("sw")) def test_instance_lookup_override_class_lookups(self): author_name = Author._meta.get_field("name") author_alias = Author._meta.get_field("alias") with register_lookup(models.CharField, CustomStartsWith, lookup_name="st_end"): with register_lookup(author_alias, CustomEndsWith, lookup_name="st_end"): self.assertEqual(author_name.get_lookup("st_end"), CustomStartsWith) self.assertEqual(author_alias.get_lookup("st_end"), CustomEndsWith) self.assertEqual(author_name.get_lookup("st_end"), CustomStartsWith) self.assertEqual(author_alias.get_lookup("st_end"), CustomStartsWith) self.assertIsNone(author_name.get_lookup("st_end")) self.assertIsNone(author_alias.get_lookup("st_end")) def test_instance_lookup_override(self): author_name = Author._meta.get_field("name") with register_lookup(author_name, CustomStartsWith, lookup_name="st_end"): self.assertEqual(author_name.get_lookup("st_end"), CustomStartsWith) author_name.register_lookup(CustomEndsWith, lookup_name="st_end") self.assertEqual(author_name.get_lookup("st_end"), CustomEndsWith) self.assertIsNone(author_name.get_lookup("st_end")) def test_lookup_on_transform(self): transform = Div3Transform with register_lookup(Div3Transform, CustomStartsWith): with register_lookup(Div3Transform, CustomEndsWith): self.assertEqual( transform.get_lookups(), {"sw": CustomStartsWith, "ew": CustomEndsWith}, ) self.assertEqual(transform.get_lookups(), {"sw": CustomStartsWith}) self.assertEqual(transform.get_lookups(), {}) def test_transform_on_field(self): author_name = Author._meta.get_field("name") author_alias = Author._meta.get_field("alias") with register_lookup(models.CharField, Div3Transform): self.assertEqual(author_alias.get_transform("div3"), Div3Transform) self.assertEqual(author_name.get_transform("div3"), Div3Transform) with register_lookup(author_alias, Div3Transform): self.assertEqual(author_alias.get_transform("div3"), Div3Transform) self.assertIsNone(author_name.get_transform("div3")) self.assertIsNone(author_alias.get_transform("div3")) self.assertIsNone(author_name.get_transform("div3")) def test_related_lookup(self): article_author = Article._meta.get_field("author") with register_lookup(models.Field, CustomStartsWith): self.assertIsNone(article_author.get_lookup("sw")) with register_lookup(models.ForeignKey, RelatedMoreThan): self.assertEqual(article_author.get_lookup("rmt"), RelatedMoreThan) def test_instance_related_lookup(self): article_author = Article._meta.get_field("author") with register_lookup(article_author, RelatedMoreThan): self.assertEqual(article_author.get_lookup("rmt"), RelatedMoreThan) self.assertIsNone(article_author.get_lookup("rmt"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/distinct_on_fields/models.py
tests/distinct_on_fields/models.py
from django.db import models class Tag(models.Model): name = models.CharField(max_length=10) parent = models.ForeignKey( "self", models.SET_NULL, blank=True, null=True, related_name="children", ) class Meta: ordering = ["name"] def __str__(self): return self.name class Celebrity(models.Model): name = models.CharField("Name", max_length=20) greatest_fan = models.ForeignKey( "Fan", models.SET_NULL, null=True, unique=True, ) def __str__(self): return self.name class Fan(models.Model): fan_of = models.ForeignKey(Celebrity, models.CASCADE) class Staff(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) organisation = models.CharField(max_length=100) tags = models.ManyToManyField(Tag, through="StaffTag") coworkers = models.ManyToManyField("self") def __str__(self): return self.name class StaffTag(models.Model): staff = models.ForeignKey(Staff, models.CASCADE) tag = models.ForeignKey(Tag, models.CASCADE) def __str__(self): return "%s -> %s" % (self.tag, self.staff)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/distinct_on_fields/__init__.py
tests/distinct_on_fields/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/distinct_on_fields/tests.py
tests/distinct_on_fields/tests.py
from django.db import connection from django.db.models import CharField, F, Max from django.db.models.functions import Lower from django.test import TestCase, skipUnlessDBFeature from django.test.utils import register_lookup from .models import Celebrity, Fan, Staff, StaffTag, Tag @skipUnlessDBFeature("can_distinct_on_fields") @skipUnlessDBFeature("supports_nullable_unique_constraints") class DistinctOnTests(TestCase): @classmethod def setUpTestData(cls): cls.t1 = Tag.objects.create(name="t1") cls.t2 = Tag.objects.create(name="t2", parent=cls.t1) cls.t3 = Tag.objects.create(name="t3", parent=cls.t1) cls.t4 = Tag.objects.create(name="t4", parent=cls.t3) cls.t5 = Tag.objects.create(name="t5", parent=cls.t3) cls.p1_o1 = Staff.objects.create(id=1, name="p1", organisation="o1") cls.p2_o1 = Staff.objects.create(id=2, name="p2", organisation="o1") cls.p3_o1 = Staff.objects.create(id=3, name="p3", organisation="o1") cls.p1_o2 = Staff.objects.create(id=4, name="p1", organisation="o2") cls.p1_o1.coworkers.add(cls.p2_o1, cls.p3_o1) cls.st1 = StaffTag.objects.create(staff=cls.p1_o1, tag=cls.t1) StaffTag.objects.create(staff=cls.p1_o1, tag=cls.t1) cls.celeb1 = Celebrity.objects.create(name="c1") cls.celeb2 = Celebrity.objects.create(name="c2") cls.fan1 = Fan.objects.create(fan_of=cls.celeb1) cls.fan2 = Fan.objects.create(fan_of=cls.celeb1) cls.fan3 = Fan.objects.create(fan_of=cls.celeb2) def test_basic_distinct_on(self): """QuerySet.distinct('field', ...) works""" # (qset, expected) tuples qsets = ( ( Staff.objects.distinct().order_by("name"), [self.p1_o1, self.p1_o2, self.p2_o1, self.p3_o1], ), ( Staff.objects.distinct("name").order_by("name"), [self.p1_o1, self.p2_o1, self.p3_o1], ), ( Staff.objects.distinct("organisation").order_by("organisation", "name"), [self.p1_o1, self.p1_o2], ), ( Staff.objects.distinct("name", "organisation").order_by( "name", "organisation" ), [self.p1_o1, self.p1_o2, self.p2_o1, self.p3_o1], ), ( Celebrity.objects.filter(fan__in=[self.fan1, self.fan2, self.fan3]) .distinct("name") .order_by("name"), [self.celeb1, self.celeb2], ), # Does combining querysets work? ( ( Celebrity.objects.filter(fan__in=[self.fan1, self.fan2]) .distinct("name") .order_by("name") | Celebrity.objects.filter(fan__in=[self.fan3]) .distinct("name") .order_by("name") ), [self.celeb1, self.celeb2], ), (StaffTag.objects.distinct("staff", "tag"), [self.st1]), ( Tag.objects.order_by("parent__pk", "pk").distinct("parent"), ( [self.t2, self.t4, self.t1] if connection.features.nulls_order_largest else [self.t1, self.t2, self.t4] ), ), ( StaffTag.objects.select_related("staff") .distinct("staff__name") .order_by("staff__name"), [self.st1], ), # Fetch the alphabetically first coworker for each worker ( ( Staff.objects.distinct("id") .order_by("id", "coworkers__name") .values_list("id", "coworkers__name") ), [(1, "p2"), (2, "p1"), (3, "p1"), (4, None)], ), ) for qset, expected in qsets: self.assertSequenceEqual(qset, expected) self.assertEqual(qset.count(), len(expected)) # Combining queries with non-unique query is not allowed. base_qs = Celebrity.objects.all() msg = "Cannot combine a unique query with a non-unique query." with self.assertRaisesMessage(TypeError, msg): base_qs.distinct("id") & base_qs # Combining queries with different distinct_fields is not allowed. msg = "Cannot combine queries with different distinct fields." with self.assertRaisesMessage(TypeError, msg): base_qs.distinct("id") & base_qs.distinct("name") # Test join unreffing c1 = Celebrity.objects.distinct("greatest_fan__id", "greatest_fan__fan_of") self.assertIn("OUTER JOIN", str(c1.query)) c2 = c1.distinct("pk") self.assertNotIn("OUTER JOIN", str(c2.query)) def test_sliced_queryset(self): msg = "Cannot create distinct fields once a slice has been taken." with self.assertRaisesMessage(TypeError, msg): Staff.objects.all()[0:5].distinct("name") def test_transform(self): new_name = self.t1.name.upper() self.assertNotEqual(self.t1.name, new_name) Tag.objects.create(name=new_name) with register_lookup(CharField, Lower): self.assertCountEqual( Tag.objects.order_by().distinct("name__lower"), [self.t1, self.t2, self.t3, self.t4, self.t5], ) def test_distinct_not_implemented_checks(self): # distinct + annotate not allowed msg = "annotate() + distinct(fields) is not implemented." with self.assertRaisesMessage(NotImplementedError, msg): Celebrity.objects.annotate(Max("id")).distinct("id")[0] with self.assertRaisesMessage(NotImplementedError, msg): Celebrity.objects.distinct("id").annotate(Max("id"))[0] # However this check is done only when the query executes, so you # can use distinct() to remove the fields before execution. Celebrity.objects.distinct("id").annotate(Max("id")).distinct()[0] # distinct + aggregate not allowed msg = "aggregate() + distinct(fields) not implemented." with self.assertRaisesMessage(NotImplementedError, msg): Celebrity.objects.distinct("id").aggregate(Max("id")) def test_distinct_on_in_ordered_subquery(self): qs = Staff.objects.distinct("name").order_by("name", "id") qs = Staff.objects.filter(pk__in=qs).order_by("name") self.assertSequenceEqual(qs, [self.p1_o1, self.p2_o1, self.p3_o1]) qs = Staff.objects.distinct("name").order_by("name", "-id") qs = Staff.objects.filter(pk__in=qs).order_by("name") self.assertSequenceEqual(qs, [self.p1_o2, self.p2_o1, self.p3_o1]) def test_distinct_on_get_ordering_preserved(self): """ Ordering shouldn't be cleared when distinct on fields are specified. refs #25081 """ staff = ( Staff.objects.distinct("name") .order_by("name", "-organisation") .get(name="p1") ) self.assertEqual(staff.organisation, "o2") def test_distinct_on_mixed_case_annotation(self): qs = ( Staff.objects.annotate( nAmEAlIaS=F("name"), ) .distinct("nAmEAlIaS") .order_by("nAmEAlIaS") ) self.assertSequenceEqual(qs, [self.p1_o1, self.p2_o1, self.p3_o1]) def test_disallowed_update_distinct_on(self): qs = Staff.objects.distinct("organisation").order_by("organisation") msg = "Cannot call update() after .distinct(*fields)." with self.assertRaisesMessage(TypeError, msg): qs.update(name="p4")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/context_processors/views.py
tests/context_processors/views.py
from django.shortcuts import render from .models import DebugObject def request_processor(request): return render(request, "context_processors/request_attrs.html") def debug_processor(request): context = { "debug_objects": DebugObject.objects, "other_debug_objects": DebugObject.objects.using("other"), } return render(request, "context_processors/debug.html", context) def csp_nonce_processor(request): return render(request, "context_processors/csp_nonce.html")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/context_processors/models.py
tests/context_processors/models.py
from django.db import models class DebugObject(models.Model): pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/context_processors/__init__.py
tests/context_processors/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/context_processors/tests.py
tests/context_processors/tests.py
""" Tests for Django's bundled context processors. """ from django.test import SimpleTestCase, TestCase, modify_settings, override_settings from django.utils.csp import CSP @override_settings( ROOT_URLCONF="context_processors.urls", TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.request", ], }, } ], ) class RequestContextProcessorTests(SimpleTestCase): """ Tests for the ``django.template.context_processors.request`` processor. """ def test_request_attributes(self): """ The request object is available in the template and that its attributes can't be overridden by GET and POST parameters (#3828). """ url = "/request_attrs/" # We should have the request object in the template. response = self.client.get(url) self.assertContains(response, "Have request") # Test is_secure. response = self.client.get(url) self.assertContains(response, "Not secure") response = self.client.get(url, {"is_secure": "blah"}) self.assertContains(response, "Not secure") response = self.client.post(url, {"is_secure": "blah"}) self.assertContains(response, "Not secure") # Test path. response = self.client.get(url) self.assertContains(response, url) response = self.client.get(url, {"path": "/blah/"}) self.assertContains(response, url) response = self.client.post(url, {"path": "/blah/"}) self.assertContains(response, url) @override_settings( DEBUG=True, INTERNAL_IPS=["127.0.0.1"], ROOT_URLCONF="context_processors.urls", TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", ], }, } ], ) class DebugContextProcessorTests(TestCase): """ Tests for the ``django.template.context_processors.debug`` processor. """ databases = {"default", "other"} def test_debug(self): url = "/debug/" # We should have the debug flag in the template. response = self.client.get(url) self.assertContains(response, "Have debug") # And now we should not with override_settings(DEBUG=False): response = self.client.get(url) self.assertNotContains(response, "Have debug") def test_sql_queries(self): """ Test whether sql_queries represents the actual amount of queries executed. (#23364) """ url = "/debug/" response = self.client.get(url) self.assertContains(response, "First query list: 0") self.assertContains(response, "Second query list: 1") # Check we have not actually memoized connection.queries self.assertContains(response, "Third query list: 2") # Check queries for DB connection 'other' self.assertContains(response, "Fourth query list: 3") @override_settings( ROOT_URLCONF="context_processors.urls", TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.csp", ], }, } ], MIDDLEWARE=[ "django.middleware.csp.ContentSecurityPolicyMiddleware", ], SECURE_CSP={ "script-src": [CSP.SELF, CSP.NONCE], }, ) class CSPContextProcessorTests(TestCase): """ Tests for the django.template.context_processors.csp_nonce processor. """ def test_csp_nonce_in_context(self): response = self.client.get("/csp_nonce/") self.assertIn("csp_nonce", response.context) @modify_settings( MIDDLEWARE={"remove": "django.middleware.csp.ContentSecurityPolicyMiddleware"} ) def test_csp_nonce_in_context_no_middleware(self): response = self.client.get("/csp_nonce/") self.assertIn("csp_nonce", response.context) def test_csp_nonce_in_header(self): response = self.client.get("/csp_nonce/") self.assertIn(CSP.HEADER_ENFORCE, response.headers) csp_header = response.headers[CSP.HEADER_ENFORCE] nonce = response.context["csp_nonce"] self.assertIn(f"'nonce-{nonce}'", csp_header) def test_different_nonce_per_request(self): response1 = self.client.get("/csp_nonce/") response2 = self.client.get("/csp_nonce/") self.assertNotEqual( response1.context["csp_nonce"], response2.context["csp_nonce"], ) def test_csp_nonce_in_template(self): response = self.client.get("/csp_nonce/") nonce = response.context["csp_nonce"] self.assertIn(f'<script nonce="{nonce}">', response.text) def test_csp_nonce_length(self): response = self.client.get("/csp_nonce/") nonce = response.context["csp_nonce"] self.assertEqual(len(nonce), 22) # Based on secrets.token_urlsafe of 16 bytes.
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/context_processors/urls.py
tests/context_processors/urls.py
from django.urls import path from . import views urlpatterns = [ path("request_attrs/", views.request_processor), path("debug/", views.debug_processor), path("csp_nonce/", views.csp_nonce_processor), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/delete/models.py
tests/delete/models.py
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models class P(models.Model): pass class R(models.Model): is_default = models.BooleanField(default=False) p = models.ForeignKey(P, models.CASCADE, null=True) def get_default_r(): return R.objects.get_or_create(is_default=True)[0].pk class S(models.Model): r = models.ForeignKey(R, models.CASCADE) class T(models.Model): s = models.ForeignKey(S, models.CASCADE) class U(models.Model): t = models.ForeignKey(T, models.CASCADE) class RChild(R): pass class RProxy(R): class Meta: proxy = True class RChildChild(RChild): pass class RelatedDbOptionGrandParent(models.Model): pass class RelatedDbOptionParent(models.Model): p = models.ForeignKey(RelatedDbOptionGrandParent, models.DB_CASCADE, null=True) class Meta: required_db_features = {"supports_on_delete_db_cascade"} class CascadeDbModel(models.Model): name = models.CharField(max_length=30) db_cascade = models.ForeignKey( RelatedDbOptionParent, models.DB_CASCADE, related_name="db_cascade_set" ) class Meta: required_db_features = {"supports_on_delete_db_cascade"} class SetNullDbModel(models.Model): db_setnull = models.ForeignKey( RelatedDbOptionParent, models.DB_SET_NULL, null=True, related_name="db_setnull_set", ) class Meta: required_db_features = {"supports_on_delete_db_null"} class SetDefaultDbModel(models.Model): db_setdefault = models.ForeignKey( RelatedDbOptionParent, models.DB_SET_DEFAULT, db_default=models.Value(1), related_name="db_setdefault_set", ) db_setdefault_none = models.ForeignKey( RelatedDbOptionParent, models.DB_SET_DEFAULT, db_default=None, null=True, related_name="db_setnull_nullable_set", ) class Meta: required_db_features = {"supports_on_delete_db_default"} class A(models.Model): name = models.CharField(max_length=30) auto = models.ForeignKey(R, models.CASCADE, related_name="auto_set") auto_nullable = models.ForeignKey( R, models.CASCADE, null=True, related_name="auto_nullable_set" ) setvalue = models.ForeignKey(R, models.SET(get_default_r), related_name="setvalue") setnull = models.ForeignKey( R, models.SET_NULL, null=True, related_name="setnull_set" ) setdefault = models.ForeignKey( R, models.SET_DEFAULT, default=get_default_r, related_name="setdefault_set" ) setdefault_none = models.ForeignKey( R, models.SET_DEFAULT, default=None, null=True, related_name="setnull_nullable_set", ) cascade = models.ForeignKey(R, models.CASCADE, related_name="cascade_set") cascade_nullable = models.ForeignKey( R, models.CASCADE, null=True, related_name="cascade_nullable_set" ) protect = models.ForeignKey( R, models.PROTECT, null=True, related_name="protect_set" ) restrict = models.ForeignKey( R, models.RESTRICT, null=True, related_name="restrict_set" ) donothing = models.ForeignKey( R, models.DO_NOTHING, null=True, related_name="donothing_set" ) child = models.ForeignKey(RChild, models.CASCADE, related_name="child") child_setnull = models.ForeignKey( RChild, models.SET_NULL, null=True, related_name="child_setnull" ) cascade_p = models.ForeignKey( P, models.CASCADE, related_name="cascade_p_set", null=True ) # A OneToOneField is just a ForeignKey unique=True, so we don't duplicate # all the tests; just one smoke test to ensure on_delete works for it as # well. o2o_setnull = models.ForeignKey( R, models.SET_NULL, null=True, related_name="o2o_nullable_set" ) class B(models.Model): protect = models.ForeignKey(R, models.PROTECT) def create_a(name): a = A(name=name) for name in ( "auto", "auto_nullable", "setvalue", "setnull", "setdefault", "setdefault_none", "cascade", "cascade_nullable", "protect", "restrict", "donothing", "o2o_setnull", ): r = R.objects.create() setattr(a, name, r) a.child = RChild.objects.create() a.child_setnull = RChild.objects.create() a.save() return a class M(models.Model): m2m = models.ManyToManyField(R, related_name="m_set") m2m_through = models.ManyToManyField(R, through="MR", related_name="m_through_set") m2m_through_null = models.ManyToManyField( R, through="MRNull", related_name="m_through_null_set" ) class MR(models.Model): m = models.ForeignKey(M, models.CASCADE) r = models.ForeignKey(R, models.CASCADE) class MRNull(models.Model): m = models.ForeignKey(M, models.CASCADE) r = models.ForeignKey(R, models.SET_NULL, null=True) class Avatar(models.Model): desc = models.TextField(null=True) # This model is used to test a duplicate query regression (#25685) class AvatarProxy(Avatar): class Meta: proxy = True class User(models.Model): avatar = models.ForeignKey(Avatar, models.CASCADE, null=True) class HiddenUser(models.Model): r = models.ForeignKey(R, models.CASCADE, related_name="+") class HiddenUserProfile(models.Model): user = models.ForeignKey(HiddenUser, models.CASCADE) class M2MTo(models.Model): pass class M2MFrom(models.Model): m2m = models.ManyToManyField(M2MTo) class Parent(models.Model): pass class Child(Parent): pass class Base(models.Model): pass class RelToBase(models.Model): base = models.ForeignKey(Base, models.DO_NOTHING, related_name="rels") class Origin(models.Model): r_proxy = models.ForeignKey("RProxy", models.CASCADE, null=True) class Referrer(models.Model): origin = models.ForeignKey(Origin, models.CASCADE) unique_field = models.IntegerField(unique=True) large_field = models.TextField() class SecondReferrer(models.Model): referrer = models.ForeignKey(Referrer, models.CASCADE) other_referrer = models.ForeignKey( Referrer, models.CASCADE, to_field="unique_field", related_name="+" ) class DeleteTop(models.Model): b1 = GenericRelation("GenericB1") b2 = GenericRelation("GenericB2") class B1(models.Model): delete_top = models.ForeignKey(DeleteTop, models.CASCADE) class B2(models.Model): delete_top = models.ForeignKey(DeleteTop, models.CASCADE) class B3(models.Model): restrict = models.ForeignKey(R, models.RESTRICT) class DeleteBottom(models.Model): b1 = models.ForeignKey(B1, models.RESTRICT) b2 = models.ForeignKey(B2, models.CASCADE) class GenericB1(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() generic_delete_top = GenericForeignKey("content_type", "object_id") class GenericB2(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() generic_delete_top = GenericForeignKey("content_type", "object_id") generic_delete_bottom = GenericRelation("GenericDeleteBottom") class GenericDeleteBottom(models.Model): generic_b1 = models.ForeignKey(GenericB1, models.RESTRICT) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() generic_b2 = GenericForeignKey() class GenericDeleteBottomParent(models.Model): generic_delete_bottom = models.ForeignKey( GenericDeleteBottom, 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/delete/__init__.py
tests/delete/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/delete/tests.py
tests/delete/tests.py
from math import ceil from django.db import connection, models from django.db.models import ProtectedError, Q, RestrictedError from django.db.models.deletion import Collector from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from .models import ( B1, B2, B3, MR, A, Avatar, B, Base, CascadeDbModel, Child, DeleteBottom, DeleteTop, GenericB1, GenericB2, GenericDeleteBottom, HiddenUser, HiddenUserProfile, M, M2MFrom, M2MTo, MRNull, Origin, P, Parent, R, RChild, RChildChild, Referrer, RelatedDbOptionGrandParent, RelatedDbOptionParent, RProxy, S, SetDefaultDbModel, SetNullDbModel, T, User, create_a, get_default_r, ) class OnDeleteTests(TestCase): def setUp(self): self.DEFAULT = get_default_r() def test_auto(self): a = create_a("auto") a.auto.delete() self.assertFalse(A.objects.filter(name="auto").exists()) def test_non_callable(self): msg = "on_delete must be callable." with self.assertRaisesMessage(TypeError, msg): models.ForeignKey("self", on_delete=None) with self.assertRaisesMessage(TypeError, msg): models.OneToOneField("self", on_delete=None) def test_auto_nullable(self): a = create_a("auto_nullable") a.auto_nullable.delete() self.assertFalse(A.objects.filter(name="auto_nullable").exists()) def test_setvalue(self): a = create_a("setvalue") a.setvalue.delete() a = A.objects.get(pk=a.pk) self.assertEqual(self.DEFAULT, a.setvalue.pk) def test_setnull(self): a = create_a("setnull") a.setnull.delete() a = A.objects.get(pk=a.pk) self.assertIsNone(a.setnull) @skipUnlessDBFeature("supports_on_delete_db_null") def test_db_setnull(self): a = SetNullDbModel.objects.create( db_setnull=RelatedDbOptionParent.objects.create() ) a.db_setnull.delete() a = SetNullDbModel.objects.get(pk=a.pk) self.assertIsNone(a.db_setnull) def test_setdefault(self): a = create_a("setdefault") a.setdefault.delete() a = A.objects.get(pk=a.pk) self.assertEqual(self.DEFAULT, a.setdefault.pk) @skipUnlessDBFeature("supports_on_delete_db_default") def test_db_setdefault(self): # Object cannot be created on the module initialization, use hardcoded # PKs instead. r = RelatedDbOptionParent.objects.create(pk=2) default_r = RelatedDbOptionParent.objects.create(pk=1) set_default_db_obj = SetDefaultDbModel.objects.create(db_setdefault=r) set_default_db_obj.db_setdefault.delete() set_default_db_obj = SetDefaultDbModel.objects.get(pk=set_default_db_obj.pk) self.assertEqual(set_default_db_obj.db_setdefault, default_r) def test_setdefault_none(self): a = create_a("setdefault_none") a.setdefault_none.delete() a = A.objects.get(pk=a.pk) self.assertIsNone(a.setdefault_none) @skipUnlessDBFeature("supports_on_delete_db_default") def test_db_setdefault_none(self): # Object cannot be created on the module initialization, use hardcoded # PKs instead. r = RelatedDbOptionParent.objects.create(pk=2) default_r = RelatedDbOptionParent.objects.create(pk=1) set_default_db_obj = SetDefaultDbModel.objects.create( db_setdefault_none=r, db_setdefault=default_r ) set_default_db_obj.db_setdefault_none.delete() set_default_db_obj = SetDefaultDbModel.objects.get(pk=set_default_db_obj.pk) self.assertIsNone(set_default_db_obj.db_setdefault_none) def test_cascade(self): a = create_a("cascade") a.cascade.delete() self.assertFalse(A.objects.filter(name="cascade").exists()) def test_cascade_nullable(self): a = create_a("cascade_nullable") a.cascade_nullable.delete() self.assertFalse(A.objects.filter(name="cascade_nullable").exists()) def test_protect(self): a = create_a("protect") msg = ( "Cannot delete some instances of model 'R' because they are " "referenced through protected foreign keys: 'A.protect'." ) with self.assertRaisesMessage(ProtectedError, msg) as cm: a.protect.delete() self.assertEqual(cm.exception.protected_objects, {a}) def test_protect_multiple(self): a = create_a("protect") b = B.objects.create(protect=a.protect) msg = ( "Cannot delete some instances of model 'R' because they are " "referenced through protected foreign keys: 'A.protect', " "'B.protect'." ) with self.assertRaisesMessage(ProtectedError, msg) as cm: a.protect.delete() self.assertEqual(cm.exception.protected_objects, {a, b}) def test_protect_path(self): a = create_a("protect") a.protect.p = P.objects.create() a.protect.save() msg = ( "Cannot delete some instances of model 'P' because they are " "referenced through protected foreign keys: 'R.p'." ) with self.assertRaisesMessage(ProtectedError, msg) as cm: a.protect.p.delete() self.assertEqual(cm.exception.protected_objects, {a}) def test_do_nothing(self): # Testing DO_NOTHING is a bit harder: It would raise IntegrityError for # a normal model, so we connect to pre_delete and set the fk to a known # value. replacement_r = R.objects.create() def check_do_nothing(sender, **kwargs): obj = kwargs["instance"] obj.donothing_set.update(donothing=replacement_r) models.signals.pre_delete.connect(check_do_nothing) a = create_a("do_nothing") a.donothing.delete() a = A.objects.get(pk=a.pk) self.assertEqual(replacement_r, a.donothing) models.signals.pre_delete.disconnect(check_do_nothing) def test_do_nothing_qscount(self): """ A models.DO_NOTHING relation doesn't trigger a query. """ b = Base.objects.create() with self.assertNumQueries(1): # RelToBase should not be queried. b.delete() self.assertEqual(Base.objects.count(), 0) def test_inheritance_cascade_up(self): child = RChild.objects.create() child.delete() self.assertFalse(R.objects.filter(pk=child.pk).exists()) def test_inheritance_cascade_down(self): child = RChild.objects.create() parent = child.r_ptr parent.delete() self.assertFalse(RChild.objects.filter(pk=child.pk).exists()) def test_cascade_from_child(self): a = create_a("child") a.child.delete() self.assertFalse(A.objects.filter(name="child").exists()) self.assertFalse(R.objects.filter(pk=a.child_id).exists()) def test_cascade_from_parent(self): a = create_a("child") R.objects.get(pk=a.child_id).delete() self.assertFalse(A.objects.filter(name="child").exists()) self.assertFalse(RChild.objects.filter(pk=a.child_id).exists()) def test_setnull_from_child(self): a = create_a("child_setnull") a.child_setnull.delete() self.assertFalse(R.objects.filter(pk=a.child_setnull_id).exists()) a = A.objects.get(pk=a.pk) self.assertIsNone(a.child_setnull) def test_setnull_from_parent(self): a = create_a("child_setnull") R.objects.get(pk=a.child_setnull_id).delete() self.assertFalse(RChild.objects.filter(pk=a.child_setnull_id).exists()) a = A.objects.get(pk=a.pk) self.assertIsNone(a.child_setnull) def test_o2o_setnull(self): a = create_a("o2o_setnull") a.o2o_setnull.delete() a = A.objects.get(pk=a.pk) self.assertIsNone(a.o2o_setnull) def test_restrict(self): a = create_a("restrict") msg = ( "Cannot delete some instances of model 'R' because they are " "referenced through restricted foreign keys: 'A.restrict'." ) with self.assertRaisesMessage(RestrictedError, msg) as cm: a.restrict.delete() self.assertEqual(cm.exception.restricted_objects, {a}) def test_restrict_multiple(self): a = create_a("restrict") b3 = B3.objects.create(restrict=a.restrict) msg = ( "Cannot delete some instances of model 'R' because they are " "referenced through restricted foreign keys: 'A.restrict', " "'B3.restrict'." ) with self.assertRaisesMessage(RestrictedError, msg) as cm: a.restrict.delete() self.assertEqual(cm.exception.restricted_objects, {a, b3}) def test_restrict_path_cascade_indirect(self): a = create_a("restrict") a.restrict.p = P.objects.create() a.restrict.save() msg = ( "Cannot delete some instances of model 'P' because they are " "referenced through restricted foreign keys: 'A.restrict'." ) with self.assertRaisesMessage(RestrictedError, msg) as cm: a.restrict.p.delete() self.assertEqual(cm.exception.restricted_objects, {a}) # Object referenced also with CASCADE relationship can be deleted. a.cascade.p = a.restrict.p a.cascade.save() a.restrict.p.delete() self.assertFalse(A.objects.filter(name="restrict").exists()) self.assertFalse(R.objects.filter(pk=a.restrict_id).exists()) def test_restrict_path_cascade_direct(self): a = create_a("restrict") a.restrict.p = P.objects.create() a.restrict.save() a.cascade_p = a.restrict.p a.save() a.restrict.p.delete() self.assertFalse(A.objects.filter(name="restrict").exists()) self.assertFalse(R.objects.filter(pk=a.restrict_id).exists()) def test_restrict_path_cascade_indirect_diamond(self): delete_top = DeleteTop.objects.create() b1 = B1.objects.create(delete_top=delete_top) b2 = B2.objects.create(delete_top=delete_top) delete_bottom = DeleteBottom.objects.create(b1=b1, b2=b2) msg = ( "Cannot delete some instances of model 'B1' because they are " "referenced through restricted foreign keys: 'DeleteBottom.b1'." ) with self.assertRaisesMessage(RestrictedError, msg) as cm: b1.delete() self.assertEqual(cm.exception.restricted_objects, {delete_bottom}) self.assertTrue(DeleteTop.objects.exists()) self.assertTrue(B1.objects.exists()) self.assertTrue(B2.objects.exists()) self.assertTrue(DeleteBottom.objects.exists()) # Object referenced also with CASCADE relationship can be deleted. delete_top.delete() self.assertFalse(DeleteTop.objects.exists()) self.assertFalse(B1.objects.exists()) self.assertFalse(B2.objects.exists()) self.assertFalse(DeleteBottom.objects.exists()) def test_restrict_gfk_no_fast_delete(self): delete_top = DeleteTop.objects.create() generic_b1 = GenericB1.objects.create(generic_delete_top=delete_top) generic_b2 = GenericB2.objects.create(generic_delete_top=delete_top) generic_delete_bottom = GenericDeleteBottom.objects.create( generic_b1=generic_b1, generic_b2=generic_b2, ) msg = ( "Cannot delete some instances of model 'GenericB1' because they " "are referenced through restricted foreign keys: " "'GenericDeleteBottom.generic_b1'." ) with self.assertRaisesMessage(RestrictedError, msg) as cm: generic_b1.delete() self.assertEqual(cm.exception.restricted_objects, {generic_delete_bottom}) self.assertTrue(DeleteTop.objects.exists()) self.assertTrue(GenericB1.objects.exists()) self.assertTrue(GenericB2.objects.exists()) self.assertTrue(GenericDeleteBottom.objects.exists()) # Object referenced also with CASCADE relationship can be deleted. delete_top.delete() self.assertFalse(DeleteTop.objects.exists()) self.assertFalse(GenericB1.objects.exists()) self.assertFalse(GenericB2.objects.exists()) self.assertFalse(GenericDeleteBottom.objects.exists()) class DeletionTests(TestCase): def test_sliced_queryset(self): msg = "Cannot use 'limit' or 'offset' with delete()." with self.assertRaisesMessage(TypeError, msg): M.objects.all()[0:5].delete() def test_pk_none(self): m = M() msg = "M object can't be deleted because its id attribute is set to None." with self.assertRaisesMessage(ValueError, msg): m.delete() def test_m2m(self): m = M.objects.create() r = R.objects.create() MR.objects.create(m=m, r=r) r.delete() self.assertFalse(MR.objects.exists()) r = R.objects.create() MR.objects.create(m=m, r=r) m.delete() self.assertFalse(MR.objects.exists()) m = M.objects.create() r = R.objects.create() m.m2m.add(r) r.delete() through = M._meta.get_field("m2m").remote_field.through self.assertFalse(through.objects.exists()) r = R.objects.create() m.m2m.add(r) m.delete() self.assertFalse(through.objects.exists()) m = M.objects.create() r = R.objects.create() MRNull.objects.create(m=m, r=r) r.delete() self.assertFalse(not MRNull.objects.exists()) self.assertFalse(m.m2m_through_null.exists()) def test_bulk(self): s = S.objects.create(r=R.objects.create()) for i in range(2 * GET_ITERATOR_CHUNK_SIZE): T.objects.create(s=s) # 1 (select related `T` instances) # + 1 (select related `U` instances) # + 2 (delete `T` instances in batches) # + 1 (delete `s`) self.assertNumQueries(5, s.delete) self.assertFalse(S.objects.exists()) @skipUnlessDBFeature("supports_on_delete_db_cascade") def test_db_cascade(self): related_db_op = RelatedDbOptionParent.objects.create( p=RelatedDbOptionGrandParent.objects.create() ) CascadeDbModel.objects.bulk_create( [ CascadeDbModel(db_cascade=related_db_op) for _ in range(2 * GET_ITERATOR_CHUNK_SIZE) ] ) with self.assertNumQueries(1): results = related_db_op.delete() self.assertEqual(results, (1, {"delete.RelatedDbOptionParent": 1})) self.assertFalse(CascadeDbModel.objects.exists()) self.assertFalse(RelatedDbOptionParent.objects.exists()) def test_instance_update(self): deleted = [] related_setnull_sets = [] def pre_delete(sender, **kwargs): obj = kwargs["instance"] deleted.append(obj) if isinstance(obj, R): related_setnull_sets.append([a.pk for a in obj.setnull_set.all()]) models.signals.pre_delete.connect(pre_delete) a = create_a("update_setnull") a.setnull.delete() a = create_a("update_cascade") a.cascade.delete() for obj in deleted: self.assertIsNone(obj.pk) for pk_list in related_setnull_sets: for a in A.objects.filter(id__in=pk_list): self.assertIsNone(a.setnull) models.signals.pre_delete.disconnect(pre_delete) def test_deletion_order(self): pre_delete_order = [] post_delete_order = [] def log_post_delete(sender, **kwargs): pre_delete_order.append((sender, kwargs["instance"].pk)) def log_pre_delete(sender, **kwargs): post_delete_order.append((sender, kwargs["instance"].pk)) models.signals.post_delete.connect(log_post_delete) models.signals.pre_delete.connect(log_pre_delete) r = R.objects.create() s1 = S.objects.create(r=r) s2 = S.objects.create(r=r) t1 = T.objects.create(s=s1) t2 = T.objects.create(s=s2) rchild = RChild.objects.create(r_ptr=r) r_pk = r.pk r.delete() self.assertEqual( pre_delete_order, [ (T, t2.pk), (T, t1.pk), (RChild, rchild.pk), (S, s2.pk), (S, s1.pk), (R, r_pk), ], ) self.assertEqual( post_delete_order, [ (T, t1.pk), (T, t2.pk), (RChild, rchild.pk), (S, s1.pk), (S, s2.pk), (R, r_pk), ], ) models.signals.post_delete.disconnect(log_post_delete) models.signals.pre_delete.disconnect(log_pre_delete) def test_relational_post_delete_signals_happen_before_parent_object(self): deletions = [] def log_post_delete(instance, **kwargs): self.assertTrue(R.objects.filter(pk=instance.r_id)) self.assertIs(type(instance), S) deletions.append(instance.id) r = R.objects.create() s = S.objects.create(r=r) s_id = s.pk models.signals.post_delete.connect(log_post_delete, sender=S) try: r.delete() finally: models.signals.post_delete.disconnect(log_post_delete) self.assertEqual(len(deletions), 1) self.assertEqual(deletions[0], s_id) @skipUnlessDBFeature("can_defer_constraint_checks") def test_can_defer_constraint_checks(self): u = User.objects.create(avatar=Avatar.objects.create()) a = Avatar.objects.get(pk=u.avatar_id) # 1 query to find the users for the avatar. # 1 query to delete the user # 1 query to delete the avatar # The important thing is that when we can defer constraint checks there # is no need to do an UPDATE on User.avatar to null it out. # Attach a signal to make sure we will not do fast_deletes. calls = [] def noop(*args, **kwargs): calls.append("") models.signals.post_delete.connect(noop, sender=User) self.assertNumQueries(3, a.delete) self.assertFalse(User.objects.exists()) self.assertFalse(Avatar.objects.exists()) self.assertEqual(len(calls), 1) models.signals.post_delete.disconnect(noop, sender=User) @skipIfDBFeature("can_defer_constraint_checks") def test_cannot_defer_constraint_checks(self): u = User.objects.create(avatar=Avatar.objects.create()) # Attach a signal to make sure we will not do fast_deletes. calls = [] def noop(*args, **kwargs): calls.append("") models.signals.post_delete.connect(noop, sender=User) a = Avatar.objects.get(pk=u.avatar_id) # The below doesn't make sense... Why do we need to null out # user.avatar if we are going to delete the user immediately after it, # and there are no more cascades. # 1 query to find the users for the avatar. # 1 query to delete the user # 1 query to null out user.avatar, since we can't defer the constraint # 1 query to delete the avatar self.assertNumQueries(4, a.delete) self.assertFalse(User.objects.exists()) self.assertFalse(Avatar.objects.exists()) self.assertEqual(len(calls), 1) models.signals.post_delete.disconnect(noop, sender=User) def test_hidden_related(self): r = R.objects.create() h = HiddenUser.objects.create(r=r) HiddenUserProfile.objects.create(user=h) r.delete() self.assertEqual(HiddenUserProfile.objects.count(), 0) def test_large_delete(self): TEST_SIZE = 2000 objs = [Avatar() for i in range(0, TEST_SIZE)] Avatar.objects.bulk_create(objs) # Calculate the number of queries needed. batch_size = connection.ops.bulk_batch_size(["pk"], objs) # The related fetches are done in batches. batches = ceil(len(objs) / batch_size) # One query for Avatar.objects.all() and then one related fast delete # for each batch. fetches_to_mem = 1 + batches # The Avatar objects are going to be deleted in batches of # GET_ITERATOR_CHUNK_SIZE. queries = fetches_to_mem + TEST_SIZE // GET_ITERATOR_CHUNK_SIZE self.assertNumQueries(queries, Avatar.objects.all().delete) self.assertFalse(Avatar.objects.exists()) def test_large_delete_related(self): TEST_SIZE = 2000 s = S.objects.create(r=R.objects.create()) for i in range(TEST_SIZE): T.objects.create(s=s) batch_size = max(connection.ops.bulk_batch_size(["pk"], range(TEST_SIZE)), 1) # TEST_SIZE / batch_size (select related `T` instances) # + 1 (select related `U` instances) # + TEST_SIZE / GET_ITERATOR_CHUNK_SIZE (delete `T` matches in batches) # + 1 (delete `s`) expected_num_queries = ceil(TEST_SIZE / batch_size) expected_num_queries += ceil(TEST_SIZE / GET_ITERATOR_CHUNK_SIZE) + 2 self.assertNumQueries(expected_num_queries, s.delete) self.assertFalse(S.objects.exists()) self.assertFalse(T.objects.exists()) def test_delete_with_keeping_parents(self): child = RChild.objects.create() parent_id = child.r_ptr_id child.delete(keep_parents=True) self.assertFalse(RChild.objects.filter(id=child.id).exists()) self.assertTrue(R.objects.filter(id=parent_id).exists()) def test_delete_with_keeping_parents_relationships(self): child = RChild.objects.create() parent_id = child.r_ptr_id parent_referent_id = S.objects.create(r=child.r_ptr).pk child.delete(keep_parents=True) self.assertFalse(RChild.objects.filter(id=child.id).exists()) self.assertTrue(R.objects.filter(id=parent_id).exists()) self.assertTrue(S.objects.filter(pk=parent_referent_id).exists()) childchild = RChildChild.objects.create() parent_id = childchild.rchild_ptr.r_ptr_id child_id = childchild.rchild_ptr_id parent_referent_id = S.objects.create(r=childchild.rchild_ptr.r_ptr).pk childchild.delete(keep_parents=True) self.assertFalse(RChildChild.objects.filter(id=childchild.id).exists()) self.assertTrue(RChild.objects.filter(id=child_id).exists()) self.assertTrue(R.objects.filter(id=parent_id).exists()) self.assertTrue(S.objects.filter(pk=parent_referent_id).exists()) def test_queryset_delete_returns_num_rows(self): """ QuerySet.delete() should return the number of deleted rows and a dictionary with the number of deletions for each object type. """ Avatar.objects.bulk_create( [Avatar(desc="a"), Avatar(desc="b"), Avatar(desc="c")] ) avatars_count = Avatar.objects.count() deleted, rows_count = Avatar.objects.all().delete() self.assertEqual(deleted, avatars_count) # more complex example with multiple object types r = R.objects.create() h1 = HiddenUser.objects.create(r=r) HiddenUser.objects.create(r=r) HiddenUserProfile.objects.create(user=h1) existed_objs = { R._meta.label: R.objects.count(), HiddenUser._meta.label: HiddenUser.objects.count(), HiddenUserProfile._meta.label: HiddenUserProfile.objects.count(), } deleted, deleted_objs = R.objects.all().delete() self.assertCountEqual(deleted_objs.keys(), existed_objs.keys()) for k, v in existed_objs.items(): self.assertEqual(deleted_objs[k], v) def test_model_delete_returns_num_rows(self): """ Model.delete() should return the number of deleted rows and a dictionary with the number of deletions for each object type. """ r = R.objects.create() h1 = HiddenUser.objects.create(r=r) h2 = HiddenUser.objects.create(r=r) HiddenUser.objects.create(r=r) HiddenUserProfile.objects.create(user=h1) HiddenUserProfile.objects.create(user=h2) m1 = M.objects.create() m2 = M.objects.create() MR.objects.create(r=r, m=m1) r.m_set.add(m1) r.m_set.add(m2) r.save() existed_objs = { R._meta.label: R.objects.count(), HiddenUser._meta.label: HiddenUser.objects.count(), MR._meta.label: MR.objects.count(), HiddenUserProfile._meta.label: HiddenUserProfile.objects.count(), M.m2m.through._meta.label: M.m2m.through.objects.count(), } deleted, deleted_objs = r.delete() self.assertEqual(deleted, sum(existed_objs.values())) self.assertCountEqual(deleted_objs.keys(), existed_objs.keys()) for k, v in existed_objs.items(): self.assertEqual(deleted_objs[k], v) def test_proxied_model_duplicate_queries(self): """ #25685 - Deleting instances of a model with existing proxy classes should not issue multiple queries during cascade deletion of referring models. """ avatar = Avatar.objects.create() # One query for the Avatar table and a second for the User one. with self.assertNumQueries(2): avatar.delete() def test_only_referenced_fields_selected(self): """ Only referenced fields are selected during cascade deletion SELECT unless deletion signals are connected. """ origin = Origin.objects.create() expected_sql = str( Referrer.objects.only( # Both fields are referenced by SecondReferrer. "id", "unique_field", ) .filter(origin__in=[origin]) .query ) with self.assertNumQueries(2) as ctx: origin.delete() self.assertEqual(ctx.captured_queries[0]["sql"], expected_sql) def receiver(instance, **kwargs): pass # All fields are selected if deletion signals are connected. for signal_name in ("pre_delete", "post_delete"): with self.subTest(signal=signal_name): origin = Origin.objects.create() signal = getattr(models.signals, signal_name) signal.connect(receiver, sender=Referrer) with self.assertNumQueries(2) as ctx: origin.delete() self.assertIn( connection.ops.quote_name("large_field"), ctx.captured_queries[0]["sql"], ) signal.disconnect(receiver, sender=Referrer) def test_keep_parents_does_not_delete_proxy_related(self): r_child = RChild.objects.create() r_proxy = RProxy.objects.get(pk=r_child.pk) Origin.objects.create(r_proxy=r_proxy) self.assertEqual(Origin.objects.count(), 1) r_child.delete(keep_parents=True) self.assertEqual(Origin.objects.count(), 1) class FastDeleteTests(TestCase): def test_fast_delete_all(self): with self.assertNumQueries(1) as ctx: User.objects.all().delete() sql = ctx.captured_queries[0]["sql"] # No subqueries is used when performing a full delete. self.assertNotIn("SELECT", sql) def test_fast_delete_fk(self): u = User.objects.create(avatar=Avatar.objects.create()) a = Avatar.objects.get(pk=u.avatar_id) # 1 query to fast-delete the user # 1 query to delete the avatar self.assertNumQueries(2, a.delete) self.assertFalse(User.objects.exists()) self.assertFalse(Avatar.objects.exists()) def test_fast_delete_m2m(self): t = M2MTo.objects.create() f = M2MFrom.objects.create() f.m2m.add(t) # 1 to delete f, 1 to fast-delete m2m for f self.assertNumQueries(2, f.delete) def test_fast_delete_revm2m(self): t = M2MTo.objects.create() f = M2MFrom.objects.create() f.m2m.add(t) # 1 to delete t, 1 to fast-delete t's m_set self.assertNumQueries(2, f.delete) def test_fast_delete_qs(self): u1 = User.objects.create() u2 = User.objects.create() self.assertNumQueries(1, User.objects.filter(pk=u1.pk).delete) self.assertEqual(User.objects.count(), 1) self.assertTrue(User.objects.filter(pk=u2.pk).exists()) def test_fast_delete_instance_set_pk_none(self): u = User.objects.create() # User can be fast-deleted. collector = Collector(using="default") self.assertTrue(collector.can_fast_delete(u)) u.delete() self.assertIsNone(u.pk) def test_fast_delete_joined_qs(self): a = Avatar.objects.create(desc="a") User.objects.create(avatar=a) u2 = User.objects.create() self.assertNumQueries(1, User.objects.filter(avatar__desc="a").delete) self.assertEqual(User.objects.count(), 1) self.assertTrue(User.objects.filter(pk=u2.pk).exists()) def test_fast_delete_inheritance(self): c = Child.objects.create() p = Parent.objects.create() # 1 for self, 1 for parent self.assertNumQueries(2, c.delete) self.assertFalse(Child.objects.exists()) self.assertEqual(Parent.objects.count(), 1) self.assertEqual(Parent.objects.filter(pk=p.pk).count(), 1) # 1 for self delete, 1 for fast delete of empty "child" qs. self.assertNumQueries(2, p.delete) self.assertFalse(Parent.objects.exists()) # 1 for self delete, 1 for fast delete of empty "child" qs. c = Child.objects.create() p = c.parent_ptr self.assertNumQueries(2, p.delete) self.assertFalse(Parent.objects.exists()) self.assertFalse(Child.objects.exists()) def test_fast_delete_large_batch(self): User.objects.bulk_create(User() for i in range(0, 2000)) # No problems here - we aren't going to cascade, so we will fast # delete the objects in a single query. self.assertNumQueries(1, User.objects.all().delete) a = Avatar.objects.create(desc="a") User.objects.bulk_create(User(avatar=a) for i in range(0, 2000)) # We don't hit parameter amount limits for a, so just one query for # that + fast delete of the related objs. self.assertNumQueries(2, a.delete) self.assertEqual(User.objects.count(), 0) def test_fast_delete_empty_no_update_can_self_select(self): """ Fast deleting when DatabaseFeatures.update_can_self_select = False works even if the specified filter doesn't match any row (#25932). """ with self.assertNumQueries(1): self.assertEqual( User.objects.filter(avatar__desc="missing").delete(), (0, {}), ) def test_fast_delete_combined_relationships(self): # The cascading fast-delete of SecondReferrer should be combined # in a single DELETE WHERE referrer_id OR unique_field. origin = Origin.objects.create() referer = Referrer.objects.create(origin=origin, unique_field=42) with self.assertNumQueries(2): referer.delete() def test_fast_delete_aggregation(self): # Fast-deleting when filtering against an aggregation result in # a single query containing a subquery. Base.objects.create() with self.assertNumQueries(1): self.assertEqual( Base.objects.annotate( rels_count=models.Count("rels"), ) .filter(rels_count=0) .delete(), (1, {"delete.Base": 1}), ) self.assertIs(Base.objects.exists(), False) def test_fast_delete_empty_result_set(self): user = User.objects.create() with self.assertNumQueries(0): self.assertEqual( User.objects.filter(pk__in=[]).delete(), (0, {}), )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/test_model_checks.py
tests/check_framework/test_model_checks.py
from django.core import checks from django.core.checks import Error, Warning from django.db import models from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import ( isolate_apps, modify_settings, override_settings, override_system_checks, ) class EmptyRouter: pass @isolate_apps("check_framework", attr_name="apps") @override_system_checks([checks.model_checks.check_all_models]) class DuplicateDBTableTests(SimpleTestCase): def test_collision_in_same_app(self): class Model1(models.Model): class Meta: db_table = "test_table" class Model2(models.Model): class Meta: db_table = "test_table" self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "db_table 'test_table' is used by multiple models: " "check_framework.Model1, check_framework.Model2.", obj="test_table", id="models.E028", ) ], ) @override_settings( DATABASE_ROUTERS=["check_framework.test_model_checks.EmptyRouter"] ) def test_collision_in_same_app_database_routers_installed(self): class Model1(models.Model): class Meta: db_table = "test_table" class Model2(models.Model): class Meta: db_table = "test_table" self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Warning( "db_table 'test_table' is used by multiple models: " "check_framework.Model1, check_framework.Model2.", hint=( "You have configured settings.DATABASE_ROUTERS. Verify " "that check_framework.Model1, check_framework.Model2 are " "correctly routed to separate databases." ), obj="test_table", id="models.W035", ) ], ) @modify_settings(INSTALLED_APPS={"append": "basic"}) @isolate_apps("basic", "check_framework", kwarg_name="apps") def test_collision_across_apps(self, apps): class Model1(models.Model): class Meta: app_label = "basic" db_table = "test_table" class Model2(models.Model): class Meta: app_label = "check_framework" db_table = "test_table" self.assertEqual( checks.run_checks(app_configs=apps.get_app_configs()), [ Error( "db_table 'test_table' is used by multiple models: " "basic.Model1, check_framework.Model2.", obj="test_table", id="models.E028", ) ], ) @modify_settings(INSTALLED_APPS={"append": "basic"}) @override_settings( DATABASE_ROUTERS=["check_framework.test_model_checks.EmptyRouter"] ) @isolate_apps("basic", "check_framework", kwarg_name="apps") def test_collision_across_apps_database_routers_installed(self, apps): class Model1(models.Model): class Meta: app_label = "basic" db_table = "test_table" class Model2(models.Model): class Meta: app_label = "check_framework" db_table = "test_table" self.assertEqual( checks.run_checks(app_configs=apps.get_app_configs()), [ Warning( "db_table 'test_table' is used by multiple models: " "basic.Model1, check_framework.Model2.", hint=( "You have configured settings.DATABASE_ROUTERS. Verify " "that basic.Model1, check_framework.Model2 are correctly " "routed to separate databases." ), obj="test_table", id="models.W035", ) ], ) def test_no_collision_for_unmanaged_models(self): class Unmanaged(models.Model): class Meta: db_table = "test_table" managed = False class Managed(models.Model): class Meta: db_table = "test_table" self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) def test_no_collision_for_proxy_models(self): class Model(models.Model): class Meta: db_table = "test_table" class ProxyModel(Model): class Meta: proxy = True self.assertEqual(Model._meta.db_table, ProxyModel._meta.db_table) self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) @isolate_apps("check_framework", attr_name="apps") @override_system_checks([checks.model_checks.check_all_models]) class IndexNameTests(SimpleTestCase): def test_collision_in_same_model(self): index = models.Index(fields=["id"], name="foo") class Model(models.Model): class Meta: indexes = [index, index] self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "index name 'foo' is not unique for model check_framework.Model.", id="models.E029", ), ], ) def test_collision_in_different_models(self): index = models.Index(fields=["id"], name="foo") class Model1(models.Model): class Meta: indexes = [index] class Model2(models.Model): class Meta: indexes = [index] self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "index name 'foo' is not unique among models: " "check_framework.Model1, check_framework.Model2.", id="models.E030", ), ], ) def test_collision_abstract_model(self): class AbstractModel(models.Model): class Meta: indexes = [models.Index(fields=["id"], name="foo")] abstract = True class Model1(AbstractModel): pass class Model2(AbstractModel): pass self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "index name 'foo' is not unique among models: " "check_framework.Model1, check_framework.Model2.", id="models.E030", ), ], ) def test_no_collision_abstract_model_interpolation(self): class AbstractModel(models.Model): name = models.CharField(max_length=20) class Meta: indexes = [ models.Index(fields=["name"], name="%(app_label)s_%(class)s_foo") ] abstract = True class Model1(AbstractModel): pass class Model2(AbstractModel): pass self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) @modify_settings(INSTALLED_APPS={"append": "basic"}) @isolate_apps("basic", "check_framework", kwarg_name="apps") def test_collision_across_apps(self, apps): index = models.Index(fields=["id"], name="foo") class Model1(models.Model): class Meta: app_label = "basic" indexes = [index] class Model2(models.Model): class Meta: app_label = "check_framework" indexes = [index] self.assertEqual( checks.run_checks(app_configs=apps.get_app_configs()), [ Error( "index name 'foo' is not unique among models: basic.Model1, " "check_framework.Model2.", id="models.E030", ), ], ) @modify_settings(INSTALLED_APPS={"append": "basic"}) @isolate_apps("basic", "check_framework", kwarg_name="apps") def test_no_collision_across_apps_interpolation(self, apps): index = models.Index(fields=["id"], name="%(app_label)s_%(class)s_foo") class Model1(models.Model): class Meta: app_label = "basic" constraints = [index] class Model2(models.Model): class Meta: app_label = "check_framework" constraints = [index] self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), []) @isolate_apps("check_framework", attr_name="apps") @override_system_checks([checks.model_checks.check_all_models]) @skipUnlessDBFeature("supports_table_check_constraints") class ConstraintNameTests(TestCase): def test_collision_in_same_model(self): class Model(models.Model): class Meta: constraints = [ models.CheckConstraint(condition=models.Q(id__gt=0), name="foo"), models.CheckConstraint(condition=models.Q(id__lt=100), name="foo"), ] self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "constraint name 'foo' is not unique for model " "check_framework.Model.", id="models.E031", ), ], ) def test_collision_in_different_models(self): constraint = models.CheckConstraint(condition=models.Q(id__gt=0), name="foo") class Model1(models.Model): class Meta: constraints = [constraint] class Model2(models.Model): class Meta: constraints = [constraint] self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "constraint name 'foo' is not unique among models: " "check_framework.Model1, check_framework.Model2.", id="models.E032", ), ], ) def test_collision_abstract_model(self): class AbstractModel(models.Model): class Meta: constraints = [ models.CheckConstraint(condition=models.Q(id__gt=0), name="foo") ] abstract = True class Model1(AbstractModel): pass class Model2(AbstractModel): pass self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "constraint name 'foo' is not unique among models: " "check_framework.Model1, check_framework.Model2.", id="models.E032", ), ], ) def test_no_collision_abstract_model_interpolation(self): class AbstractModel(models.Model): class Meta: constraints = [ models.CheckConstraint( condition=models.Q(id__gt=0), name="%(app_label)s_%(class)s_foo" ), ] abstract = True class Model1(AbstractModel): pass class Model2(AbstractModel): pass self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) @modify_settings(INSTALLED_APPS={"append": "basic"}) @isolate_apps("basic", "check_framework", kwarg_name="apps") def test_collision_across_apps(self, apps): constraint = models.CheckConstraint(condition=models.Q(id__gt=0), name="foo") class Model1(models.Model): class Meta: app_label = "basic" constraints = [constraint] class Model2(models.Model): class Meta: app_label = "check_framework" constraints = [constraint] self.assertEqual( checks.run_checks(app_configs=apps.get_app_configs()), [ Error( "constraint name 'foo' is not unique among models: " "basic.Model1, check_framework.Model2.", id="models.E032", ), ], ) @modify_settings(INSTALLED_APPS={"append": "basic"}) @isolate_apps("basic", "check_framework", kwarg_name="apps") def test_no_collision_across_apps_interpolation(self, apps): constraint = models.CheckConstraint( condition=models.Q(id__gt=0), name="%(app_label)s_%(class)s_foo" ) class Model1(models.Model): class Meta: app_label = "basic" constraints = [constraint] class Model2(models.Model): class Meta: app_label = "check_framework" constraints = [constraint] self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), [])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/test_async_checks.py
tests/check_framework/test_async_checks.py
import os from unittest import mock from django.core.checks.async_checks import E001, check_async_unsafe from django.test import SimpleTestCase class AsyncCheckTests(SimpleTestCase): @mock.patch.dict(os.environ, {"DJANGO_ALLOW_ASYNC_UNSAFE": ""}) def test_no_allowed_async_unsafe(self): self.assertEqual(check_async_unsafe(None), []) @mock.patch.dict(os.environ, {"DJANGO_ALLOW_ASYNC_UNSAFE": "true"}) def test_allowed_async_unsafe_set(self): self.assertEqual(check_async_unsafe(None), [E001])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/test_files.py
tests/check_framework/test_files.py
from pathlib import Path from django.core.checks import Error from django.core.checks.files import check_setting_file_upload_temp_dir from django.test import SimpleTestCase class FilesCheckTests(SimpleTestCase): def test_file_upload_temp_dir(self): tests = [ None, "", Path.cwd(), str(Path.cwd()), ] for setting in tests: with self.subTest(setting), self.settings(FILE_UPLOAD_TEMP_DIR=setting): self.assertEqual(check_setting_file_upload_temp_dir(None), []) def test_file_upload_temp_dir_nonexistent(self): for setting in ["nonexistent", Path("nonexistent")]: with self.subTest(setting), self.settings(FILE_UPLOAD_TEMP_DIR=setting): self.assertEqual( check_setting_file_upload_temp_dir(None), [ Error( "The FILE_UPLOAD_TEMP_DIR setting refers to the " "nonexistent directory 'nonexistent'.", id="files.E001", ), ], )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/test_model_field_deprecation.py
tests/check_framework/test_model_field_deprecation.py
from django.core import checks from django.db import models from django.test import SimpleTestCase from django.test.utils import isolate_apps @isolate_apps("check_framework") class TestDeprecatedField(SimpleTestCase): def test_default_details(self): class MyField(models.Field): system_check_deprecated_details = {} class Model(models.Model): name = MyField() model = Model() self.assertEqual( model.check(), [ checks.Warning( msg="MyField has been deprecated.", obj=Model._meta.get_field("name"), id="fields.WXXX", ) ], ) def test_user_specified_details(self): class MyField(models.Field): system_check_deprecated_details = { "msg": "This field is deprecated and will be removed soon.", "hint": "Use something else.", "id": "fields.W999", } class Model(models.Model): name = MyField() model = Model() self.assertEqual( model.check(), [ checks.Warning( msg="This field is deprecated and will be removed soon.", hint="Use something else.", obj=Model._meta.get_field("name"), id="fields.W999", ) ], ) @isolate_apps("check_framework") class TestRemovedField(SimpleTestCase): def test_default_details(self): class MyField(models.Field): system_check_removed_details = {} class Model(models.Model): name = MyField() model = Model() self.assertEqual( model.check(), [ checks.Error( msg=( "MyField has been removed except for support in historical " "migrations." ), obj=Model._meta.get_field("name"), id="fields.EXXX", ) ], ) def test_user_specified_details(self): class MyField(models.Field): system_check_removed_details = { "msg": "Support for this field is gone.", "hint": "Use something else.", "id": "fields.E999", } class Model(models.Model): name = MyField() model = Model() self.assertEqual( model.check(), [ checks.Error( msg="Support for this field is gone.", hint="Use something else.", obj=Model._meta.get_field("name"), id="fields.E999", ) ], )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/models.py
tests/check_framework/models.py
from django.core.checks import register from django.db import models class SimpleModel(models.Model): field = models.IntegerField() manager = models.manager.Manager() @register("tests") def my_check(app_configs, **kwargs): my_check.did_run = True return [] my_check.did_run = False
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/test_multi_db.py
tests/check_framework/test_multi_db.py
from unittest import mock from django.db import connections, models from django.test import SimpleTestCase from django.test.utils import isolate_apps, override_settings class TestRouter: """ Routes to the 'other' database if the model name starts with 'Other'. """ def allow_migrate(self, db, app_label, model_name=None, **hints): return db == ("other" if model_name.startswith("other") else "default") @override_settings(DATABASE_ROUTERS=[TestRouter()]) @isolate_apps("check_framework") class TestMultiDBChecks(SimpleTestCase): def _patch_check_field_on(self, db): return mock.patch.object(connections[db].validation, "check_field") def test_checks_called_on_the_default_database(self): class Model(models.Model): field = models.CharField(max_length=100) model = Model() with self._patch_check_field_on("default") as mock_check_field_default: with self._patch_check_field_on("other") as mock_check_field_other: model.check(databases={"default", "other"}) self.assertTrue(mock_check_field_default.called) self.assertFalse(mock_check_field_other.called) def test_checks_called_on_the_other_database(self): class OtherModel(models.Model): field = models.CharField(max_length=100) model = OtherModel() with self._patch_check_field_on("other") as mock_check_field_other: with self._patch_check_field_on("default") as mock_check_field_default: model.check(databases={"default", "other"}) self.assertTrue(mock_check_field_other.called) self.assertFalse(mock_check_field_default.called)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/test_translation.py
tests/check_framework/test_translation.py
from django.core.checks import Error from django.core.checks.translation import ( check_language_settings_consistent, check_setting_language_code, check_setting_languages, check_setting_languages_bidi, ) from django.test import SimpleTestCase, override_settings class TranslationCheckTests(SimpleTestCase): def setUp(self): self.valid_tags = ( "en", # language "mas", # language "sgn-ase", # language+extlang "fr-CA", # language+region "es-419", # language+region "zh-Hans", # language+script "ca-ES-valencia", # language+region+variant # FIXME: The following should be invalid: "sr@latin", # language+script ) self.invalid_tags = ( None, # invalid type: None. 123, # invalid type: int. b"en", # invalid type: bytes. "eü", # non-latin characters. "en_US", # locale format. "en--us", # empty subtag. "-en", # leading separator. "en-", # trailing separator. "en-US.UTF-8", # language tag w/ locale encoding. "en_US.UTF-8", # locale format - language w/ region and encoding. "ca_ES@valencia", # locale format - language w/ region and variant. # FIXME: The following should be invalid: # 'sr@latin', # locale instead of language tag. ) def test_valid_language_code(self): for tag in self.valid_tags: with self.subTest(tag), self.settings(LANGUAGE_CODE=tag): self.assertEqual(check_setting_language_code(None), []) def test_invalid_language_code(self): msg = "You have provided an invalid value for the LANGUAGE_CODE setting: %r." for tag in self.invalid_tags: with self.subTest(tag), self.settings(LANGUAGE_CODE=tag): self.assertEqual( check_setting_language_code(None), [ Error(msg % tag, id="translation.E001"), ], ) def test_valid_languages(self): for tag in self.valid_tags: with self.subTest(tag), self.settings(LANGUAGES=[(tag, tag)]): self.assertEqual(check_setting_languages(None), []) def test_invalid_languages(self): msg = "You have provided an invalid language code in the LANGUAGES setting: %r." for tag in self.invalid_tags: with self.subTest(tag), self.settings(LANGUAGES=[(tag, tag)]): self.assertEqual( check_setting_languages(None), [ Error(msg % tag, id="translation.E002"), ], ) def test_valid_languages_bidi(self): for tag in self.valid_tags: with self.subTest(tag), self.settings(LANGUAGES_BIDI=[tag]): self.assertEqual(check_setting_languages_bidi(None), []) def test_invalid_languages_bidi(self): msg = ( "You have provided an invalid language code in the LANGUAGES_BIDI setting: " "%r." ) for tag in self.invalid_tags: with self.subTest(tag), self.settings(LANGUAGES_BIDI=[tag]): self.assertEqual( check_setting_languages_bidi(None), [ Error(msg % tag, id="translation.E003"), ], ) @override_settings(USE_I18N=True, LANGUAGES=[("en", "English")]) def test_inconsistent_language_settings(self): msg = ( "You have provided a value for the LANGUAGE_CODE setting that is " "not in the LANGUAGES setting." ) for tag in ["fr", "fr-CA", "fr-357"]: with self.subTest(tag), self.settings(LANGUAGE_CODE=tag): self.assertEqual( check_language_settings_consistent(None), [ Error(msg, id="translation.E004"), ], ) @override_settings( USE_I18N=True, LANGUAGES=[ ("de", "German"), ("es", "Spanish"), ("fr", "French"), ("ca", "Catalan"), ], ) def test_valid_variant_consistent_language_settings(self): tests = [ # language + region. "fr-CA", "es-419", "de-at", # language + region + variant. "ca-ES-valencia", ] for tag in tests: with self.subTest(tag), self.settings(LANGUAGE_CODE=tag): self.assertEqual(check_language_settings_consistent(None), [])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/test_database.py
tests/check_framework/test_database.py
import unittest from unittest import mock from django.core.checks.database import check_database_backends from django.db import connection, connections from django.test import TestCase class DatabaseCheckTests(TestCase): databases = {"default", "other"} @mock.patch("django.db.backends.base.validation.BaseDatabaseValidation.check") def test_database_checks_called(self, mocked_check): check_database_backends() self.assertFalse(mocked_check.called) check_database_backends(databases=self.databases) self.assertTrue(mocked_check.called) @unittest.skipUnless(connection.vendor == "mysql", "Test only for MySQL") def test_mysql_strict_mode(self): def _clean_sql_mode(): for alias in self.databases: if hasattr(connections[alias], "sql_mode"): del connections[alias].sql_mode _clean_sql_mode() good_sql_modes = [ "STRICT_TRANS_TABLES,STRICT_ALL_TABLES", "STRICT_TRANS_TABLES", "STRICT_ALL_TABLES", ] for sql_mode in good_sql_modes: with mock.patch.object( connection, "mysql_server_data", {"sql_mode": sql_mode}, ): self.assertEqual(check_database_backends(databases=self.databases), []) _clean_sql_mode() bad_sql_modes = ["", "WHATEVER"] for sql_mode in bad_sql_modes: mocker_default = mock.patch.object( connection, "mysql_server_data", {"sql_mode": sql_mode}, ) mocker_other = mock.patch.object( connections["other"], "mysql_server_data", {"sql_mode": sql_mode}, ) with mocker_default, mocker_other: # One warning for each database alias result = check_database_backends(databases=self.databases) self.assertEqual(len(result), 2) self.assertEqual([r.id for r in result], ["mysql.W002", "mysql.W002"]) _clean_sql_mode()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/test_urls.py
tests/check_framework/test_urls.py
from django.conf import settings from django.core.checks.messages import Error, Warning from django.core.checks.urls import ( E006, check_custom_error_handlers, check_url_config, check_url_namespaces_unique, check_url_settings, get_warning_for_invalid_pattern, ) from django.test import SimpleTestCase from django.test.utils import override_settings class CheckUrlConfigTests(SimpleTestCase): @override_settings(ROOT_URLCONF="check_framework.urls.no_warnings") def test_no_warnings(self): result = check_url_config(None) self.assertEqual(result, []) @override_settings(ROOT_URLCONF="check_framework.urls.no_warnings_i18n") def test_no_warnings_i18n(self): self.assertEqual(check_url_config(None), []) @override_settings(ROOT_URLCONF="check_framework.urls.warning_in_include") def test_check_resolver_recursive(self): # The resolver is checked recursively (examining URL patterns in # include()). result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "urls.W001") @override_settings(ROOT_URLCONF="check_framework.urls.include_with_dollar") def test_include_with_dollar(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "urls.W001") self.assertEqual( warning.msg, ( "Your URL pattern '^include-with-dollar$' uses include with a " "route ending with a '$'. Remove the dollar from the route to " "avoid problems including URLs." ), ) @override_settings(ROOT_URLCONF="check_framework.urls.contains_tuple") def test_contains_tuple_not_url_instance(self): result = check_url_config(None) warning = result[0] self.assertEqual(warning.id, "urls.E004") self.assertRegex( warning.msg, ( r"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) " r"is invalid. Ensure that urlpatterns is a list of path\(\) and/or " r"re_path\(\) instances\.$" ), ) @override_settings(ROOT_URLCONF="check_framework.urls.include_contains_tuple") def test_contains_included_tuple(self): result = check_url_config(None) warning = result[0] self.assertEqual(warning.id, "urls.E004") self.assertRegex( warning.msg, ( r"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) " r"is invalid. Ensure that urlpatterns is a list of path\(\) and/or " r"re_path\(\) instances\.$" ), ) @override_settings(ROOT_URLCONF="check_framework.urls.beginning_with_slash") def test_beginning_with_slash(self): msg = ( "Your URL pattern '%s' has a route beginning with a '/'. Remove " "this slash as it is unnecessary. If this pattern is targeted in " "an include(), ensure the include() pattern has a trailing '/'." ) warning1, warning2 = check_url_config(None) self.assertEqual(warning1.id, "urls.W002") self.assertEqual(warning1.msg, msg % "/path-starting-with-slash/") self.assertEqual(warning2.id, "urls.W002") self.assertEqual(warning2.msg, msg % "/url-starting-with-slash/$") @override_settings( ROOT_URLCONF="check_framework.urls.beginning_with_slash", APPEND_SLASH=False, ) def test_beginning_with_slash_append_slash(self): # It can be useful to start a URL pattern with a slash when # APPEND_SLASH=False (#27238). result = check_url_config(None) self.assertEqual(result, []) @override_settings(ROOT_URLCONF="check_framework.urls.name_with_colon") def test_name_with_colon(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "urls.W003") expected_msg = ( "Your URL pattern '^$' [name='name_with:colon'] has a name including a ':'." ) self.assertIn(expected_msg, warning.msg) @override_settings(ROOT_URLCONF=None) def test_no_root_urlconf_in_settings(self): delattr(settings, "ROOT_URLCONF") result = check_url_config(None) self.assertEqual(result, []) def test_get_warning_for_invalid_pattern_string(self): warning = get_warning_for_invalid_pattern("")[0] self.assertEqual( warning.hint, "Try removing the string ''. The list of urlpatterns should " "not have a prefix string as the first element.", ) def test_get_warning_for_invalid_pattern_tuple(self): warning = get_warning_for_invalid_pattern((r"^$", lambda x: x))[0] self.assertEqual(warning.hint, "Try using path() instead of a tuple.") def test_get_warning_for_invalid_pattern_other(self): warning = get_warning_for_invalid_pattern(object())[0] self.assertIsNone(warning.hint) @override_settings(ROOT_URLCONF="check_framework.urls.non_unique_namespaces") def test_check_non_unique_namespaces(self): result = check_url_namespaces_unique(None) self.assertEqual(len(result), 2) non_unique_namespaces = ["app-ns1", "app-1"] warning_messages = [ "URL namespace '{}' isn't unique. You may not be able to reverse " "all URLs in this namespace".format(namespace) for namespace in non_unique_namespaces ] for warning in result: self.assertIsInstance(warning, Warning) self.assertEqual("urls.W005", warning.id) self.assertIn(warning.msg, warning_messages) @override_settings(ROOT_URLCONF="check_framework.urls.unique_namespaces") def test_check_unique_namespaces(self): result = check_url_namespaces_unique(None) self.assertEqual(result, []) @override_settings(ROOT_URLCONF="check_framework.urls.cbv_as_view") def test_check_view_not_class(self): self.assertEqual( check_url_config(None), [ Error( "Your URL pattern 'missing_as_view' has an invalid view, pass " "EmptyCBV.as_view() instead of EmptyCBV.", id="urls.E009", ), ], ) @override_settings( ROOT_URLCONF="check_framework.urls.path_compatibility.matched_angle_brackets" ) def test_no_warnings_matched_angle_brackets(self): self.assertEqual(check_url_config(None), []) @override_settings( ROOT_URLCONF="check_framework.urls.path_compatibility.unmatched_angle_brackets" ) def test_warning_unmatched_angle_brackets(self): self.assertEqual( check_url_config(None), [ Warning( "Your URL pattern 'beginning-with/<angle_bracket' has an unmatched " "'<' bracket.", id="urls.W010", ), Warning( "Your URL pattern 'ending-with/angle_bracket>' has an unmatched " "'>' bracket.", id="urls.W010", ), Warning( "Your URL pattern 'closed_angle>/x/<opened_angle' has an unmatched " "'>' bracket.", id="urls.W010", ), Warning( "Your URL pattern 'closed_angle>/x/<opened_angle' has an unmatched " "'<' bracket.", id="urls.W010", ), Warning( "Your URL pattern '<mixed>angle_bracket>' has an unmatched '>' " "bracket.", id="urls.W010", ), ], ) class UpdatedToPathTests(SimpleTestCase): @override_settings( ROOT_URLCONF="check_framework.urls.path_compatibility.contains_re_named_group" ) def test_contains_re_named_group(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "2_0.W001") expected_msg = "Your URL pattern '(?P<named_group>\\d+)' has a route" self.assertIn(expected_msg, warning.msg) @override_settings( ROOT_URLCONF="check_framework.urls.path_compatibility.beginning_with_caret" ) def test_beginning_with_caret(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "2_0.W001") expected_msg = "Your URL pattern '^beginning-with-caret' has a route" self.assertIn(expected_msg, warning.msg) @override_settings( ROOT_URLCONF="check_framework.urls.path_compatibility.ending_with_dollar" ) def test_ending_with_dollar(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "2_0.W001") expected_msg = "Your URL pattern 'ending-with-dollar$' has a route" self.assertIn(expected_msg, warning.msg) class CheckCustomErrorHandlersTests(SimpleTestCase): @override_settings( ROOT_URLCONF="check_framework.urls.bad_function_based_error_handlers", ) def test_bad_function_based_handlers(self): result = check_custom_error_handlers(None) self.assertEqual(len(result), 4) for code, num_params, error in zip([400, 403, 404, 500], [2, 2, 2, 1], result): with self.subTest("handler{}".format(code)): self.assertEqual( error, Error( "The custom handler{} view 'check_framework.urls." "bad_function_based_error_handlers.bad_handler' " "does not take the correct number of arguments " "(request{}).".format( code, ", exception" if num_params == 2 else "" ), id="urls.E007", ), ) @override_settings( ROOT_URLCONF="check_framework.urls.bad_class_based_error_handlers", ) def test_bad_class_based_handlers(self): result = check_custom_error_handlers(None) self.assertEqual(len(result), 4) for code, num_params, error in zip([400, 403, 404, 500], [2, 2, 2, 1], result): with self.subTest("handler%s" % code): self.assertEqual( error, Error( "The custom handler%s view 'check_framework.urls." "bad_class_based_error_handlers.HandlerView.as_view." "<locals>.view' does not take the correct number of " "arguments (request%s)." % ( code, ", exception" if num_params == 2 else "", ), id="urls.E007", ), ) @override_settings( ROOT_URLCONF="check_framework.urls.bad_error_handlers_invalid_path" ) def test_bad_handlers_invalid_path(self): result = check_custom_error_handlers(None) paths = [ "django.views.bad_handler", "django.invalid_module.bad_handler", "invalid_module.bad_handler", "django", ] hints = [ "Could not import '{}'. View does not exist in module django.views.", "Could not import '{}'. Parent module django.invalid_module does not " "exist.", "No module named 'invalid_module'", "Could not import '{}'. The path must be fully qualified.", ] for code, path, hint, error in zip([400, 403, 404, 500], paths, hints, result): with self.subTest("handler{}".format(code)): self.assertEqual( error, Error( "The custom handler{} view '{}' could not be imported.".format( code, path ), hint=hint.format(path), id="urls.E008", ), ) @override_settings( ROOT_URLCONF="check_framework.urls.good_function_based_error_handlers", ) def test_good_function_based_handlers(self): result = check_custom_error_handlers(None) self.assertEqual(result, []) @override_settings( ROOT_URLCONF="check_framework.urls.good_class_based_error_handlers", ) def test_good_class_based_handlers(self): result = check_custom_error_handlers(None) self.assertEqual(result, []) class CheckURLSettingsTests(SimpleTestCase): @override_settings(STATIC_URL="a/", MEDIA_URL="b/") def test_slash_no_errors(self): self.assertEqual(check_url_settings(None), []) @override_settings(STATIC_URL="", MEDIA_URL="") def test_empty_string_no_errors(self): self.assertEqual(check_url_settings(None), []) @override_settings(STATIC_URL="noslash") def test_static_url_no_slash(self): self.assertEqual(check_url_settings(None), [E006("STATIC_URL")]) @override_settings(STATIC_URL="slashes//") def test_static_url_double_slash_allowed(self): # The check allows for a double slash, presuming the user knows what # they are doing. self.assertEqual(check_url_settings(None), []) @override_settings(MEDIA_URL="noslash") def test_media_url_no_slash(self): self.assertEqual(check_url_settings(None), [E006("MEDIA_URL")])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/test_4_0_compatibility.py
tests/check_framework/test_4_0_compatibility.py
from django.core.checks import Error from django.core.checks.compatibility.django_4_0 import check_csrf_trusted_origins from django.test import SimpleTestCase from django.test.utils import override_settings class CheckCSRFTrustedOrigins(SimpleTestCase): @override_settings(CSRF_TRUSTED_ORIGINS=["example.com"]) def test_invalid_url(self): self.assertEqual( check_csrf_trusted_origins(None), [ Error( "As of Django 4.0, the values in the CSRF_TRUSTED_ORIGINS " "setting must start with a scheme (usually http:// or " "https://) but found example.com. See the release notes for " "details.", id="4_0.E001", ) ], ) @override_settings( CSRF_TRUSTED_ORIGINS=["http://example.com", "https://example.com"], ) def test_valid_urls(self): self.assertEqual(check_csrf_trusted_origins(None), [])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/__init__.py
tests/check_framework/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/tests.py
tests/check_framework/tests.py
import multiprocessing import sys from io import StringIO from unittest import mock, skipIf from django.apps import apps from django.core import checks from django.core.checks import Error, Tags, Warning from django.core.checks.messages import CheckMessage from django.core.checks.registry import CheckRegistry from django.core.management import call_command from django.core.management.base import CommandError from django.db import models from django.test import SimpleTestCase from django.test.utils import isolate_apps, override_settings, override_system_checks from .models import SimpleModel, my_check class DummyObj: def __repr__(self): return "obj" class SystemCheckFrameworkTests(SimpleTestCase): def test_register_and_run_checks(self): def f(**kwargs): calls[0] += 1 return [1, 2, 3] def f2(**kwargs): return [4] def f3(**kwargs): return [5] calls = [0] # test register as decorator registry = CheckRegistry() registry.register()(f) registry.register("tag1", "tag2")(f2) registry.register("tag2", deploy=True)(f3) # test register as function registry2 = CheckRegistry() registry2.register(f) registry2.register(f2, "tag1", "tag2") registry2.register(f3, "tag2", deploy=True) # check results errors = registry.run_checks() errors2 = registry2.run_checks() self.assertEqual(errors, errors2) self.assertEqual(sorted(errors), [1, 2, 3, 4]) self.assertEqual(calls[0], 2) errors = registry.run_checks(tags=["tag1"]) errors2 = registry2.run_checks(tags=["tag1"]) self.assertEqual(errors, errors2) self.assertEqual(sorted(errors), [4]) errors = registry.run_checks( tags=["tag1", "tag2"], include_deployment_checks=True ) errors2 = registry2.run_checks( tags=["tag1", "tag2"], include_deployment_checks=True ) self.assertEqual(errors, errors2) self.assertEqual(sorted(errors), [4, 5]) def test_register_no_kwargs_error(self): registry = CheckRegistry() msg = "Check functions must accept keyword arguments (**kwargs)." with self.assertRaisesMessage(TypeError, msg): @registry.register def no_kwargs(app_configs, databases): pass def test_register_run_checks_non_iterable(self): registry = CheckRegistry() @registry.register def return_non_iterable(**kwargs): return Error("Message") msg = ( "The function %r did not return a list. All functions registered " "with the checks registry must return a list." % return_non_iterable ) with self.assertRaisesMessage(TypeError, msg): registry.run_checks() def test_run_checks_database_exclusion(self): registry = CheckRegistry() database_errors = [checks.Warning("Database Check")] @registry.register(Tags.database) def database_system_check(**kwargs): return database_errors errors = registry.run_checks() self.assertEqual(errors, []) errors = registry.run_checks(databases=["default"]) self.assertEqual(errors, database_errors) class MessageTests(SimpleTestCase): def test_printing(self): e = Error("Message", hint="Hint", obj=DummyObj()) expected = "obj: Message\n\tHINT: Hint" self.assertEqual(str(e), expected) def test_printing_no_hint(self): e = Error("Message", obj=DummyObj()) expected = "obj: Message" self.assertEqual(str(e), expected) def test_printing_no_object(self): e = Error("Message", hint="Hint") expected = "?: Message\n\tHINT: Hint" self.assertEqual(str(e), expected) def test_printing_with_given_id(self): e = Error("Message", hint="Hint", obj=DummyObj(), id="ID") expected = "obj: (ID) Message\n\tHINT: Hint" self.assertEqual(str(e), expected) def test_printing_field_error(self): field = SimpleModel._meta.get_field("field") e = Error("Error", obj=field) expected = "check_framework.SimpleModel.field: Error" self.assertEqual(str(e), expected) def test_printing_model_error(self): e = Error("Error", obj=SimpleModel) expected = "check_framework.SimpleModel: Error" self.assertEqual(str(e), expected) def test_printing_manager_error(self): manager = SimpleModel.manager e = Error("Error", obj=manager) expected = "check_framework.SimpleModel.manager: Error" self.assertEqual(str(e), expected) def test_equal_to_self(self): e = Error("Error", obj=SimpleModel) self.assertEqual(e, e) def test_equal_to_same_constructed_check(self): e1 = Error("Error", obj=SimpleModel) e2 = Error("Error", obj=SimpleModel) self.assertEqual(e1, e2) def test_not_equal_to_different_constructed_check(self): e1 = Error("Error", obj=SimpleModel) e2 = Error("Error2", obj=SimpleModel) self.assertNotEqual(e1, e2) def test_not_equal_to_non_check(self): e = Error("Error", obj=DummyObj()) self.assertNotEqual(e, "a string") def test_invalid_level(self): msg = "The first argument should be level." with self.assertRaisesMessage(TypeError, msg): CheckMessage("ERROR", "Message") def simple_system_check(**kwargs): simple_system_check.kwargs = kwargs return [] def tagged_system_check(**kwargs): tagged_system_check.kwargs = kwargs return [checks.Warning("System Check")] tagged_system_check.tags = ["simpletag"] def deployment_system_check(**kwargs): deployment_system_check.kwargs = kwargs return [checks.Warning("Deployment Check")] deployment_system_check.tags = ["deploymenttag"] class CheckCommandTests(SimpleTestCase): def setUp(self): simple_system_check.kwargs = None tagged_system_check.kwargs = None self.old_stdout, self.old_stderr = sys.stdout, sys.stderr sys.stdout, sys.stderr = StringIO(), StringIO() def tearDown(self): sys.stdout, sys.stderr = self.old_stdout, self.old_stderr @override_system_checks([simple_system_check, tagged_system_check]) def test_simple_call(self): call_command("check") self.assertEqual( simple_system_check.kwargs, {"app_configs": None, "databases": ["default", "other"]}, ) self.assertEqual( tagged_system_check.kwargs, {"app_configs": None, "databases": ["default", "other"]}, ) @override_system_checks([simple_system_check, tagged_system_check]) def test_given_app(self): call_command("check", "auth", "admin") auth_config = apps.get_app_config("auth") admin_config = apps.get_app_config("admin") self.assertEqual( simple_system_check.kwargs, { "app_configs": [auth_config, admin_config], "databases": ["default", "other"], }, ) self.assertEqual( tagged_system_check.kwargs, { "app_configs": [auth_config, admin_config], "databases": ["default", "other"], }, ) @override_system_checks([simple_system_check, tagged_system_check]) def test_given_tag(self): call_command("check", tags=["simpletag"]) self.assertIsNone(simple_system_check.kwargs) self.assertEqual( tagged_system_check.kwargs, {"app_configs": None, "databases": ["default", "other"]}, ) @override_system_checks([simple_system_check, tagged_system_check]) def test_invalid_tag(self): msg = 'There is no system check with the "missingtag" tag.' with self.assertRaisesMessage(CommandError, msg): call_command("check", tags=["missingtag"]) @override_system_checks([simple_system_check]) def test_list_tags_empty(self): call_command("check", list_tags=True) self.assertEqual("\n", sys.stdout.getvalue()) @override_system_checks([tagged_system_check]) def test_list_tags(self): call_command("check", list_tags=True) self.assertEqual("simpletag\n", sys.stdout.getvalue()) @override_system_checks( [tagged_system_check], deployment_checks=[deployment_system_check] ) def test_list_deployment_check_omitted(self): call_command("check", list_tags=True) self.assertEqual("simpletag\n", sys.stdout.getvalue()) @override_system_checks( [tagged_system_check], deployment_checks=[deployment_system_check] ) def test_list_deployment_check_included(self): call_command("check", deploy=True, list_tags=True) self.assertEqual("deploymenttag\nsimpletag\n", sys.stdout.getvalue()) @override_system_checks( [tagged_system_check], deployment_checks=[deployment_system_check] ) def test_tags_deployment_check_omitted(self): msg = 'There is no system check with the "deploymenttag" tag.' with self.assertRaisesMessage(CommandError, msg): call_command("check", tags=["deploymenttag"]) @override_system_checks( [tagged_system_check], deployment_checks=[deployment_system_check] ) def test_tags_deployment_check_included(self): call_command("check", deploy=True, tags=["deploymenttag"]) self.assertIn("Deployment Check", sys.stderr.getvalue()) @override_system_checks([tagged_system_check]) def test_fail_level(self): with self.assertRaises(CommandError): call_command("check", fail_level="WARNING") def test_database_system_checks(self): database_check = mock.Mock(return_value=[], tags=[Tags.database]) with override_system_checks([database_check]): call_command("check") database_check.assert_not_called() call_command("check", databases=["default"]) database_check.assert_called_once_with( app_configs=None, databases=["default"] ) def custom_error_system_check(app_configs, **kwargs): return [Error("Error", id="myerrorcheck.E001")] def custom_warning_system_check(app_configs, **kwargs): return [Warning("Warning", id="mywarningcheck.E001")] class SilencingCheckTests(SimpleTestCase): def setUp(self): self.old_stdout, self.old_stderr = sys.stdout, sys.stderr self.stdout, self.stderr = StringIO(), StringIO() sys.stdout, sys.stderr = self.stdout, self.stderr def tearDown(self): sys.stdout, sys.stderr = self.old_stdout, self.old_stderr @override_settings(SILENCED_SYSTEM_CHECKS=["myerrorcheck.E001"]) @override_system_checks([custom_error_system_check]) def test_silenced_error(self): out = StringIO() err = StringIO() call_command("check", stdout=out, stderr=err) self.assertEqual( out.getvalue(), "System check identified no issues (1 silenced).\n" ) self.assertEqual(err.getvalue(), "") @override_settings(SILENCED_SYSTEM_CHECKS=["mywarningcheck.E001"]) @override_system_checks([custom_warning_system_check]) def test_silenced_warning(self): out = StringIO() err = StringIO() call_command("check", stdout=out, stderr=err) self.assertEqual( out.getvalue(), "System check identified no issues (1 silenced).\n" ) self.assertEqual(err.getvalue(), "") class CheckFrameworkReservedNamesTests(SimpleTestCase): @isolate_apps("check_framework", kwarg_name="apps") @override_system_checks([checks.model_checks.check_all_models]) def test_model_check_method_not_shadowed(self, apps): class ModelWithAttributeCalledCheck(models.Model): check = 42 class ModelWithFieldCalledCheck(models.Model): check = models.IntegerField() class ModelWithRelatedManagerCalledCheck(models.Model): pass class ModelWithDescriptorCalledCheck(models.Model): check = models.ForeignKey( ModelWithRelatedManagerCalledCheck, models.CASCADE ) article = models.ForeignKey( ModelWithRelatedManagerCalledCheck, models.CASCADE, related_name="check", ) errors = checks.run_checks(app_configs=apps.get_app_configs()) expected = [ Error( "The 'ModelWithAttributeCalledCheck.check()' class method is " "currently overridden by 42.", obj=ModelWithAttributeCalledCheck, id="models.E020", ), Error( "The 'ModelWithFieldCalledCheck.check()' class method is " "currently overridden by %r." % ModelWithFieldCalledCheck.check, obj=ModelWithFieldCalledCheck, id="models.E020", ), Error( "The 'ModelWithRelatedManagerCalledCheck.check()' class method is " "currently overridden by %r." % ModelWithRelatedManagerCalledCheck.check, obj=ModelWithRelatedManagerCalledCheck, id="models.E020", ), Error( "The 'ModelWithDescriptorCalledCheck.check()' class method is " "currently overridden by %r." % ModelWithDescriptorCalledCheck.check, obj=ModelWithDescriptorCalledCheck, id="models.E020", ), ] self.assertEqual(errors, expected) @skipIf( multiprocessing.get_start_method() == "spawn", "Spawning reimports modules, overwriting my_check.did_run to False, making this " "test useless.", ) class ChecksRunDuringTests(SimpleTestCase): databases = "__all__" def test_registered_check_did_run(self): self.assertTrue(my_check.did_run)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/test_caches.py
tests/check_framework/test_caches.py
import pathlib from django.core.checks import Warning from django.core.checks.caches import ( E001, check_cache_location_not_exposed, check_default_cache_is_configured, check_file_based_cache_is_absolute, ) from django.test import SimpleTestCase from django.test.utils import override_settings class CheckCacheSettingsAppDirsTest(SimpleTestCase): VALID_CACHES_CONFIGURATION = { "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", }, } INVALID_CACHES_CONFIGURATION = { "other": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", }, } @override_settings(CACHES=VALID_CACHES_CONFIGURATION) def test_default_cache_included(self): """ Don't error if 'default' is present in CACHES setting. """ self.assertEqual(check_default_cache_is_configured(None), []) @override_settings(CACHES=INVALID_CACHES_CONFIGURATION) def test_default_cache_not_included(self): """ Error if 'default' not present in CACHES setting. """ self.assertEqual(check_default_cache_is_configured(None), [E001]) class CheckCacheLocationTest(SimpleTestCase): warning_message = ( "Your 'default' cache configuration might expose your cache or lead " "to corruption of your data because its LOCATION %s %s." ) @staticmethod def get_settings(setting, cache_path, setting_path): return { "CACHES": { "default": { "BACKEND": "django.core.cache.backends.filebased.FileBasedCache", "LOCATION": cache_path, }, }, setting: [setting_path] if setting == "STATICFILES_DIRS" else setting_path, } def test_cache_path_matches_media_static_setting(self): root = pathlib.Path.cwd() for setting in ("MEDIA_ROOT", "STATIC_ROOT", "STATICFILES_DIRS"): settings = self.get_settings(setting, root, root) with self.subTest(setting=setting), self.settings(**settings): msg = self.warning_message % ("matches", setting) self.assertEqual( check_cache_location_not_exposed(None), [ Warning(msg, id="caches.W002"), ], ) def test_cache_path_inside_media_static_setting(self): root = pathlib.Path.cwd() for setting in ("MEDIA_ROOT", "STATIC_ROOT", "STATICFILES_DIRS"): settings = self.get_settings(setting, root / "cache", root) with self.subTest(setting=setting), self.settings(**settings): msg = self.warning_message % ("is inside", setting) self.assertEqual( check_cache_location_not_exposed(None), [ Warning(msg, id="caches.W002"), ], ) def test_cache_path_contains_media_static_setting(self): root = pathlib.Path.cwd() for setting in ("MEDIA_ROOT", "STATIC_ROOT", "STATICFILES_DIRS"): settings = self.get_settings(setting, root, root / "other") with self.subTest(setting=setting), self.settings(**settings): msg = self.warning_message % ("contains", setting) self.assertEqual( check_cache_location_not_exposed(None), [ Warning(msg, id="caches.W002"), ], ) def test_cache_path_not_conflict(self): root = pathlib.Path.cwd() for setting in ("MEDIA_ROOT", "STATIC_ROOT", "STATICFILES_DIRS"): settings = self.get_settings(setting, root / "cache", root / "other") with self.subTest(setting=setting), self.settings(**settings): self.assertEqual(check_cache_location_not_exposed(None), []) def test_staticfiles_dirs_prefix(self): root = pathlib.Path.cwd() tests = [ (root, root, "matches"), (root / "cache", root, "is inside"), (root, root / "other", "contains"), ] for cache_path, setting_path, msg in tests: settings = self.get_settings( "STATICFILES_DIRS", cache_path, ("prefix", setting_path), ) with self.subTest(path=setting_path), self.settings(**settings): msg = self.warning_message % (msg, "STATICFILES_DIRS") self.assertEqual( check_cache_location_not_exposed(None), [ Warning(msg, id="caches.W002"), ], ) def test_staticfiles_dirs_prefix_not_conflict(self): root = pathlib.Path.cwd() settings = self.get_settings( "STATICFILES_DIRS", root / "cache", ("prefix", root / "other"), ) with self.settings(**settings): self.assertEqual(check_cache_location_not_exposed(None), []) class CheckCacheAbsolutePath(SimpleTestCase): def test_absolute_path(self): with self.settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.filebased.FileBasedCache", "LOCATION": pathlib.Path.cwd() / "cache", }, } ): self.assertEqual(check_file_based_cache_is_absolute(None), []) def test_relative_path(self): with self.settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.filebased.FileBasedCache", "LOCATION": "cache", }, } ): self.assertEqual( check_file_based_cache_is_absolute(None), [ Warning( "Your 'default' cache LOCATION path is relative. Use an " "absolute path instead.", id="caches.W003", ), ], )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/test_security.py
tests/check_framework/test_security.py
import itertools from django.conf import settings from django.core.checks.messages import Error, Warning from django.core.checks.security import base, csrf, sessions from django.core.management.utils import get_random_secret_key from django.test import SimpleTestCase from django.test.utils import override_settings from django.views.generic import View class CheckSessionCookieSecureTest(SimpleTestCase): @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_secure_with_installed_app(self): """ Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions" is in INSTALLED_APPS. """ self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W010]) @override_settings( SESSION_COOKIE_SECURE="1", INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_secure_with_installed_app_truthy(self): """SESSION_COOKIE_SECURE must be boolean.""" self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W010]) @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=[], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_secure_with_middleware(self): """ Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions.middleware.SessionMiddleware" is in MIDDLEWARE. """ self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W011]) @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_secure_both(self): """ If SESSION_COOKIE_SECURE is off and we find both the session app and the middleware, provide one common warning. """ self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W012]) @override_settings( SESSION_COOKIE_SECURE=True, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_secure_true(self): """ If SESSION_COOKIE_SECURE is on, there's no warning about it. """ self.assertEqual(sessions.check_session_cookie_secure(None), []) class CheckSessionCookieHttpOnlyTest(SimpleTestCase): @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_httponly_with_installed_app(self): """ Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions" is in INSTALLED_APPS. """ self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W013]) @override_settings( SESSION_COOKIE_HTTPONLY="1", INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_httponly_with_installed_app_truthy(self): """SESSION_COOKIE_HTTPONLY must be boolean.""" self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W013]) @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=[], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_httponly_with_middleware(self): """ Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions.middleware.SessionMiddleware" is in MIDDLEWARE. """ self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W014]) @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_httponly_both(self): """ If SESSION_COOKIE_HTTPONLY is off and we find both the session app and the middleware, provide one common warning. """ self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W015]) @override_settings( SESSION_COOKIE_HTTPONLY=True, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_httponly_true(self): """ If SESSION_COOKIE_HTTPONLY is on, there's no warning about it. """ self.assertEqual(sessions.check_session_cookie_httponly(None), []) class CheckCSRFMiddlewareTest(SimpleTestCase): @override_settings(MIDDLEWARE=[]) def test_no_csrf_middleware(self): """ Warn if CsrfViewMiddleware isn't in MIDDLEWARE. """ self.assertEqual(csrf.check_csrf_middleware(None), [csrf.W003]) @override_settings(MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"]) def test_with_csrf_middleware(self): self.assertEqual(csrf.check_csrf_middleware(None), []) class CheckCSRFCookieSecureTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_COOKIE_SECURE=False, ) def test_with_csrf_cookie_secure_false(self): """ Warn if CsrfViewMiddleware is in MIDDLEWARE but CSRF_COOKIE_SECURE isn't True. """ self.assertEqual(csrf.check_csrf_cookie_secure(None), [csrf.W016]) @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_COOKIE_SECURE="1", ) def test_with_csrf_cookie_secure_truthy(self): """CSRF_COOKIE_SECURE must be boolean.""" self.assertEqual(csrf.check_csrf_cookie_secure(None), [csrf.W016]) @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_USE_SESSIONS=True, CSRF_COOKIE_SECURE=False, ) def test_use_sessions_with_csrf_cookie_secure_false(self): """ No warning if CSRF_COOKIE_SECURE isn't True while CSRF_USE_SESSIONS is True. """ self.assertEqual(csrf.check_csrf_cookie_secure(None), []) @override_settings(MIDDLEWARE=[], CSRF_COOKIE_SECURE=False) def test_with_csrf_cookie_secure_false_no_middleware(self): """ No warning if CsrfViewMiddleware isn't in MIDDLEWARE, even if CSRF_COOKIE_SECURE is False. """ self.assertEqual(csrf.check_csrf_cookie_secure(None), []) @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_COOKIE_SECURE=True, ) def test_with_csrf_cookie_secure_true(self): self.assertEqual(csrf.check_csrf_cookie_secure(None), []) class CheckSecurityMiddlewareTest(SimpleTestCase): @override_settings(MIDDLEWARE=[]) def test_no_security_middleware(self): """ Warn if SecurityMiddleware isn't in MIDDLEWARE. """ self.assertEqual(base.check_security_middleware(None), [base.W001]) @override_settings(MIDDLEWARE=["django.middleware.security.SecurityMiddleware"]) def test_with_security_middleware(self): self.assertEqual(base.check_security_middleware(None), []) class CheckStrictTransportSecurityTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_SECONDS=0, ) def test_no_sts(self): """ Warn if SECURE_HSTS_SECONDS isn't > 0. """ self.assertEqual(base.check_sts(None), [base.W004]) @override_settings(MIDDLEWARE=[], SECURE_HSTS_SECONDS=0) def test_no_sts_no_middleware(self): """ Don't warn if SECURE_HSTS_SECONDS isn't > 0 and SecurityMiddleware isn't installed. """ self.assertEqual(base.check_sts(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_SECONDS=3600, ) def test_with_sts(self): self.assertEqual(base.check_sts(None), []) class CheckStrictTransportSecuritySubdomainsTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_INCLUDE_SUBDOMAINS=False, SECURE_HSTS_SECONDS=3600, ) def test_no_sts_subdomains(self): """ Warn if SECURE_HSTS_INCLUDE_SUBDOMAINS isn't True. """ self.assertEqual(base.check_sts_include_subdomains(None), [base.W005]) @override_settings( MIDDLEWARE=[], SECURE_HSTS_INCLUDE_SUBDOMAINS=False, SECURE_HSTS_SECONDS=3600, ) def test_no_sts_subdomains_no_middleware(self): """ Don't warn if SecurityMiddleware isn't installed. """ self.assertEqual(base.check_sts_include_subdomains(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=False, SECURE_HSTS_SECONDS=None, ) def test_no_sts_subdomains_no_seconds(self): """ Don't warn if SECURE_HSTS_SECONDS isn't set. """ self.assertEqual(base.check_sts_include_subdomains(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_INCLUDE_SUBDOMAINS=True, SECURE_HSTS_SECONDS=3600, ) def test_with_sts_subdomains(self): self.assertEqual(base.check_sts_include_subdomains(None), []) class CheckStrictTransportSecurityPreloadTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_PRELOAD=False, SECURE_HSTS_SECONDS=3600, ) def test_no_sts_preload(self): """ Warn if SECURE_HSTS_PRELOAD isn't True. """ self.assertEqual(base.check_sts_preload(None), [base.W021]) @override_settings( MIDDLEWARE=[], SECURE_HSTS_PRELOAD=False, SECURE_HSTS_SECONDS=3600 ) def test_no_sts_preload_no_middleware(self): """ Don't warn if SecurityMiddleware isn't installed. """ self.assertEqual(base.check_sts_preload(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=False, SECURE_HSTS_SECONDS=None, ) def test_no_sts_preload_no_seconds(self): """ Don't warn if SECURE_HSTS_SECONDS isn't set. """ self.assertEqual(base.check_sts_preload(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_PRELOAD=True, SECURE_HSTS_SECONDS=3600, ) def test_with_sts_preload(self): self.assertEqual(base.check_sts_preload(None), []) class CheckXFrameOptionsMiddlewareTest(SimpleTestCase): @override_settings(MIDDLEWARE=[]) def test_middleware_not_installed(self): """ Warn if XFrameOptionsMiddleware isn't in MIDDLEWARE. """ self.assertEqual(base.check_xframe_options_middleware(None), [base.W002]) @override_settings( MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"] ) def test_middleware_installed(self): self.assertEqual(base.check_xframe_options_middleware(None), []) class CheckXFrameOptionsDenyTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"], X_FRAME_OPTIONS="SAMEORIGIN", ) def test_x_frame_options_not_deny(self): """ Warn if XFrameOptionsMiddleware is in MIDDLEWARE but X_FRAME_OPTIONS isn't 'DENY'. """ self.assertEqual(base.check_xframe_deny(None), [base.W019]) @override_settings(MIDDLEWARE=[], X_FRAME_OPTIONS="SAMEORIGIN") def test_middleware_not_installed(self): """ No error if XFrameOptionsMiddleware isn't in MIDDLEWARE even if X_FRAME_OPTIONS isn't 'DENY'. """ self.assertEqual(base.check_xframe_deny(None), []) @override_settings( MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"], X_FRAME_OPTIONS="DENY", ) def test_xframe_deny(self): self.assertEqual(base.check_xframe_deny(None), []) class CheckContentTypeNosniffTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_CONTENT_TYPE_NOSNIFF=False, ) def test_no_content_type_nosniff(self): """ Warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True. """ self.assertEqual(base.check_content_type_nosniff(None), [base.W006]) @override_settings(MIDDLEWARE=[], SECURE_CONTENT_TYPE_NOSNIFF=False) def test_no_content_type_nosniff_no_middleware(self): """ Don't warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True and SecurityMiddleware isn't in MIDDLEWARE. """ self.assertEqual(base.check_content_type_nosniff(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_CONTENT_TYPE_NOSNIFF=True, ) def test_with_content_type_nosniff(self): self.assertEqual(base.check_content_type_nosniff(None), []) class CheckSSLRedirectTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=False, ) def test_no_ssl_redirect(self): """ Warn if SECURE_SSL_REDIRECT isn't True. """ self.assertEqual(base.check_ssl_redirect(None), [base.W008]) @override_settings(MIDDLEWARE=[], SECURE_SSL_REDIRECT=False) def test_no_ssl_redirect_no_middleware(self): """ Don't warn if SECURE_SSL_REDIRECT is False and SecurityMiddleware isn't installed. """ self.assertEqual(base.check_ssl_redirect(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=True, ) def test_with_ssl_redirect(self): self.assertEqual(base.check_ssl_redirect(None), []) class CheckSecretKeyTest(SimpleTestCase): @override_settings(SECRET_KEY=("abcdefghijklmnopqrstuvwx" * 2) + "ab") def test_okay_secret_key(self): self.assertEqual(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH) self.assertGreater( len(set(settings.SECRET_KEY)), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS ) self.assertEqual(base.check_secret_key(None), []) @override_settings(SECRET_KEY="") def test_empty_secret_key(self): self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings(SECRET_KEY=None) def test_missing_secret_key(self): del settings.SECRET_KEY self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings(SECRET_KEY=None) def test_none_secret_key(self): self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings( SECRET_KEY=base.SECRET_KEY_INSECURE_PREFIX + get_random_secret_key() ) def test_insecure_secret_key(self): self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings(SECRET_KEY=("abcdefghijklmnopqrstuvwx" * 2) + "a") def test_low_length_secret_key(self): self.assertEqual(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH - 1) self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings(SECRET_KEY="abcd" * 20) def test_low_entropy_secret_key(self): self.assertGreater(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH) self.assertLess( len(set(settings.SECRET_KEY)), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS ) self.assertEqual(base.check_secret_key(None), [base.W009]) class CheckSecretKeyFallbacksTest(SimpleTestCase): @override_settings(SECRET_KEY_FALLBACKS=[("abcdefghijklmnopqrstuvwx" * 2) + "ab"]) def test_okay_secret_key_fallbacks(self): self.assertEqual( len(settings.SECRET_KEY_FALLBACKS[0]), base.SECRET_KEY_MIN_LENGTH, ) self.assertGreater( len(set(settings.SECRET_KEY_FALLBACKS[0])), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS, ) self.assertEqual(base.check_secret_key_fallbacks(None), []) def test_no_secret_key_fallbacks(self): with self.settings(SECRET_KEY_FALLBACKS=None): del settings.SECRET_KEY_FALLBACKS self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS", id=base.W025.id), ], ) @override_settings( SECRET_KEY_FALLBACKS=[base.SECRET_KEY_INSECURE_PREFIX + get_random_secret_key()] ) def test_insecure_secret_key_fallbacks(self): self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[0]", id=base.W025.id), ], ) @override_settings(SECRET_KEY_FALLBACKS=[("abcdefghijklmnopqrstuvwx" * 2) + "a"]) def test_low_length_secret_key_fallbacks(self): self.assertEqual( len(settings.SECRET_KEY_FALLBACKS[0]), base.SECRET_KEY_MIN_LENGTH - 1, ) self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[0]", id=base.W025.id), ], ) @override_settings(SECRET_KEY_FALLBACKS=["abcd" * 20]) def test_low_entropy_secret_key_fallbacks(self): self.assertGreater( len(settings.SECRET_KEY_FALLBACKS[0]), base.SECRET_KEY_MIN_LENGTH, ) self.assertLess( len(set(settings.SECRET_KEY_FALLBACKS[0])), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS, ) self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[0]", id=base.W025.id), ], ) @override_settings( SECRET_KEY_FALLBACKS=[ ("abcdefghijklmnopqrstuvwx" * 2) + "ab", "badkey", ] ) def test_multiple_keys(self): self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[1]", id=base.W025.id), ], ) @override_settings( SECRET_KEY_FALLBACKS=[ ("abcdefghijklmnopqrstuvwx" * 2) + "ab", "badkey1", "badkey2", ] ) def test_multiple_bad_keys(self): self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[1]", id=base.W025.id), Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[2]", id=base.W025.id), ], ) class CheckDebugTest(SimpleTestCase): @override_settings(DEBUG=True) def test_debug_true(self): """ Warn if DEBUG is True. """ self.assertEqual(base.check_debug(None), [base.W018]) @override_settings(DEBUG=False) def test_debug_false(self): self.assertEqual(base.check_debug(None), []) class CheckAllowedHostsTest(SimpleTestCase): @override_settings(ALLOWED_HOSTS=[]) def test_allowed_hosts_empty(self): self.assertEqual(base.check_allowed_hosts(None), [base.W020]) @override_settings(ALLOWED_HOSTS=[".example.com"]) def test_allowed_hosts_set(self): self.assertEqual(base.check_allowed_hosts(None), []) class CheckReferrerPolicyTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_REFERRER_POLICY=None, ) def test_no_referrer_policy(self): self.assertEqual(base.check_referrer_policy(None), [base.W022]) @override_settings(MIDDLEWARE=[], SECURE_REFERRER_POLICY=None) def test_no_referrer_policy_no_middleware(self): """ Don't warn if SECURE_REFERRER_POLICY is None and SecurityMiddleware isn't in MIDDLEWARE. """ self.assertEqual(base.check_referrer_policy(None), []) @override_settings(MIDDLEWARE=["django.middleware.security.SecurityMiddleware"]) def test_with_referrer_policy(self): tests = ( "strict-origin", "strict-origin,origin", "strict-origin, origin", ["strict-origin", "origin"], ("strict-origin", "origin"), ) for value in tests: with ( self.subTest(value=value), override_settings(SECURE_REFERRER_POLICY=value), ): self.assertEqual(base.check_referrer_policy(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_REFERRER_POLICY="invalid-value", ) def test_with_invalid_referrer_policy(self): self.assertEqual(base.check_referrer_policy(None), [base.E023]) def failure_view_with_invalid_signature(): pass good_class_based_csrf_failure_view = View.as_view() class CSRFFailureViewTest(SimpleTestCase): @override_settings(CSRF_FAILURE_VIEW="") def test_failure_view_import_error(self): self.assertEqual( csrf.check_csrf_failure_view(None), [ Error( "The CSRF failure view '' could not be imported.", id="security.E102", ) ], ) @override_settings( CSRF_FAILURE_VIEW=( "check_framework.test_security.failure_view_with_invalid_signature" ), ) def test_failure_view_invalid_signature(self): msg = ( "The CSRF failure view " "'check_framework.test_security.failure_view_with_invalid_signature' " "does not take the correct number of arguments." ) self.assertEqual( csrf.check_csrf_failure_view(None), [Error(msg, id="security.E101")], ) @override_settings( CSRF_FAILURE_VIEW=( "check_framework.test_security.good_class_based_csrf_failure_view" ), ) def test_failure_view_valid_class_based(self): self.assertEqual(csrf.check_csrf_failure_view(None), []) class CheckCrossOriginOpenerPolicyTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_CROSS_ORIGIN_OPENER_POLICY=None, ) def test_no_coop(self): self.assertEqual(base.check_cross_origin_opener_policy(None), []) @override_settings(MIDDLEWARE=["django.middleware.security.SecurityMiddleware"]) def test_with_coop(self): tests = ["same-origin", "same-origin-allow-popups", "unsafe-none"] for value in tests: with ( self.subTest(value=value), override_settings( SECURE_CROSS_ORIGIN_OPENER_POLICY=value, ), ): self.assertEqual(base.check_cross_origin_opener_policy(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_CROSS_ORIGIN_OPENER_POLICY="invalid-value", ) def test_with_invalid_coop(self): self.assertEqual(base.check_cross_origin_opener_policy(None), [base.E024]) class CheckSecureCSPTests(SimpleTestCase): """Tests for the CSP settings check function.""" def test_secure_csp_allowed_values(self): """Check should pass when both CSP settings are None or dicts.""" allowed_values = (None, {}, {"key": "value"}) combinations = itertools.product(allowed_values, repeat=2) for csp_value, csp_report_only_value in combinations: with ( self.subTest( csp_value=csp_value, csp_report_only_value=csp_report_only_value ), self.settings( SECURE_CSP=csp_value, SECURE_CSP_REPORT_ONLY=csp_report_only_value ), ): errors = base.check_csp_settings(None) self.assertEqual(errors, []) def test_secure_csp_invalid_values(self): """Check should fail when either CSP setting is not a dict.""" for value in ( False, True, 0, 42, "", "not-a-dict", set(), {"a", "b"}, [], [1, 2, 3, 4], ): with self.subTest(value=value): csp_error = Error( base.E026.msg % ("SECURE_CSP", value), id=base.E026.id ) with self.settings(SECURE_CSP=value): errors = base.check_csp_settings(None) self.assertEqual(errors, [csp_error]) csp_report_only_error = Error( base.E026.msg % ("SECURE_CSP_REPORT_ONLY", value), id=base.E026.id ) with self.settings(SECURE_CSP_REPORT_ONLY=value): errors = base.check_csp_settings(None) self.assertEqual(errors, [csp_report_only_error]) with self.settings(SECURE_CSP=value, SECURE_CSP_REPORT_ONLY=value): errors = base.check_csp_settings(None) self.assertEqual(errors, [csp_error, csp_report_only_error])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/test_templates.py
tests/check_framework/test_templates.py
from copy import deepcopy from itertools import chain from django.core.checks import Error, Warning from django.core.checks.templates import check_templates from django.template import engines from django.template.backends.base import BaseEngine from django.test import SimpleTestCase from django.test.utils import override_settings class ErrorEngine(BaseEngine): def __init__(self, params): params.pop("OPTIONS") super().__init__(params) def check(self, **kwargs): return [Error("Example")] class CheckTemplatesTests(SimpleTestCase): @override_settings( TEMPLATES=[ {"BACKEND": f"{__name__}.{ErrorEngine.__qualname__}", "NAME": "backend_1"}, {"BACKEND": f"{__name__}.{ErrorEngine.__qualname__}", "NAME": "backend_2"}, ] ) def test_errors_aggregated(self): errors = check_templates(None) self.assertEqual(errors, [Error("Example")] * 2) class CheckTemplateStringIfInvalidTest(SimpleTestCase): TEMPLATES_STRING_IF_INVALID = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "NAME": "backend_1", "OPTIONS": { "string_if_invalid": False, }, }, { "BACKEND": "django.template.backends.django.DjangoTemplates", "NAME": "backend_2", "OPTIONS": { "string_if_invalid": 42, }, }, ] def _get_error_for_engine(self, engine): value = engine.engine.string_if_invalid return Error( "'string_if_invalid' in TEMPLATES OPTIONS must be a string but got: %r " "(%s)." % (value, type(value)), obj=engine, id="templates.E002", ) def _check_engines(self, engines): return list( chain.from_iterable(e._check_string_if_invalid_is_string() for e in engines) ) @override_settings(TEMPLATES=TEMPLATES_STRING_IF_INVALID) def test_string_if_invalid_not_string(self): _engines = engines.all() errors = [ self._get_error_for_engine(_engines[0]), self._get_error_for_engine(_engines[1]), ] self.assertEqual(self._check_engines(_engines), errors) def test_string_if_invalid_first_is_string(self): TEMPLATES = deepcopy(self.TEMPLATES_STRING_IF_INVALID) TEMPLATES[0]["OPTIONS"]["string_if_invalid"] = "test" with self.settings(TEMPLATES=TEMPLATES): _engines = engines.all() errors = [self._get_error_for_engine(_engines[1])] self.assertEqual(self._check_engines(_engines), errors) def test_string_if_invalid_both_are_strings(self): TEMPLATES = deepcopy(self.TEMPLATES_STRING_IF_INVALID) TEMPLATES[0]["OPTIONS"]["string_if_invalid"] = "test" TEMPLATES[1]["OPTIONS"]["string_if_invalid"] = "test" with self.settings(TEMPLATES=TEMPLATES): self.assertEqual(self._check_engines(engines.all()), []) def test_string_if_invalid_not_specified(self): TEMPLATES = deepcopy(self.TEMPLATES_STRING_IF_INVALID) del TEMPLATES[1]["OPTIONS"]["string_if_invalid"] with self.settings(TEMPLATES=TEMPLATES): _engines = engines.all() errors = [self._get_error_for_engine(_engines[0])] self.assertEqual(self._check_engines(_engines), errors) class CheckTemplateTagLibrariesWithSameName(SimpleTestCase): def get_settings(self, module_name, module_path, name="django"): return { "BACKEND": "django.template.backends.django.DjangoTemplates", "NAME": name, "OPTIONS": { "libraries": { module_name: f"check_framework.template_test_apps.{module_path}", }, }, } def _get_error_for_engine(self, engine, modules): return Warning( f"'same_tags' is used for multiple template tag modules: {modules}", obj=engine, id="templates.W003", ) def _check_engines(self, engines): return list( chain.from_iterable( e._check_for_template_tags_with_the_same_name() for e in engines ) ) @override_settings( INSTALLED_APPS=[ "check_framework.template_test_apps.same_tags_app_1", "check_framework.template_test_apps.same_tags_app_2", ] ) def test_template_tags_with_same_name(self): _engines = engines.all() modules = ( "'check_framework.template_test_apps.same_tags_app_1.templatetags" ".same_tags', 'check_framework.template_test_apps.same_tags_app_2" ".templatetags.same_tags'" ) errors = [self._get_error_for_engine(_engines[0], modules)] self.assertEqual(self._check_engines(_engines), errors) def test_template_tags_for_separate_backends(self): # The "libraries" names are the same, but the backends are different. with self.settings( TEMPLATES=[ self.get_settings( "same_tags", "same_tags_app_1.templatetags.same_tags", name="backend_1", ), self.get_settings( "same_tags", "same_tags_app_2.templatetags.same_tags", name="backend_2", ), ] ): self.assertEqual(self._check_engines(engines.all()), []) @override_settings( INSTALLED_APPS=["check_framework.template_test_apps.same_tags_app_1"] ) def test_template_tags_same_library_in_installed_apps_libraries(self): with self.settings( TEMPLATES=[ self.get_settings( "same_tags", "same_tags_app_1.templatetags.same_tags" ), ] ): self.assertEqual(self._check_engines(engines.all()), []) @override_settings( INSTALLED_APPS=["check_framework.template_test_apps.same_tags_app_1"] ) def test_template_tags_with_same_library_name_and_module_name(self): modules = ( "'check_framework.template_test_apps.different_tags_app.templatetags" ".different_tags', 'check_framework.template_test_apps.same_tags_app_1" ".templatetags.same_tags'" ) with self.settings( TEMPLATES=[ self.get_settings( "same_tags", "different_tags_app.templatetags.different_tags" ), ] ): _engines = engines.all() errors = [self._get_error_for_engine(_engines[0], modules)] self.assertEqual(self._check_engines(_engines), errors) def test_template_tags_with_different_library_name(self): with self.settings( TEMPLATES=[ self.get_settings( "same_tags", "same_tags_app_1.templatetags.same_tags", name="backend_1", ), self.get_settings( "not_same_tags", "same_tags_app_2.templatetags.same_tags", name="backend_2", ), ] ): self.assertEqual(self._check_engines(engines.all()), []) @override_settings( INSTALLED_APPS=[ "check_framework.template_test_apps.same_tags_app_1", "check_framework.template_test_apps.different_tags_app", ] ) def test_template_tags_with_different_name(self): self.assertEqual(self._check_engines(engines.all()), [])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/test_commands.py
tests/check_framework/test_commands.py
from django.core import checks from django.core.checks import Error from django.test import SimpleTestCase from django.test.utils import isolate_apps, override_settings, override_system_checks @isolate_apps("check_framework.custom_commands_app", attr_name="apps") @override_settings(INSTALLED_APPS=["check_framework.custom_commands_app"]) @override_system_checks([checks.commands.migrate_and_makemigrations_autodetector]) class CommandCheckTests(SimpleTestCase): def test_migrate_and_makemigrations_autodetector_different(self): expected_error = Error( "The migrate and makemigrations commands must have the same " "autodetector.", hint=( "makemigrations.Command.autodetector is int, but " "migrate.Command.autodetector is MigrationAutodetector." ), id="commands.E001", ) self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [expected_error], )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/template_test_apps/__init__.py
tests/check_framework/template_test_apps/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/template_test_apps/different_tags_app/__init__.py
tests/check_framework/template_test_apps/different_tags_app/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/template_test_apps/different_tags_app/apps.py
tests/check_framework/template_test_apps/different_tags_app/apps.py
from django.apps import AppConfig class DifferentTagsAppAppConfig(AppConfig): name = "check_framework.template_test_apps.different_tags_app"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/template_test_apps/different_tags_app/templatetags/__init__.py
tests/check_framework/template_test_apps/different_tags_app/templatetags/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/template_test_apps/different_tags_app/templatetags/different_tags.py
tests/check_framework/template_test_apps/different_tags_app/templatetags/different_tags.py
from django.template import Library register = Library()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/template_test_apps/same_tags_app_2/__init__.py
tests/check_framework/template_test_apps/same_tags_app_2/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/template_test_apps/same_tags_app_2/apps.py
tests/check_framework/template_test_apps/same_tags_app_2/apps.py
from django.apps import AppConfig class SameTagsApp2AppConfig(AppConfig): name = "check_framework.template_test_apps.same_tags_app_2"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/template_test_apps/same_tags_app_2/templatetags/same_tags.py
tests/check_framework/template_test_apps/same_tags_app_2/templatetags/same_tags.py
from django.template import Library register = Library()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/template_test_apps/same_tags_app_2/templatetags/__init__.py
tests/check_framework/template_test_apps/same_tags_app_2/templatetags/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/check_framework/template_test_apps/same_tags_app_1/__init__.py
tests/check_framework/template_test_apps/same_tags_app_1/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false