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/resolve_url/__init__.py
tests/resolve_url/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/resolve_url/tests.py
tests/resolve_url/tests.py
from django.shortcuts import resolve_url from django.test import SimpleTestCase, override_settings from django.urls import NoReverseMatch, reverse_lazy from .models import UnimportantThing from .views import params_cbv, params_view, some_cbv, some_view @override_settings(ROOT_URLCONF="resolve_url.urls") class ResolveUrlTests(SimpleTestCase): """ Tests for the resolve_url() function. """ def test_url_path(self): """ Passing a URL path to resolve_url() results in the same url. """ self.assertEqual("/something/", resolve_url("/something/")) def test_relative_path(self): """ Passing a relative URL path to resolve_url() results in the same url. """ self.assertEqual("../", resolve_url("../")) self.assertEqual("../relative/", resolve_url("../relative/")) self.assertEqual("./", resolve_url("./")) self.assertEqual("./relative/", resolve_url("./relative/")) def test_full_url(self): """ Passing a full URL to resolve_url() results in the same url. """ url = "http://example.com/" self.assertEqual(url, resolve_url(url)) def test_model(self): """ Passing a model to resolve_url() results in get_absolute_url() being called on that model instance. """ m = UnimportantThing(importance=1) self.assertEqual(m.get_absolute_url(), resolve_url(m)) def test_view_function(self): """ Passing a view function to resolve_url() results in the URL path mapping to that view name. """ resolved_url = resolve_url(some_view) self.assertEqual("/some-url/", resolved_url) def test_view_function_with_kwargs(self): self.assertEqual("/params/django/", resolve_url(params_view, slug="django")) def test_view_function_with_args(self): self.assertEqual("/params/django/", resolve_url(params_view, "django")) def test_class_based_view(self): self.assertEqual("/some-cbv/", resolve_url(some_cbv)) def test_class_based_view_with_kwargs(self): self.assertEqual("/params-cbv/5/", resolve_url(params_cbv, pk=5)) def test_class_based_view_with_args(self): self.assertEqual("/params-cbv/5/", resolve_url(params_cbv, 5)) def test_missing_params_raise_no_reverse_match(self): with self.assertRaises(NoReverseMatch): resolve_url(params_view) with self.assertRaises(NoReverseMatch): resolve_url(params_cbv) def test_lazy_reverse(self): """ Passing the result of reverse_lazy is resolved to a real URL string. """ resolved_url = resolve_url(reverse_lazy("some-view")) self.assertIsInstance(resolved_url, str) self.assertEqual("/some-url/", resolved_url) def test_valid_view_name(self): """ Passing a view name to resolve_url() results in the URL path mapping to that view. """ resolved_url = resolve_url("some-view") self.assertEqual("/some-url/", resolved_url) def test_domain(self): """ Passing a domain to resolve_url() returns the same domain. """ self.assertEqual(resolve_url("example.com"), "example.com") def test_non_view_callable_raises_no_reverse_match(self): """ Passing a non-view callable into resolve_url() raises a NoReverseMatch exception. """ with self.assertRaises(NoReverseMatch): resolve_url(lambda: "asdf")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/resolve_url/urls.py
tests/resolve_url/urls.py
from django.urls import path from .views import params_cbv, params_view, some_cbv, some_view urlpatterns = [ path("params/<slug:slug>/", params_view, name="params-view"), path("params-cbv/<int:pk>/", params_cbv, name="params-cbv"), path("some-url/", some_view, name="some-view"), path("some-cbv/", some_cbv, name="some-cbv"), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/test_uuid.py
tests/db_functions/test_uuid.py
import uuid from datetime import datetime, timedelta, timezone from django.db import NotSupportedError, connection from django.db.models.functions import UUID4, UUID7 from django.test import TestCase from django.test.testcases import skipIfDBFeature, skipUnlessDBFeature from .models import UUIDModel class TestUUID(TestCase): @skipUnlessDBFeature("supports_uuid4_function") def test_uuid4(self): m1 = UUIDModel.objects.create() m2 = UUIDModel.objects.create() UUIDModel.objects.update(uuid=UUID4()) m1.refresh_from_db() m2.refresh_from_db() self.assertIsInstance(m1.uuid, uuid.UUID) self.assertEqual(m1.uuid.version, 4) self.assertNotEqual(m1.uuid, m2.uuid) @skipUnlessDBFeature("supports_uuid7_function") def test_uuid7(self): m1 = UUIDModel.objects.create() m2 = UUIDModel.objects.create() UUIDModel.objects.update(uuid=UUID7()) m1.refresh_from_db() m2.refresh_from_db() self.assertIsInstance(m1.uuid, uuid.UUID) self.assertEqual(m1.uuid.version, 7) self.assertNotEqual(m1.uuid, m2.uuid) @skipUnlessDBFeature("supports_uuid7_function_shift") def test_uuid7_shift(self): now = datetime.now(timezone.utc) past = datetime(2005, 11, 16, tzinfo=timezone.utc) shift = past - now m = UUIDModel.objects.create(uuid=UUID7(shift)) self.assertTrue(str(m.uuid).startswith("0107965e-e40"), m.uuid) @skipUnlessDBFeature("supports_uuid7_function_shift") def test_uuid7_shift_duration_field(self): now = datetime.now(timezone.utc) past = datetime(2005, 11, 16, tzinfo=timezone.utc) shift = past - now m = UUIDModel.objects.create(shift=shift) UUIDModel.objects.update(uuid=UUID7("shift")) m.refresh_from_db() self.assertTrue(str(m.uuid).startswith("0107965e-e40"), m.uuid) @skipIfDBFeature("supports_uuid4_function") def test_uuid4_unsupported(self): if connection.vendor == "mysql": if connection.mysql_is_mariadb: msg = "UUID4 requires MariaDB version 11.7 or later." else: msg = "UUID4 is not supported on MySQL." elif connection.vendor == "oracle": msg = "UUID4 requires Oracle version 23ai/26ai (23.9) or later." else: msg = "UUID4 is not supported on this database backend." with self.assertRaisesMessage(NotSupportedError, msg): UUIDModel.objects.update(uuid=UUID4()) @skipIfDBFeature("supports_uuid7_function") def test_uuid7_unsupported(self): if connection.vendor == "mysql": if connection.mysql_is_mariadb: msg = "UUID7 requires MariaDB version 11.7 or later." else: msg = "UUID7 is not supported on MySQL." elif connection.vendor == "postgresql": msg = "UUID7 requires PostgreSQL version 18 or later." elif connection.vendor == "sqlite": msg = "UUID7 on SQLite requires Python version 3.14 or later." else: msg = "UUID7 is not supported on this database backend." with self.assertRaisesMessage(NotSupportedError, msg): UUIDModel.objects.update(uuid=UUID7()) @skipUnlessDBFeature("supports_uuid7_function") @skipIfDBFeature("supports_uuid7_function_shift") def test_uuid7_shift_unsupported(self): msg = "The shift argument to UUID7 is not supported on this database backend." with self.assertRaisesMessage(NotSupportedError, msg): UUIDModel.objects.update(uuid=UUID7(shift=timedelta(hours=12)))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/models.py
tests/db_functions/models.py
""" Tests for built in Function expressions. """ from django.db import models class Author(models.Model): name = models.CharField(max_length=50) alias = models.CharField(max_length=50, null=True, blank=True) goes_by = models.CharField(max_length=50, null=True, blank=True) age = models.PositiveSmallIntegerField(default=30) class Article(models.Model): authors = models.ManyToManyField(Author, related_name="articles") title = models.CharField(max_length=50) summary = models.CharField(max_length=200, null=True, blank=True) text = models.TextField() written = models.DateTimeField() published = models.DateTimeField(null=True, blank=True) updated = models.DateTimeField(null=True, blank=True) views = models.PositiveIntegerField(default=0) class Fan(models.Model): name = models.CharField(max_length=50) age = models.PositiveSmallIntegerField(default=30) author = models.ForeignKey(Author, models.CASCADE, related_name="fans") fan_since = models.DateTimeField(null=True, blank=True) class DTModel(models.Model): name = models.CharField(max_length=32) start_datetime = models.DateTimeField(null=True, blank=True) end_datetime = models.DateTimeField(null=True, blank=True) start_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) start_time = models.TimeField(null=True, blank=True) end_time = models.TimeField(null=True, blank=True) duration = models.DurationField(null=True, blank=True) class DecimalModel(models.Model): n1 = models.DecimalField(decimal_places=2, max_digits=6) n2 = models.DecimalField(decimal_places=7, max_digits=9, null=True, blank=True) class IntegerModel(models.Model): big = models.BigIntegerField(null=True, blank=True) normal = models.IntegerField(null=True, blank=True) small = models.SmallIntegerField(null=True, blank=True) class FloatModel(models.Model): f1 = models.FloatField(null=True, blank=True) f2 = models.FloatField(null=True, blank=True) class UUIDModel(models.Model): uuid = models.UUIDField(null=True) shift = models.DurationField(null=True)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/__init__.py
tests/db_functions/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/tests.py
tests/db_functions/tests.py
from django.db.models import CharField from django.db.models import Value as V from django.db.models.functions import Coalesce, Length, Upper from django.test import TestCase from django.test.utils import register_lookup from .models import Author class UpperBilateral(Upper): bilateral = True class FunctionTests(TestCase): def test_nested_function_ordering(self): Author.objects.create(name="John Smith") Author.objects.create(name="Rhonda Simpson", alias="ronny") authors = Author.objects.order_by(Length(Coalesce("alias", "name"))) self.assertQuerySetEqual( authors, [ "Rhonda Simpson", "John Smith", ], lambda a: a.name, ) authors = Author.objects.order_by(Length(Coalesce("alias", "name")).desc()) self.assertQuerySetEqual( authors, [ "John Smith", "Rhonda Simpson", ], lambda a: a.name, ) def test_func_transform_bilateral(self): with register_lookup(CharField, UpperBilateral): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.filter(name__upper__exact="john smith") self.assertQuerySetEqual( authors.order_by("name"), [ "John Smith", ], lambda a: a.name, ) def test_func_transform_bilateral_multivalue(self): with register_lookup(CharField, UpperBilateral): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.filter(name__upper__in=["john smith", "rhonda"]) self.assertQuerySetEqual( authors.order_by("name"), [ "John Smith", "Rhonda", ], lambda a: a.name, ) def test_function_as_filter(self): Author.objects.create(name="John Smith", alias="SMITHJ") Author.objects.create(name="Rhonda") self.assertQuerySetEqual( Author.objects.filter(alias=Upper(V("smithj"))), ["John Smith"], lambda x: x.name, ) self.assertQuerySetEqual( Author.objects.exclude(alias=Upper(V("smithj"))), ["Rhonda"], lambda x: x.name, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/datetime/test_now.py
tests/db_functions/datetime/test_now.py
from datetime import datetime, timedelta from django.db import connection from django.db.models import TextField from django.db.models.functions import Cast, Now from django.test import TestCase from django.utils import timezone from ..models import Article lorem_ipsum = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" class NowTests(TestCase): def test_basic(self): a1 = Article.objects.create( title="How to Django", text=lorem_ipsum, written=timezone.now(), ) a2 = Article.objects.create( title="How to Time Travel", text=lorem_ipsum, written=timezone.now(), ) num_updated = Article.objects.filter(id=a1.id, published=None).update( published=Now() ) self.assertEqual(num_updated, 1) num_updated = Article.objects.filter(id=a1.id, published=None).update( published=Now() ) self.assertEqual(num_updated, 0) a1.refresh_from_db() self.assertIsInstance(a1.published, datetime) a2.published = Now() + timedelta(days=2) a2.save() a2.refresh_from_db() self.assertIsInstance(a2.published, datetime) self.assertQuerySetEqual( Article.objects.filter(published__lte=Now()), ["How to Django"], lambda a: a.title, ) self.assertQuerySetEqual( Article.objects.filter(published__gt=Now()), ["How to Time Travel"], lambda a: a.title, ) def test_microseconds(self): Article.objects.create( title="How to Django", text=lorem_ipsum, written=timezone.now(), ) now_string = ( Article.objects.annotate(now_string=Cast(Now(), TextField())) .get() .now_string ) precision = connection.features.time_cast_precision self.assertRegex(now_string, rf"^.*\.\d{{1,{precision}}}")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/datetime/test_extract_trunc.py
tests/db_functions/datetime/test_extract_trunc.py
import datetime import zoneinfo from django.conf import settings from django.db import DataError, OperationalError from django.db.models import ( DateField, DateTimeField, F, IntegerField, Max, OuterRef, Subquery, TimeField, ) from django.db.models.functions import ( Extract, ExtractDay, ExtractHour, ExtractIsoWeekDay, ExtractIsoYear, ExtractMinute, ExtractMonth, ExtractQuarter, ExtractSecond, ExtractWeek, ExtractWeekDay, ExtractYear, Trunc, TruncDate, TruncDay, TruncHour, TruncMinute, TruncMonth, TruncQuarter, TruncSecond, TruncTime, TruncWeek, TruncYear, ) from django.test import ( TestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from django.utils import timezone from ..models import Author, DTModel, Fan def truncate_to(value, kind, tzinfo=None): # Convert to target timezone before truncation if tzinfo is not None: value = value.astimezone(tzinfo) def truncate(value, kind): if kind == "second": return value.replace(microsecond=0) if kind == "minute": return value.replace(second=0, microsecond=0) if kind == "hour": return value.replace(minute=0, second=0, microsecond=0) if kind == "day": if isinstance(value, datetime.datetime): return value.replace(hour=0, minute=0, second=0, microsecond=0) return value if kind == "week": if isinstance(value, datetime.datetime): return (value - datetime.timedelta(days=value.weekday())).replace( hour=0, minute=0, second=0, microsecond=0 ) return value - datetime.timedelta(days=value.weekday()) if kind == "month": if isinstance(value, datetime.datetime): return value.replace(day=1, hour=0, minute=0, second=0, microsecond=0) return value.replace(day=1) if kind == "quarter": month_in_quarter = value.month - (value.month - 1) % 3 if isinstance(value, datetime.datetime): return value.replace( month=month_in_quarter, day=1, hour=0, minute=0, second=0, microsecond=0, ) return value.replace(month=month_in_quarter, day=1) # otherwise, truncate to year if isinstance(value, datetime.datetime): return value.replace( month=1, day=1, hour=0, minute=0, second=0, microsecond=0 ) return value.replace(month=1, day=1) value = truncate(value, kind) if tzinfo is not None: # If there was a daylight saving transition, then reset the timezone. value = timezone.make_aware(value.replace(tzinfo=None), tzinfo) return value @override_settings(USE_TZ=False) class DateFunctionTests(TestCase): def create_model(self, start_datetime, end_datetime): return DTModel.objects.create( name=start_datetime.isoformat() if start_datetime else "None", start_datetime=start_datetime, end_datetime=end_datetime, start_date=start_datetime.date() if start_datetime else None, end_date=end_datetime.date() if end_datetime else None, start_time=start_datetime.time() if start_datetime else None, end_time=end_datetime.time() if end_datetime else None, duration=( (end_datetime - start_datetime) if start_datetime and end_datetime else None ), ) def test_extract_year_exact_lookup(self): """ Extract year uses a BETWEEN filter to compare the year to allow indexes to be used. """ start_datetime = datetime.datetime(2015, 6, 15, 14, 10) end_datetime = datetime.datetime(2016, 6, 15, 14, 10) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) for lookup in ("year", "iso_year"): with self.subTest(lookup): qs = DTModel.objects.filter( **{"start_datetime__%s__exact" % lookup: 2015} ) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(" between "), 1) self.assertEqual(query_string.count("extract"), 0) # exact is implied and should be the same qs = DTModel.objects.filter(**{"start_datetime__%s" % lookup: 2015}) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(" between "), 1) self.assertEqual(query_string.count("extract"), 0) # date and datetime fields should behave the same qs = DTModel.objects.filter(**{"start_date__%s" % lookup: 2015}) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(" between "), 1) self.assertEqual(query_string.count("extract"), 0) # an expression rhs cannot use the between optimization. qs = DTModel.objects.annotate( start_year=ExtractYear("start_datetime"), ).filter(end_datetime__year=F("start_year") + 1) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(" between "), 0) self.assertEqual(query_string.count("extract"), 3) def test_extract_year_greaterthan_lookup(self): start_datetime = datetime.datetime(2015, 6, 15, 14, 10) end_datetime = datetime.datetime(2016, 6, 15, 14, 10) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) for lookup in ("year", "iso_year"): with self.subTest(lookup): qs = DTModel.objects.filter(**{"start_datetime__%s__gt" % lookup: 2015}) self.assertEqual(qs.count(), 1) self.assertEqual(str(qs.query).lower().count("extract"), 0) qs = DTModel.objects.filter( **{"start_datetime__%s__gte" % lookup: 2015} ) self.assertEqual(qs.count(), 2) self.assertEqual(str(qs.query).lower().count("extract"), 0) qs = DTModel.objects.annotate( start_year=ExtractYear("start_datetime"), ).filter(**{"end_datetime__%s__gte" % lookup: F("start_year")}) self.assertEqual(qs.count(), 1) self.assertGreaterEqual(str(qs.query).lower().count("extract"), 2) def test_extract_year_lessthan_lookup(self): start_datetime = datetime.datetime(2015, 6, 15, 14, 10) end_datetime = datetime.datetime(2016, 6, 15, 14, 10) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) for lookup in ("year", "iso_year"): with self.subTest(lookup): qs = DTModel.objects.filter(**{"start_datetime__%s__lt" % lookup: 2016}) self.assertEqual(qs.count(), 1) self.assertEqual(str(qs.query).count("extract"), 0) qs = DTModel.objects.filter( **{"start_datetime__%s__lte" % lookup: 2016} ) self.assertEqual(qs.count(), 2) self.assertEqual(str(qs.query).count("extract"), 0) qs = DTModel.objects.annotate( end_year=ExtractYear("end_datetime"), ).filter(**{"start_datetime__%s__lte" % lookup: F("end_year")}) self.assertEqual(qs.count(), 1) self.assertGreaterEqual(str(qs.query).lower().count("extract"), 2) def test_extract_lookup_name_sql_injection(self): start_datetime = datetime.datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime.datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) with self.assertRaises((OperationalError, ValueError)): DTModel.objects.filter( start_datetime__year=Extract( "start_datetime", "day' FROM start_datetime)) OR 1=1;--" ) ).exists() def test_extract_func(self): start_datetime = datetime.datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime.datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) with self.assertRaisesMessage(ValueError, "lookup_name must be provided"): Extract("start_datetime") msg = ( "Extract input expression must be DateField, DateTimeField, TimeField, or " "DurationField." ) with self.assertRaisesMessage(ValueError, msg): list(DTModel.objects.annotate(extracted=Extract("name", "hour"))) with self.assertRaisesMessage( ValueError, "Cannot extract time component 'second' from DateField 'start_date'.", ): list(DTModel.objects.annotate(extracted=Extract("start_date", "second"))) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "year") ).order_by("start_datetime"), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "quarter") ).order_by("start_datetime"), [(start_datetime, 2), (end_datetime, 2)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "month") ).order_by("start_datetime"), [ (start_datetime, start_datetime.month), (end_datetime, end_datetime.month), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "day") ).order_by("start_datetime"), [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "week") ).order_by("start_datetime"), [(start_datetime, 25), (end_datetime, 24)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "week_day") ).order_by("start_datetime"), [ (start_datetime, (start_datetime.isoweekday() % 7) + 1), (end_datetime, (end_datetime.isoweekday() % 7) + 1), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "iso_week_day"), ).order_by("start_datetime"), [ (start_datetime, start_datetime.isoweekday()), (end_datetime, end_datetime.isoweekday()), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "hour") ).order_by("start_datetime"), [(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "minute") ).order_by("start_datetime"), [ (start_datetime, start_datetime.minute), (end_datetime, end_datetime.minute), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "second") ).order_by("start_datetime"), [ (start_datetime, start_datetime.second), (end_datetime, end_datetime.second), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__year=Extract("start_datetime", "year") ).count(), 2, ) self.assertEqual( DTModel.objects.filter( start_datetime__hour=Extract("start_datetime", "hour") ).count(), 2, ) self.assertEqual( DTModel.objects.filter( start_date__month=Extract("start_date", "month") ).count(), 2, ) self.assertEqual( DTModel.objects.filter( start_time__hour=Extract("start_time", "hour") ).count(), 2, ) def test_extract_none(self): self.create_model(None, None) for t in ( Extract("start_datetime", "year"), Extract("start_date", "year"), Extract("start_time", "hour"), ): with self.subTest(t): self.assertIsNone( DTModel.objects.annotate(extracted=t).first().extracted ) def test_extract_outerref_validation(self): inner_qs = DTModel.objects.filter(name=ExtractMonth(OuterRef("name"))) msg = ( "Extract input expression must be DateField, DateTimeField, " "TimeField, or DurationField." ) with self.assertRaisesMessage(ValueError, msg): DTModel.objects.annotate(related_name=Subquery(inner_qs.values("name")[:1])) @skipUnlessDBFeature("has_native_duration_field") def test_extract_duration(self): start_datetime = datetime.datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime.datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=Extract("duration", "second")).order_by( "start_datetime" ), [ (start_datetime, (end_datetime - start_datetime).seconds % 60), (end_datetime, (start_datetime - end_datetime).seconds % 60), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.annotate( duration_days=Extract("duration", "day"), ) .filter(duration_days__gt=200) .count(), 1, ) @skipIfDBFeature("has_native_duration_field") def test_extract_duration_without_native_duration_field(self): msg = "Extract requires native DurationField database support." with self.assertRaisesMessage(ValueError, msg): list(DTModel.objects.annotate(extracted=Extract("duration", "second"))) def test_extract_duration_unsupported_lookups(self): msg = "Cannot extract component '%s' from DurationField 'duration'." for lookup in ( "year", "iso_year", "month", "week", "week_day", "iso_week_day", "quarter", ): with self.subTest(lookup): with self.assertRaisesMessage(ValueError, msg % lookup): DTModel.objects.annotate(extracted=Extract("duration", lookup)) def test_extract_year_func(self): start_datetime = datetime.datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime.datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractYear("start_datetime")).order_by( "start_datetime" ), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractYear("start_date")).order_by( "start_datetime" ), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__year=ExtractYear("start_datetime") ).count(), 2, ) def test_extract_iso_year_func(self): start_datetime = datetime.datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime.datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=ExtractIsoYear("start_datetime") ).order_by("start_datetime"), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractIsoYear("start_date")).order_by( "start_datetime" ), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted), ) # Both dates are from the same week year. self.assertEqual( DTModel.objects.filter( start_datetime__iso_year=ExtractIsoYear("start_datetime") ).count(), 2, ) def test_extract_iso_year_func_boundaries(self): end_datetime = datetime.datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: end_datetime = timezone.make_aware(end_datetime) week_52_day_2014 = datetime.datetime(2014, 12, 27, 13, 0) # Sunday week_1_day_2014_2015 = datetime.datetime(2014, 12, 31, 13, 0) # Wednesday week_53_day_2015 = datetime.datetime(2015, 12, 31, 13, 0) # Thursday if settings.USE_TZ: week_1_day_2014_2015 = timezone.make_aware(week_1_day_2014_2015) week_52_day_2014 = timezone.make_aware(week_52_day_2014) week_53_day_2015 = timezone.make_aware(week_53_day_2015) days = [week_52_day_2014, week_1_day_2014_2015, week_53_day_2015] obj_1_iso_2014 = self.create_model(week_52_day_2014, end_datetime) obj_1_iso_2015 = self.create_model(week_1_day_2014_2015, end_datetime) obj_2_iso_2015 = self.create_model(week_53_day_2015, end_datetime) qs = ( DTModel.objects.filter(start_datetime__in=days) .annotate( extracted=ExtractIsoYear("start_datetime"), ) .order_by("start_datetime") ) self.assertQuerySetEqual( qs, [ (week_52_day_2014, 2014), (week_1_day_2014_2015, 2015), (week_53_day_2015, 2015), ], lambda m: (m.start_datetime, m.extracted), ) qs = DTModel.objects.filter( start_datetime__iso_year=2015, ).order_by("start_datetime") self.assertSequenceEqual(qs, [obj_1_iso_2015, obj_2_iso_2015]) qs = DTModel.objects.filter( start_datetime__iso_year__gt=2014, ).order_by("start_datetime") self.assertSequenceEqual(qs, [obj_1_iso_2015, obj_2_iso_2015]) qs = DTModel.objects.filter( start_datetime__iso_year__lte=2014, ).order_by("start_datetime") self.assertSequenceEqual(qs, [obj_1_iso_2014]) def test_extract_month_func(self): start_datetime = datetime.datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime.datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractMonth("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, start_datetime.month), (end_datetime, end_datetime.month), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractMonth("start_date")).order_by( "start_datetime" ), [ (start_datetime, start_datetime.month), (end_datetime, end_datetime.month), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__month=ExtractMonth("start_datetime") ).count(), 2, ) def test_extract_day_func(self): start_datetime = datetime.datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime.datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractDay("start_datetime")).order_by( "start_datetime" ), [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractDay("start_date")).order_by( "start_datetime" ), [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__day=ExtractDay("start_datetime") ).count(), 2, ) def test_extract_week_func(self): start_datetime = datetime.datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime.datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractWeek("start_datetime")).order_by( "start_datetime" ), [(start_datetime, 25), (end_datetime, 24)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractWeek("start_date")).order_by( "start_datetime" ), [(start_datetime, 25), (end_datetime, 24)], lambda m: (m.start_datetime, m.extracted), ) # both dates are from the same week. self.assertEqual( DTModel.objects.filter( start_datetime__week=ExtractWeek("start_datetime") ).count(), 2, ) def test_extract_quarter_func(self): start_datetime = datetime.datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime.datetime(2016, 8, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=ExtractQuarter("start_datetime") ).order_by("start_datetime"), [(start_datetime, 2), (end_datetime, 3)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractQuarter("start_date")).order_by( "start_datetime" ), [(start_datetime, 2), (end_datetime, 3)], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__quarter=ExtractQuarter("start_datetime") ).count(), 2, ) def test_extract_quarter_func_boundaries(self): end_datetime = datetime.datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: end_datetime = timezone.make_aware(end_datetime) last_quarter_2014 = datetime.datetime(2014, 12, 31, 13, 0) first_quarter_2015 = datetime.datetime(2015, 1, 1, 13, 0) if settings.USE_TZ: last_quarter_2014 = timezone.make_aware(last_quarter_2014) first_quarter_2015 = timezone.make_aware(first_quarter_2015) dates = [last_quarter_2014, first_quarter_2015] self.create_model(last_quarter_2014, end_datetime) self.create_model(first_quarter_2015, end_datetime) qs = ( DTModel.objects.filter(start_datetime__in=dates) .annotate( extracted=ExtractQuarter("start_datetime"), ) .order_by("start_datetime") ) self.assertQuerySetEqual( qs, [ (last_quarter_2014, 4), (first_quarter_2015, 1), ], lambda m: (m.start_datetime, m.extracted), ) def test_extract_week_func_boundaries(self): end_datetime = datetime.datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: end_datetime = timezone.make_aware(end_datetime) week_52_day_2014 = datetime.datetime(2014, 12, 27, 13, 0) # Sunday week_1_day_2014_2015 = datetime.datetime(2014, 12, 31, 13, 0) # Wednesday week_53_day_2015 = datetime.datetime(2015, 12, 31, 13, 0) # Thursday if settings.USE_TZ: week_1_day_2014_2015 = timezone.make_aware(week_1_day_2014_2015) week_52_day_2014 = timezone.make_aware(week_52_day_2014) week_53_day_2015 = timezone.make_aware(week_53_day_2015) days = [week_52_day_2014, week_1_day_2014_2015, week_53_day_2015] self.create_model(week_53_day_2015, end_datetime) self.create_model(week_52_day_2014, end_datetime) self.create_model(week_1_day_2014_2015, end_datetime) qs = ( DTModel.objects.filter(start_datetime__in=days) .annotate( extracted=ExtractWeek("start_datetime"), ) .order_by("start_datetime") ) self.assertQuerySetEqual( qs, [ (week_52_day_2014, 52), (week_1_day_2014_2015, 1), (week_53_day_2015, 53), ], lambda m: (m.start_datetime, m.extracted), ) def test_extract_weekday_func(self): start_datetime = datetime.datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime.datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=ExtractWeekDay("start_datetime") ).order_by("start_datetime"), [ (start_datetime, (start_datetime.isoweekday() % 7) + 1), (end_datetime, (end_datetime.isoweekday() % 7) + 1), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractWeekDay("start_date")).order_by( "start_datetime" ), [ (start_datetime, (start_datetime.isoweekday() % 7) + 1), (end_datetime, (end_datetime.isoweekday() % 7) + 1), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__week_day=ExtractWeekDay("start_datetime") ).count(), 2, ) def test_extract_iso_weekday_func(self): start_datetime = datetime.datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime.datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=ExtractIsoWeekDay("start_datetime"), ).order_by("start_datetime"), [ (start_datetime, start_datetime.isoweekday()), (end_datetime, end_datetime.isoweekday()), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=ExtractIsoWeekDay("start_date"), ).order_by("start_datetime"), [ (start_datetime, start_datetime.isoweekday()), (end_datetime, end_datetime.isoweekday()), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__week_day=ExtractWeekDay("start_datetime"), ).count(), 2, ) def test_extract_hour_func(self):
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/datetime/__init__.py
tests/db_functions/datetime/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/window/__init__.py
tests/db_functions/window/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/window/test_validation.py
tests/db_functions/window/test_validation.py
from django.db.models.functions import Lag, Lead, NthValue, Ntile from django.test import SimpleTestCase class ValidationTests(SimpleTestCase): def test_nth_negative_nth_value(self): msg = "NthValue requires a positive integer as for nth" with self.assertRaisesMessage(ValueError, msg): NthValue(expression="salary", nth=-1) def test_nth_null_expression(self): msg = "NthValue requires a non-null source expression" with self.assertRaisesMessage(ValueError, msg): NthValue(expression=None) def test_lag_negative_offset(self): msg = "Lag requires a positive integer for the offset" with self.assertRaisesMessage(ValueError, msg): Lag(expression="salary", offset=-1) def test_lead_negative_offset(self): msg = "Lead requires a positive integer for the offset" with self.assertRaisesMessage(ValueError, msg): Lead(expression="salary", offset=-1) def test_null_source_lead(self): msg = "Lead requires a non-null source expression" with self.assertRaisesMessage(ValueError, msg): Lead(expression=None) def test_null_source_lag(self): msg = "Lag requires a non-null source expression" with self.assertRaisesMessage(ValueError, msg): Lag(expression=None) def test_negative_num_buckets_ntile(self): msg = "num_buckets must be greater than 0" with self.assertRaisesMessage(ValueError, msg): Ntile(num_buckets=-1)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/comparison/test_cast.py
tests/db_functions/comparison/test_cast.py
import datetime import decimal import unittest from django.db import connection, models from django.db.models.functions import Cast from django.test import TestCase, ignore_warnings, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from ..models import Author, DTModel, Fan, FloatModel class CastTests(TestCase): @classmethod def setUpTestData(self): Author.objects.create(name="Bob", age=1, alias="1") def test_cast_from_value(self): numbers = Author.objects.annotate( cast_integer=Cast(models.Value("0"), models.IntegerField()) ) self.assertEqual(numbers.get().cast_integer, 0) def test_cast_from_field(self): numbers = Author.objects.annotate( cast_string=Cast("age", models.CharField(max_length=255)), ) self.assertEqual(numbers.get().cast_string, "1") def test_cast_to_char_field_without_max_length(self): numbers = Author.objects.annotate(cast_string=Cast("age", models.CharField())) self.assertEqual(numbers.get().cast_string, "1") # Silence "Truncated incorrect CHAR(1) value: 'Bob'". @ignore_warnings(module="django.db.backends.mysql.base") @skipUnlessDBFeature("supports_cast_with_precision") def test_cast_to_char_field_with_max_length(self): names = Author.objects.annotate( cast_string=Cast("name", models.CharField(max_length=1)) ) self.assertEqual(names.get().cast_string, "B") @skipUnlessDBFeature("supports_cast_with_precision") def test_cast_to_decimal_field(self): FloatModel.objects.create(f1=-1.934, f2=3.467) float_obj = FloatModel.objects.annotate( cast_f1_decimal=Cast( "f1", models.DecimalField(max_digits=8, decimal_places=2) ), cast_f2_decimal=Cast( "f2", models.DecimalField(max_digits=8, decimal_places=1) ), ).get() self.assertEqual(float_obj.cast_f1_decimal, decimal.Decimal("-1.93")) expected = "3.4" if connection.features.rounds_to_even else "3.5" self.assertEqual(float_obj.cast_f2_decimal, decimal.Decimal(expected)) author_obj = Author.objects.annotate( cast_alias_decimal=Cast( "alias", models.DecimalField(max_digits=8, decimal_places=2) ), ).get() self.assertEqual(author_obj.cast_alias_decimal, decimal.Decimal("1")) def test_cast_to_integer(self): for field_class in ( models.AutoField, models.BigAutoField, models.SmallAutoField, models.IntegerField, models.BigIntegerField, models.SmallIntegerField, models.PositiveBigIntegerField, models.PositiveIntegerField, models.PositiveSmallIntegerField, ): with self.subTest(field_class=field_class): numbers = Author.objects.annotate(cast_int=Cast("alias", field_class())) self.assertEqual(numbers.get().cast_int, 1) def test_cast_to_integer_foreign_key(self): numbers = Author.objects.annotate( cast_fk=Cast( models.Value("0"), models.ForeignKey(Author, on_delete=models.SET_NULL), ) ) self.assertEqual(numbers.get().cast_fk, 0) def test_cast_to_duration(self): duration = datetime.timedelta(days=1, seconds=2, microseconds=3) DTModel.objects.create(duration=duration) dtm = DTModel.objects.annotate( cast_duration=Cast("duration", models.DurationField()), cast_neg_duration=Cast(-duration, models.DurationField()), ).get() self.assertEqual(dtm.cast_duration, duration) self.assertEqual(dtm.cast_neg_duration, -duration) def test_cast_from_db_datetime_to_date(self): dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567) DTModel.objects.create(start_datetime=dt_value) dtm = DTModel.objects.annotate( start_datetime_as_date=Cast("start_datetime", models.DateField()) ).first() self.assertEqual(dtm.start_datetime_as_date, datetime.date(2018, 9, 28)) def test_cast_from_db_datetime_to_time(self): dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567) DTModel.objects.create(start_datetime=dt_value) dtm = DTModel.objects.annotate( start_datetime_as_time=Cast("start_datetime", models.TimeField()) ).first() rounded_ms = int( round(0.234567, connection.features.time_cast_precision) * 10**6 ) self.assertEqual( dtm.start_datetime_as_time, datetime.time(12, 42, 10, rounded_ms) ) def test_cast_from_db_date_to_datetime(self): dt_value = datetime.date(2018, 9, 28) DTModel.objects.create(start_date=dt_value) dtm = DTModel.objects.annotate( start_as_datetime=Cast("start_date", models.DateTimeField()) ).first() self.assertEqual( dtm.start_as_datetime, datetime.datetime(2018, 9, 28, 0, 0, 0, 0) ) def test_cast_from_db_datetime_to_date_group_by(self): author = Author.objects.create(name="John Smith", age=45) dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567) Fan.objects.create(name="Margaret", age=50, author=author, fan_since=dt_value) fans = ( Fan.objects.values("author") .annotate( fan_for_day=Cast("fan_since", models.DateField()), fans=models.Count("*"), ) .values() ) self.assertEqual(fans[0]["fan_for_day"], datetime.date(2018, 9, 28)) self.assertEqual(fans[0]["fans"], 1) def test_cast_from_python_to_date(self): today = datetime.date.today() dates = Author.objects.annotate(cast_date=Cast(today, models.DateField())) self.assertEqual(dates.get().cast_date, today) def test_cast_from_python_to_datetime(self): now = datetime.datetime.now() dates = Author.objects.annotate(cast_datetime=Cast(now, models.DateTimeField())) time_precision = datetime.timedelta( microseconds=10 ** (6 - connection.features.time_cast_precision) ) self.assertAlmostEqual(dates.get().cast_datetime, now, delta=time_precision) def test_cast_from_python(self): numbers = Author.objects.annotate( cast_float=Cast(decimal.Decimal(0.125), models.FloatField()) ) cast_float = numbers.get().cast_float self.assertIsInstance(cast_float, float) self.assertEqual(cast_float, 0.125) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL test") def test_expression_wrapped_with_parentheses_on_postgresql(self): """ The SQL for the Cast expression is wrapped with parentheses in case it's a complex expression. """ with CaptureQueriesContext(connection) as captured_queries: list( Author.objects.annotate( cast_float=Cast(models.Avg("age"), models.FloatField()), ) ) self.assertIn( '(AVG("db_functions_author"."age"))::double precision', captured_queries[0]["sql"], ) def test_cast_to_text_field(self): self.assertEqual( Author.objects.values_list( Cast("age", models.TextField()), flat=True ).get(), "1", )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/comparison/test_collate.py
tests/db_functions/comparison/test_collate.py
from django.db import connection from django.db.models import F, Value from django.db.models.functions import Collate from django.test import TestCase from ..models import Author class CollateTests(TestCase): @classmethod def setUpTestData(cls): cls.author1 = Author.objects.create(alias="a", name="Jones 1") cls.author2 = Author.objects.create(alias="A", name="Jones 2") def test_collate_filter_ci(self): collation = connection.features.test_collations.get("ci") if not collation: self.skipTest("This backend does not support case-insensitive collations.") qs = Author.objects.filter(alias=Collate(Value("a"), collation)) self.assertEqual(qs.count(), 2) def test_collate_order_by_cs(self): collation = connection.features.test_collations.get("cs") if not collation: self.skipTest("This backend does not support case-sensitive collations.") qs = Author.objects.order_by(Collate("alias", collation)) self.assertSequenceEqual(qs, [self.author2, self.author1]) def test_language_collation_order_by(self): collation = connection.features.test_collations.get("swedish_ci") if not collation: self.skipTest("This backend does not support language collations.") author3 = Author.objects.create(alias="O", name="Jones") author4 = Author.objects.create(alias="Ö", name="Jones") author5 = Author.objects.create(alias="P", name="Jones") qs = Author.objects.order_by(Collate(F("alias"), collation), "name") self.assertSequenceEqual( qs, [self.author1, self.author2, author3, author5, author4], ) def test_invalid_collation(self): tests = [ None, "", 'et-x-icu" OR ', '"schema"."collation"', ] msg = "Invalid collation name: %r." for value in tests: with self.subTest(value), self.assertRaisesMessage(ValueError, msg % value): Collate(F("alias"), value)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/comparison/test_least.py
tests/db_functions/comparison/test_least.py
from datetime import datetime, timedelta from decimal import Decimal from unittest import skipUnless from django.db import connection from django.db.models.expressions import RawSQL from django.db.models.functions import Coalesce, Least from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from django.utils import timezone from ..models import Article, Author, DecimalModel, Fan class LeastTests(TestCase): def test_basic(self): now = timezone.now() before = now - timedelta(hours=1) Article.objects.create( title="Testing with Django", written=before, published=now ) articles = Article.objects.annotate(first_updated=Least("written", "published")) self.assertEqual(articles.first().first_updated, before) @skipUnlessDBFeature("greatest_least_ignores_nulls") def test_ignores_null(self): now = timezone.now() Article.objects.create(title="Testing with Django", written=now) articles = Article.objects.annotate( first_updated=Least("written", "published"), ) self.assertEqual(articles.first().first_updated, now) @skipIfDBFeature("greatest_least_ignores_nulls") def test_propagates_null(self): Article.objects.create(title="Testing with Django", written=timezone.now()) articles = Article.objects.annotate(first_updated=Least("written", "published")) self.assertIsNone(articles.first().first_updated) def test_coalesce_workaround(self): future = datetime(2100, 1, 1) now = timezone.now() Article.objects.create(title="Testing with Django", written=now) articles = Article.objects.annotate( last_updated=Least( Coalesce("written", future), Coalesce("published", future), ), ) self.assertEqual(articles.first().last_updated, now) @skipUnless(connection.vendor == "mysql", "MySQL-specific workaround") def test_coalesce_workaround_mysql(self): future = datetime(2100, 1, 1) now = timezone.now() Article.objects.create(title="Testing with Django", written=now) future_sql = RawSQL("cast(%s as datetime)", (future,)) articles = Article.objects.annotate( last_updated=Least( Coalesce("written", future_sql), Coalesce("published", future_sql), ), ) self.assertEqual(articles.first().last_updated, now) def test_all_null(self): Article.objects.create(title="Testing with Django", written=timezone.now()) articles = Article.objects.annotate(first_updated=Least("published", "updated")) self.assertIsNone(articles.first().first_updated) def test_one_expressions(self): with self.assertRaisesMessage( ValueError, "Least must take at least two expressions" ): Least("written") def test_related_field(self): author = Author.objects.create(name="John Smith", age=45) Fan.objects.create(name="Margaret", age=50, author=author) authors = Author.objects.annotate(lowest_age=Least("age", "fans__age")) self.assertEqual(authors.first().lowest_age, 45) def test_update(self): author = Author.objects.create(name="James Smith", goes_by="Jim") Author.objects.update(alias=Least("name", "goes_by")) author.refresh_from_db() self.assertEqual(author.alias, "James Smith") def test_decimal_filter(self): obj = DecimalModel.objects.create(n1=Decimal("1.1"), n2=Decimal("1.2")) self.assertCountEqual( DecimalModel.objects.annotate( least=Least("n1", "n2"), ).filter(least=Decimal("1.1")), [obj], )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/comparison/test_coalesce.py
tests/db_functions/comparison/test_coalesce.py
from django.db.models import Subquery, TextField from django.db.models.functions import Coalesce, Lower from django.test import TestCase from django.utils import timezone from ..models import Article, Author lorem_ipsum = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" class CoalesceTests(TestCase): def test_basic(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.annotate(display_name=Coalesce("alias", "name")) self.assertQuerySetEqual( authors.order_by("name"), ["smithj", "Rhonda"], lambda a: a.display_name ) def test_gt_two_expressions(self): with self.assertRaisesMessage( ValueError, "Coalesce must take at least two expressions" ): Author.objects.annotate(display_name=Coalesce("alias")) def test_mixed_values(self): a1 = Author.objects.create(name="John Smith", alias="smithj") a2 = Author.objects.create(name="Rhonda") ar1 = Article.objects.create( title="How to Django", text=lorem_ipsum, written=timezone.now(), ) ar1.authors.add(a1) ar1.authors.add(a2) # mixed Text and Char article = Article.objects.annotate( headline=Coalesce("summary", "text", output_field=TextField()), ) self.assertQuerySetEqual( article.order_by("title"), [lorem_ipsum], lambda a: a.headline ) # mixed Text and Char wrapped article = Article.objects.annotate( headline=Coalesce( Lower("summary"), Lower("text"), output_field=TextField() ), ) self.assertQuerySetEqual( article.order_by("title"), [lorem_ipsum.lower()], lambda a: a.headline ) def test_ordering(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.order_by(Coalesce("alias", "name")) self.assertQuerySetEqual(authors, ["Rhonda", "John Smith"], lambda a: a.name) authors = Author.objects.order_by(Coalesce("alias", "name").asc()) self.assertQuerySetEqual(authors, ["Rhonda", "John Smith"], lambda a: a.name) authors = Author.objects.order_by(Coalesce("alias", "name").desc()) self.assertQuerySetEqual(authors, ["John Smith", "Rhonda"], lambda a: a.name) def test_empty_queryset(self): Author.objects.create(name="John Smith") queryset = Author.objects.values("id") tests = [ (queryset.none(), "QuerySet.none()"), (queryset.filter(id=0), "QuerySet.filter(id=0)"), (Subquery(queryset.none()), "Subquery(QuerySet.none())"), (Subquery(queryset.filter(id=0)), "Subquery(Queryset.filter(id=0)"), ] for empty_query, description in tests: with self.subTest(description), self.assertNumQueries(1): qs = Author.objects.annotate(annotation=Coalesce(empty_query, 42)) self.assertEqual(qs.first().annotation, 42)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/comparison/test_nullif.py
tests/db_functions/comparison/test_nullif.py
from unittest import skipUnless from django.db import connection from django.db.models import Value from django.db.models.functions import NullIf from django.test import TestCase from ..models import Author class NullIfTests(TestCase): @classmethod def setUpTestData(cls): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda", alias="Rhonda") def test_basic(self): authors = Author.objects.annotate(nullif=NullIf("alias", "name")).values_list( "nullif" ) self.assertCountEqual( authors, [ ("smithj",), ( ( "" if connection.features.interprets_empty_strings_as_nulls else None ), ), ], ) def test_null_argument(self): authors = Author.objects.annotate( nullif=NullIf("name", Value(None)) ).values_list("nullif") self.assertCountEqual(authors, [("John Smith",), ("Rhonda",)]) def test_too_few_args(self): msg = "'NullIf' takes exactly 2 arguments (1 given)" with self.assertRaisesMessage(TypeError, msg): NullIf("name") @skipUnless(connection.vendor == "oracle", "Oracle specific test for NULL-literal") def test_null_literal(self): msg = "Oracle does not allow Value(None) for expression1." with self.assertRaisesMessage(ValueError, msg): list( Author.objects.annotate(nullif=NullIf(Value(None), "name")).values_list( "nullif" ) )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/comparison/__init__.py
tests/db_functions/comparison/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/comparison/test_greatest.py
tests/db_functions/comparison/test_greatest.py
from datetime import datetime, timedelta from decimal import Decimal from unittest import skipUnless from django.db import connection from django.db.models.expressions import RawSQL from django.db.models.functions import Coalesce, Greatest from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from django.utils import timezone from ..models import Article, Author, DecimalModel, Fan class GreatestTests(TestCase): def test_basic(self): now = timezone.now() before = now - timedelta(hours=1) Article.objects.create( title="Testing with Django", written=before, published=now ) articles = Article.objects.annotate( last_updated=Greatest("written", "published") ) self.assertEqual(articles.first().last_updated, now) @skipUnlessDBFeature("greatest_least_ignores_nulls") def test_ignores_null(self): now = timezone.now() Article.objects.create(title="Testing with Django", written=now) articles = Article.objects.annotate( last_updated=Greatest("written", "published") ) self.assertEqual(articles.first().last_updated, now) @skipIfDBFeature("greatest_least_ignores_nulls") def test_propagates_null(self): Article.objects.create(title="Testing with Django", written=timezone.now()) articles = Article.objects.annotate( last_updated=Greatest("written", "published") ) self.assertIsNone(articles.first().last_updated) def test_coalesce_workaround(self): past = datetime(1900, 1, 1) now = timezone.now() Article.objects.create(title="Testing with Django", written=now) articles = Article.objects.annotate( last_updated=Greatest( Coalesce("written", past), Coalesce("published", past), ), ) self.assertEqual(articles.first().last_updated, now) @skipUnless(connection.vendor == "mysql", "MySQL-specific workaround") def test_coalesce_workaround_mysql(self): past = datetime(1900, 1, 1) now = timezone.now() Article.objects.create(title="Testing with Django", written=now) past_sql = RawSQL("cast(%s as datetime)", (past,)) articles = Article.objects.annotate( last_updated=Greatest( Coalesce("written", past_sql), Coalesce("published", past_sql), ), ) self.assertEqual(articles.first().last_updated, now) def test_all_null(self): Article.objects.create(title="Testing with Django", written=timezone.now()) articles = Article.objects.annotate( last_updated=Greatest("published", "updated") ) self.assertIsNone(articles.first().last_updated) def test_one_expressions(self): with self.assertRaisesMessage( ValueError, "Greatest must take at least two expressions" ): Greatest("written") def test_related_field(self): author = Author.objects.create(name="John Smith", age=45) Fan.objects.create(name="Margaret", age=50, author=author) authors = Author.objects.annotate(highest_age=Greatest("age", "fans__age")) self.assertEqual(authors.first().highest_age, 50) def test_update(self): author = Author.objects.create(name="James Smith", goes_by="Jim") Author.objects.update(alias=Greatest("name", "goes_by")) author.refresh_from_db() self.assertEqual(author.alias, "Jim") def test_decimal_filter(self): obj = DecimalModel.objects.create(n1=Decimal("1.1"), n2=Decimal("1.2")) self.assertCountEqual( DecimalModel.objects.annotate( greatest=Greatest("n1", "n2"), ).filter(greatest=Decimal("1.2")), [obj], )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_mod.py
tests/db_functions/math/test_mod.py
import math from decimal import Decimal from django.db.models.functions import Mod from django.test import TestCase from ..models import DecimalModel, FloatModel, IntegerModel class ModTests(TestCase): def test_null(self): IntegerModel.objects.create(big=100) obj = IntegerModel.objects.annotate( null_mod_small=Mod("small", "normal"), null_mod_normal=Mod("normal", "big"), ).first() self.assertIsNone(obj.null_mod_small) self.assertIsNone(obj.null_mod_normal) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-9.9"), n2=Decimal("4.6")) obj = DecimalModel.objects.annotate(n_mod=Mod("n1", "n2")).first() self.assertIsInstance(obj.n_mod, Decimal) self.assertAlmostEqual(obj.n_mod, Decimal(math.fmod(obj.n1, obj.n2))) def test_float(self): FloatModel.objects.create(f1=-25, f2=0.33) obj = FloatModel.objects.annotate(f_mod=Mod("f1", "f2")).first() self.assertIsInstance(obj.f_mod, float) self.assertAlmostEqual(obj.f_mod, math.fmod(obj.f1, obj.f2)) def test_integer(self): IntegerModel.objects.create(small=20, normal=15, big=1) obj = IntegerModel.objects.annotate( small_mod=Mod("small", "normal"), normal_mod=Mod("normal", "big"), big_mod=Mod("big", "small"), ).first() self.assertIsInstance(obj.small_mod, float) self.assertIsInstance(obj.normal_mod, float) self.assertIsInstance(obj.big_mod, float) self.assertEqual(obj.small_mod, math.fmod(obj.small, obj.normal)) self.assertEqual(obj.normal_mod, math.fmod(obj.normal, obj.big)) self.assertEqual(obj.big_mod, math.fmod(obj.big, obj.small))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_ln.py
tests/db_functions/math/test_ln.py
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Ln from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class LnTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_ln=Ln("normal")).first() self.assertIsNone(obj.null_ln) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate(n1_ln=Ln("n1"), n2_ln=Ln("n2")).first() self.assertIsInstance(obj.n1_ln, Decimal) self.assertIsInstance(obj.n2_ln, Decimal) self.assertAlmostEqual(obj.n1_ln, Decimal(math.log(obj.n1))) self.assertAlmostEqual(obj.n2_ln, Decimal(math.log(obj.n2))) def test_float(self): FloatModel.objects.create(f1=27.5, f2=0.33) obj = FloatModel.objects.annotate(f1_ln=Ln("f1"), f2_ln=Ln("f2")).first() self.assertIsInstance(obj.f1_ln, float) self.assertIsInstance(obj.f2_ln, float) self.assertAlmostEqual(obj.f1_ln, math.log(obj.f1)) self.assertAlmostEqual(obj.f2_ln, math.log(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=20, normal=15, big=1) obj = IntegerModel.objects.annotate( small_ln=Ln("small"), normal_ln=Ln("normal"), big_ln=Ln("big"), ).first() self.assertIsInstance(obj.small_ln, float) self.assertIsInstance(obj.normal_ln, float) self.assertIsInstance(obj.big_ln, float) self.assertAlmostEqual(obj.small_ln, math.log(obj.small)) self.assertAlmostEqual(obj.normal_ln, math.log(obj.normal)) self.assertAlmostEqual(obj.big_ln, math.log(obj.big)) def test_transform(self): with register_lookup(DecimalField, Ln): DecimalModel.objects.create(n1=Decimal("12.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("1.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__ln__gt=0).get() self.assertEqual(obj.n1, Decimal("12.0"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_sin.py
tests/db_functions/math/test_sin.py
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Sin from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class SinTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_sin=Sin("normal")).first() self.assertIsNone(obj.null_sin) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate(n1_sin=Sin("n1"), n2_sin=Sin("n2")).first() self.assertIsInstance(obj.n1_sin, Decimal) self.assertIsInstance(obj.n2_sin, Decimal) self.assertAlmostEqual(obj.n1_sin, Decimal(math.sin(obj.n1))) self.assertAlmostEqual(obj.n2_sin, Decimal(math.sin(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate(f1_sin=Sin("f1"), f2_sin=Sin("f2")).first() self.assertIsInstance(obj.f1_sin, float) self.assertIsInstance(obj.f2_sin, float) self.assertAlmostEqual(obj.f1_sin, math.sin(obj.f1)) self.assertAlmostEqual(obj.f2_sin, math.sin(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_sin=Sin("small"), normal_sin=Sin("normal"), big_sin=Sin("big"), ).first() self.assertIsInstance(obj.small_sin, float) self.assertIsInstance(obj.normal_sin, float) self.assertIsInstance(obj.big_sin, float) self.assertAlmostEqual(obj.small_sin, math.sin(obj.small)) self.assertAlmostEqual(obj.normal_sin, math.sin(obj.normal)) self.assertAlmostEqual(obj.big_sin, math.sin(obj.big)) def test_transform(self): with register_lookup(DecimalField, Sin): DecimalModel.objects.create(n1=Decimal("5.4"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("0.1"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__sin__lt=0).get() self.assertEqual(obj.n1, Decimal("5.4"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_exp.py
tests/db_functions/math/test_exp.py
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Exp from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class ExpTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_exp=Exp("normal")).first() self.assertIsNone(obj.null_exp) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate(n1_exp=Exp("n1"), n2_exp=Exp("n2")).first() self.assertIsInstance(obj.n1_exp, Decimal) self.assertIsInstance(obj.n2_exp, Decimal) self.assertAlmostEqual(obj.n1_exp, Decimal(math.exp(obj.n1))) self.assertAlmostEqual(obj.n2_exp, Decimal(math.exp(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate(f1_exp=Exp("f1"), f2_exp=Exp("f2")).first() self.assertIsInstance(obj.f1_exp, float) self.assertIsInstance(obj.f2_exp, float) self.assertAlmostEqual(obj.f1_exp, math.exp(obj.f1)) self.assertAlmostEqual(obj.f2_exp, math.exp(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_exp=Exp("small"), normal_exp=Exp("normal"), big_exp=Exp("big"), ).first() self.assertIsInstance(obj.small_exp, float) self.assertIsInstance(obj.normal_exp, float) self.assertIsInstance(obj.big_exp, float) self.assertAlmostEqual(obj.small_exp, math.exp(obj.small)) self.assertAlmostEqual(obj.normal_exp, math.exp(obj.normal)) self.assertAlmostEqual(obj.big_exp, math.exp(obj.big)) def test_transform(self): with register_lookup(DecimalField, Exp): DecimalModel.objects.create(n1=Decimal("12.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-1.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__exp__gt=10).get() self.assertEqual(obj.n1, Decimal("12.0"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_cos.py
tests/db_functions/math/test_cos.py
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Cos from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class CosTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_cos=Cos("normal")).first() self.assertIsNone(obj.null_cos) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate(n1_cos=Cos("n1"), n2_cos=Cos("n2")).first() self.assertIsInstance(obj.n1_cos, Decimal) self.assertIsInstance(obj.n2_cos, Decimal) self.assertAlmostEqual(obj.n1_cos, Decimal(math.cos(obj.n1))) self.assertAlmostEqual(obj.n2_cos, Decimal(math.cos(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate(f1_cos=Cos("f1"), f2_cos=Cos("f2")).first() self.assertIsInstance(obj.f1_cos, float) self.assertIsInstance(obj.f2_cos, float) self.assertAlmostEqual(obj.f1_cos, math.cos(obj.f1)) self.assertAlmostEqual(obj.f2_cos, math.cos(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_cos=Cos("small"), normal_cos=Cos("normal"), big_cos=Cos("big"), ).first() self.assertIsInstance(obj.small_cos, float) self.assertIsInstance(obj.normal_cos, float) self.assertIsInstance(obj.big_cos, float) self.assertAlmostEqual(obj.small_cos, math.cos(obj.small)) self.assertAlmostEqual(obj.normal_cos, math.cos(obj.normal)) self.assertAlmostEqual(obj.big_cos, math.cos(obj.big)) def test_transform(self): with register_lookup(DecimalField, Cos): DecimalModel.objects.create(n1=Decimal("-8.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("3.14"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__cos__gt=-0.2).get() self.assertEqual(obj.n1, Decimal("-8.0"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_random.py
tests/db_functions/math/test_random.py
from django.db.models.functions import Random from django.test import TestCase from ..models import FloatModel class RandomTests(TestCase): def test(self): FloatModel.objects.create() obj = FloatModel.objects.annotate(random=Random()).first() self.assertIsInstance(obj.random, float) self.assertGreaterEqual(obj.random, 0) self.assertLess(obj.random, 1)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_sqrt.py
tests/db_functions/math/test_sqrt.py
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Sqrt from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class SqrtTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_sqrt=Sqrt("normal")).first() self.assertIsNone(obj.null_sqrt) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_sqrt=Sqrt("n1"), n2_sqrt=Sqrt("n2") ).first() self.assertIsInstance(obj.n1_sqrt, Decimal) self.assertIsInstance(obj.n2_sqrt, Decimal) self.assertAlmostEqual(obj.n1_sqrt, Decimal(math.sqrt(obj.n1))) self.assertAlmostEqual(obj.n2_sqrt, Decimal(math.sqrt(obj.n2))) def test_float(self): FloatModel.objects.create(f1=27.5, f2=0.33) obj = FloatModel.objects.annotate( f1_sqrt=Sqrt("f1"), f2_sqrt=Sqrt("f2") ).first() self.assertIsInstance(obj.f1_sqrt, float) self.assertIsInstance(obj.f2_sqrt, float) self.assertAlmostEqual(obj.f1_sqrt, math.sqrt(obj.f1)) self.assertAlmostEqual(obj.f2_sqrt, math.sqrt(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=20, normal=15, big=1) obj = IntegerModel.objects.annotate( small_sqrt=Sqrt("small"), normal_sqrt=Sqrt("normal"), big_sqrt=Sqrt("big"), ).first() self.assertIsInstance(obj.small_sqrt, float) self.assertIsInstance(obj.normal_sqrt, float) self.assertIsInstance(obj.big_sqrt, float) self.assertAlmostEqual(obj.small_sqrt, math.sqrt(obj.small)) self.assertAlmostEqual(obj.normal_sqrt, math.sqrt(obj.normal)) self.assertAlmostEqual(obj.big_sqrt, math.sqrt(obj.big)) def test_transform(self): with register_lookup(DecimalField, Sqrt): DecimalModel.objects.create(n1=Decimal("6.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("1.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__sqrt__gt=2).get() self.assertEqual(obj.n1, Decimal("6.0"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_degrees.py
tests/db_functions/math/test_degrees.py
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Degrees from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class DegreesTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_degrees=Degrees("normal")).first() self.assertIsNone(obj.null_degrees) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_degrees=Degrees("n1"), n2_degrees=Degrees("n2") ).first() self.assertIsInstance(obj.n1_degrees, Decimal) self.assertIsInstance(obj.n2_degrees, Decimal) self.assertAlmostEqual(obj.n1_degrees, Decimal(math.degrees(obj.n1))) self.assertAlmostEqual(obj.n2_degrees, Decimal(math.degrees(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate( f1_degrees=Degrees("f1"), f2_degrees=Degrees("f2") ).first() self.assertIsInstance(obj.f1_degrees, float) self.assertIsInstance(obj.f2_degrees, float) self.assertAlmostEqual(obj.f1_degrees, math.degrees(obj.f1)) self.assertAlmostEqual(obj.f2_degrees, math.degrees(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_degrees=Degrees("small"), normal_degrees=Degrees("normal"), big_degrees=Degrees("big"), ).first() self.assertIsInstance(obj.small_degrees, float) self.assertIsInstance(obj.normal_degrees, float) self.assertIsInstance(obj.big_degrees, float) self.assertAlmostEqual(obj.small_degrees, math.degrees(obj.small)) self.assertAlmostEqual(obj.normal_degrees, math.degrees(obj.normal)) self.assertAlmostEqual(obj.big_degrees, math.degrees(obj.big)) def test_transform(self): with register_lookup(DecimalField, Degrees): DecimalModel.objects.create(n1=Decimal("5.4"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-30"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__degrees__gt=0).get() self.assertEqual(obj.n1, Decimal("5.4"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_round.py
tests/db_functions/math/test_round.py
import unittest from decimal import Decimal from django.db import connection from django.db.models import DecimalField from django.db.models.functions import Pi, Round from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class RoundTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_round=Round("normal")).first() self.assertIsNone(obj.null_round) def test_null_with_precision(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_round=Round("normal", 5)).first() self.assertIsNone(obj.null_round) def test_null_with_negative_precision(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_round=Round("normal", -1)).first() self.assertIsNone(obj.null_round) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_round=Round("n1"), n2_round=Round("n2") ).first() self.assertIsInstance(obj.n1_round, Decimal) self.assertIsInstance(obj.n2_round, Decimal) self.assertAlmostEqual(obj.n1_round, obj.n1, places=0) self.assertAlmostEqual(obj.n2_round, obj.n2, places=0) def test_decimal_with_precision(self): DecimalModel.objects.create(n1=Decimal("-5.75"), n2=Pi()) obj = DecimalModel.objects.annotate( n1_round=Round("n1", 1), n2_round=Round("n2", 5), ).first() self.assertIsInstance(obj.n1_round, Decimal) self.assertIsInstance(obj.n2_round, Decimal) self.assertAlmostEqual(obj.n1_round, obj.n1, places=1) self.assertAlmostEqual(obj.n2_round, obj.n2, places=5) def test_decimal_with_negative_precision(self): DecimalModel.objects.create(n1=Decimal("365.25")) obj = DecimalModel.objects.annotate(n1_round=Round("n1", -1)).first() self.assertIsInstance(obj.n1_round, Decimal) self.assertEqual(obj.n1_round, 370) def test_float(self): FloatModel.objects.create(f1=-27.55, f2=0.55) obj = FloatModel.objects.annotate( f1_round=Round("f1"), f2_round=Round("f2") ).first() self.assertIsInstance(obj.f1_round, float) self.assertIsInstance(obj.f2_round, float) self.assertAlmostEqual(obj.f1_round, obj.f1, places=0) self.assertAlmostEqual(obj.f2_round, obj.f2, places=0) def test_float_with_precision(self): FloatModel.objects.create(f1=-5.75, f2=Pi()) obj = FloatModel.objects.annotate( f1_round=Round("f1", 1), f2_round=Round("f2", 5), ).first() self.assertIsInstance(obj.f1_round, float) self.assertIsInstance(obj.f2_round, float) self.assertAlmostEqual(obj.f1_round, obj.f1, places=1) self.assertAlmostEqual(obj.f2_round, obj.f2, places=5) def test_float_with_negative_precision(self): FloatModel.objects.create(f1=365.25) obj = FloatModel.objects.annotate(f1_round=Round("f1", -1)).first() self.assertIsInstance(obj.f1_round, float) self.assertEqual(obj.f1_round, 370) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_round=Round("small"), normal_round=Round("normal"), big_round=Round("big"), ).first() self.assertIsInstance(obj.small_round, int) self.assertIsInstance(obj.normal_round, int) self.assertIsInstance(obj.big_round, int) self.assertAlmostEqual(obj.small_round, obj.small, places=0) self.assertAlmostEqual(obj.normal_round, obj.normal, places=0) self.assertAlmostEqual(obj.big_round, obj.big, places=0) def test_integer_with_precision(self): IntegerModel.objects.create(small=-5, normal=3, big=-100) obj = IntegerModel.objects.annotate( small_round=Round("small", 1), normal_round=Round("normal", 5), big_round=Round("big", 2), ).first() self.assertIsInstance(obj.small_round, int) self.assertIsInstance(obj.normal_round, int) self.assertIsInstance(obj.big_round, int) self.assertAlmostEqual(obj.small_round, obj.small, places=1) self.assertAlmostEqual(obj.normal_round, obj.normal, places=5) self.assertAlmostEqual(obj.big_round, obj.big, places=2) def test_integer_with_negative_precision(self): IntegerModel.objects.create(normal=365) obj = IntegerModel.objects.annotate(normal_round=Round("normal", -1)).first() self.assertIsInstance(obj.normal_round, int) expected = 360 if connection.features.rounds_to_even else 370 self.assertEqual(obj.normal_round, expected) def test_transform(self): with register_lookup(DecimalField, Round): DecimalModel.objects.create(n1=Decimal("2.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-1.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__round__gt=0).get() self.assertEqual(obj.n1, Decimal("2.0")) @unittest.skipUnless( connection.vendor == "sqlite", "SQLite doesn't support negative precision.", ) def test_unsupported_negative_precision(self): FloatModel.objects.create(f1=123.45) msg = "SQLite does not support negative precision." with self.assertRaisesMessage(ValueError, msg): FloatModel.objects.annotate(value=Round("f1", -1)).first()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_cot.py
tests/db_functions/math/test_cot.py
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Cot from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class CotTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_cot=Cot("normal")).first() self.assertIsNone(obj.null_cot) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate(n1_cot=Cot("n1"), n2_cot=Cot("n2")).first() self.assertIsInstance(obj.n1_cot, Decimal) self.assertIsInstance(obj.n2_cot, Decimal) self.assertAlmostEqual(obj.n1_cot, Decimal(1 / math.tan(obj.n1))) self.assertAlmostEqual(obj.n2_cot, Decimal(1 / math.tan(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate(f1_cot=Cot("f1"), f2_cot=Cot("f2")).first() self.assertIsInstance(obj.f1_cot, float) self.assertIsInstance(obj.f2_cot, float) self.assertAlmostEqual(obj.f1_cot, 1 / math.tan(obj.f1)) self.assertAlmostEqual(obj.f2_cot, 1 / math.tan(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-5, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_cot=Cot("small"), normal_cot=Cot("normal"), big_cot=Cot("big"), ).first() self.assertIsInstance(obj.small_cot, float) self.assertIsInstance(obj.normal_cot, float) self.assertIsInstance(obj.big_cot, float) self.assertAlmostEqual(obj.small_cot, 1 / math.tan(obj.small)) self.assertAlmostEqual(obj.normal_cot, 1 / math.tan(obj.normal)) self.assertAlmostEqual(obj.big_cot, 1 / math.tan(obj.big)) def test_transform(self): with register_lookup(DecimalField, Cot): DecimalModel.objects.create(n1=Decimal("12.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("1.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__cot__gt=0).get() self.assertEqual(obj.n1, Decimal("1.0"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_acos.py
tests/db_functions/math/test_acos.py
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import ACos from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class ACosTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_acos=ACos("normal")).first() self.assertIsNone(obj.null_acos) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-0.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_acos=ACos("n1"), n2_acos=ACos("n2") ).first() self.assertIsInstance(obj.n1_acos, Decimal) self.assertIsInstance(obj.n2_acos, Decimal) self.assertAlmostEqual(obj.n1_acos, Decimal(math.acos(obj.n1))) self.assertAlmostEqual(obj.n2_acos, Decimal(math.acos(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-0.5, f2=0.33) obj = FloatModel.objects.annotate( f1_acos=ACos("f1"), f2_acos=ACos("f2") ).first() self.assertIsInstance(obj.f1_acos, float) self.assertIsInstance(obj.f2_acos, float) self.assertAlmostEqual(obj.f1_acos, math.acos(obj.f1)) self.assertAlmostEqual(obj.f2_acos, math.acos(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=0, normal=1, big=-1) obj = IntegerModel.objects.annotate( small_acos=ACos("small"), normal_acos=ACos("normal"), big_acos=ACos("big"), ).first() self.assertIsInstance(obj.small_acos, float) self.assertIsInstance(obj.normal_acos, float) self.assertIsInstance(obj.big_acos, float) self.assertAlmostEqual(obj.small_acos, math.acos(obj.small)) self.assertAlmostEqual(obj.normal_acos, math.acos(obj.normal)) self.assertAlmostEqual(obj.big_acos, math.acos(obj.big)) def test_transform(self): with register_lookup(DecimalField, ACos): DecimalModel.objects.create(n1=Decimal("0.5"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-0.9"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__acos__lt=2).get() self.assertEqual(obj.n1, Decimal("0.5"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_log.py
tests/db_functions/math/test_log.py
import math from decimal import Decimal from django.db.models.functions import Log from django.test import TestCase from ..models import DecimalModel, FloatModel, IntegerModel class LogTests(TestCase): def test_null(self): IntegerModel.objects.create(big=100) obj = IntegerModel.objects.annotate( null_log_small=Log("small", "normal"), null_log_normal=Log("normal", "big"), null_log_big=Log("big", "normal"), ).first() self.assertIsNone(obj.null_log_small) self.assertIsNone(obj.null_log_normal) self.assertIsNone(obj.null_log_big) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("12.9"), n2=Decimal("3.6")) obj = DecimalModel.objects.annotate(n_log=Log("n1", "n2")).first() self.assertIsInstance(obj.n_log, Decimal) self.assertAlmostEqual(obj.n_log, Decimal(math.log(obj.n2, obj.n1))) def test_float(self): FloatModel.objects.create(f1=2.0, f2=4.0) obj = FloatModel.objects.annotate(f_log=Log("f1", "f2")).first() self.assertIsInstance(obj.f_log, float) self.assertAlmostEqual(obj.f_log, math.log(obj.f2, obj.f1)) def test_integer(self): IntegerModel.objects.create(small=4, normal=8, big=2) obj = IntegerModel.objects.annotate( small_log=Log("small", "big"), normal_log=Log("normal", "big"), big_log=Log("big", "big"), ).first() self.assertIsInstance(obj.small_log, float) self.assertIsInstance(obj.normal_log, float) self.assertIsInstance(obj.big_log, float) self.assertAlmostEqual(obj.small_log, math.log(obj.big, obj.small)) self.assertAlmostEqual(obj.normal_log, math.log(obj.big, obj.normal)) self.assertAlmostEqual(obj.big_log, math.log(obj.big, obj.big))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_floor.py
tests/db_functions/math/test_floor.py
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Floor from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class FloorTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_floor=Floor("normal")).first() self.assertIsNone(obj.null_floor) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_floor=Floor("n1"), n2_floor=Floor("n2") ).first() self.assertIsInstance(obj.n1_floor, Decimal) self.assertIsInstance(obj.n2_floor, Decimal) self.assertEqual(obj.n1_floor, Decimal(math.floor(obj.n1))) self.assertEqual(obj.n2_floor, Decimal(math.floor(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate( f1_floor=Floor("f1"), f2_floor=Floor("f2") ).first() self.assertIsInstance(obj.f1_floor, float) self.assertIsInstance(obj.f2_floor, float) self.assertEqual(obj.f1_floor, math.floor(obj.f1)) self.assertEqual(obj.f2_floor, math.floor(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_floor=Floor("small"), normal_floor=Floor("normal"), big_floor=Floor("big"), ).first() self.assertIsInstance(obj.small_floor, int) self.assertIsInstance(obj.normal_floor, int) self.assertIsInstance(obj.big_floor, int) self.assertEqual(obj.small_floor, math.floor(obj.small)) self.assertEqual(obj.normal_floor, math.floor(obj.normal)) self.assertEqual(obj.big_floor, math.floor(obj.big)) def test_transform(self): with register_lookup(DecimalField, Floor): DecimalModel.objects.create(n1=Decimal("5.4"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("3.4"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__floor__gt=4).get() self.assertEqual(obj.n1, Decimal("5.4"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_tan.py
tests/db_functions/math/test_tan.py
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Tan from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class TanTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_tan=Tan("normal")).first() self.assertIsNone(obj.null_tan) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate(n1_tan=Tan("n1"), n2_tan=Tan("n2")).first() self.assertIsInstance(obj.n1_tan, Decimal) self.assertIsInstance(obj.n2_tan, Decimal) self.assertAlmostEqual(obj.n1_tan, Decimal(math.tan(obj.n1))) self.assertAlmostEqual(obj.n2_tan, Decimal(math.tan(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate(f1_tan=Tan("f1"), f2_tan=Tan("f2")).first() self.assertIsInstance(obj.f1_tan, float) self.assertIsInstance(obj.f2_tan, float) self.assertAlmostEqual(obj.f1_tan, math.tan(obj.f1)) self.assertAlmostEqual(obj.f2_tan, math.tan(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_tan=Tan("small"), normal_tan=Tan("normal"), big_tan=Tan("big"), ).first() self.assertIsInstance(obj.small_tan, float) self.assertIsInstance(obj.normal_tan, float) self.assertIsInstance(obj.big_tan, float) self.assertAlmostEqual(obj.small_tan, math.tan(obj.small)) self.assertAlmostEqual(obj.normal_tan, math.tan(obj.normal)) self.assertAlmostEqual(obj.big_tan, math.tan(obj.big)) def test_transform(self): with register_lookup(DecimalField, Tan): DecimalModel.objects.create(n1=Decimal("0.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("12.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__tan__lt=0).get() self.assertEqual(obj.n1, Decimal("12.0"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_power.py
tests/db_functions/math/test_power.py
from decimal import Decimal from django.db.models.functions import Power from django.test import TestCase from ..models import DecimalModel, FloatModel, IntegerModel class PowerTests(TestCase): def test_null(self): IntegerModel.objects.create(big=100) obj = IntegerModel.objects.annotate( null_power_small=Power("small", "normal"), null_power_normal=Power("normal", "big"), null_power_big=Power("big", "normal"), ).first() self.assertIsNone(obj.null_power_small) self.assertIsNone(obj.null_power_normal) self.assertIsNone(obj.null_power_big) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("1.0"), n2=Decimal("-0.6")) obj = DecimalModel.objects.annotate(n_power=Power("n1", "n2")).first() self.assertIsInstance(obj.n_power, Decimal) self.assertAlmostEqual(obj.n_power, Decimal(obj.n1**obj.n2)) def test_float(self): FloatModel.objects.create(f1=2.3, f2=1.1) obj = FloatModel.objects.annotate(f_power=Power("f1", "f2")).first() self.assertIsInstance(obj.f_power, float) self.assertAlmostEqual(obj.f_power, obj.f1**obj.f2) def test_integer(self): IntegerModel.objects.create(small=-1, normal=20, big=3) obj = IntegerModel.objects.annotate( small_power=Power("small", "normal"), normal_power=Power("normal", "big"), big_power=Power("big", "small"), ).first() self.assertIsInstance(obj.small_power, float) self.assertIsInstance(obj.normal_power, float) self.assertIsInstance(obj.big_power, float) self.assertAlmostEqual(obj.small_power, obj.small**obj.normal) self.assertAlmostEqual(obj.normal_power, obj.normal**obj.big) self.assertAlmostEqual(obj.big_power, obj.big**obj.small)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_sign.py
tests/db_functions/math/test_sign.py
from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Sign from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class SignTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_sign=Sign("normal")).first() self.assertIsNone(obj.null_sign) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_sign=Sign("n1"), n2_sign=Sign("n2") ).first() self.assertIsInstance(obj.n1_sign, Decimal) self.assertIsInstance(obj.n2_sign, Decimal) self.assertEqual(obj.n1_sign, Decimal("-1")) self.assertEqual(obj.n2_sign, Decimal("1")) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate( f1_sign=Sign("f1"), f2_sign=Sign("f2") ).first() self.assertIsInstance(obj.f1_sign, float) self.assertIsInstance(obj.f2_sign, float) self.assertEqual(obj.f1_sign, -1.0) self.assertEqual(obj.f2_sign, 1.0) def test_integer(self): IntegerModel.objects.create(small=-20, normal=0, big=20) obj = IntegerModel.objects.annotate( small_sign=Sign("small"), normal_sign=Sign("normal"), big_sign=Sign("big"), ).first() self.assertIsInstance(obj.small_sign, int) self.assertIsInstance(obj.normal_sign, int) self.assertIsInstance(obj.big_sign, int) self.assertEqual(obj.small_sign, -1) self.assertEqual(obj.normal_sign, 0) self.assertEqual(obj.big_sign, 1) def test_transform(self): with register_lookup(DecimalField, Sign): DecimalModel.objects.create(n1=Decimal("5.4"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-0.1"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__sign__lt=0, n2__sign=0).get() self.assertEqual(obj.n1, Decimal("-0.1"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/__init__.py
tests/db_functions/math/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_radians.py
tests/db_functions/math/test_radians.py
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Radians from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class RadiansTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_radians=Radians("normal")).first() self.assertIsNone(obj.null_radians) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_radians=Radians("n1"), n2_radians=Radians("n2") ).first() self.assertIsInstance(obj.n1_radians, Decimal) self.assertIsInstance(obj.n2_radians, Decimal) self.assertAlmostEqual(obj.n1_radians, Decimal(math.radians(obj.n1))) self.assertAlmostEqual(obj.n2_radians, Decimal(math.radians(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate( f1_radians=Radians("f1"), f2_radians=Radians("f2") ).first() self.assertIsInstance(obj.f1_radians, float) self.assertIsInstance(obj.f2_radians, float) self.assertAlmostEqual(obj.f1_radians, math.radians(obj.f1)) self.assertAlmostEqual(obj.f2_radians, math.radians(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_radians=Radians("small"), normal_radians=Radians("normal"), big_radians=Radians("big"), ).first() self.assertIsInstance(obj.small_radians, float) self.assertIsInstance(obj.normal_radians, float) self.assertIsInstance(obj.big_radians, float) self.assertAlmostEqual(obj.small_radians, math.radians(obj.small)) self.assertAlmostEqual(obj.normal_radians, math.radians(obj.normal)) self.assertAlmostEqual(obj.big_radians, math.radians(obj.big)) def test_transform(self): with register_lookup(DecimalField, Radians): DecimalModel.objects.create(n1=Decimal("2.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-1.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__radians__gt=0).get() self.assertEqual(obj.n1, Decimal("2.0"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_abs.py
tests/db_functions/math/test_abs.py
from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Abs from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class AbsTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_abs=Abs("normal")).first() self.assertIsNone(obj.null_abs) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-0.8"), n2=Decimal("1.2")) obj = DecimalModel.objects.annotate(n1_abs=Abs("n1"), n2_abs=Abs("n2")).first() self.assertIsInstance(obj.n1_abs, Decimal) self.assertIsInstance(obj.n2_abs, Decimal) self.assertEqual(obj.n1, -obj.n1_abs) self.assertEqual(obj.n2, obj.n2_abs) def test_float(self): obj = FloatModel.objects.create(f1=-0.5, f2=12) obj = FloatModel.objects.annotate(f1_abs=Abs("f1"), f2_abs=Abs("f2")).first() self.assertIsInstance(obj.f1_abs, float) self.assertIsInstance(obj.f2_abs, float) self.assertEqual(obj.f1, -obj.f1_abs) self.assertEqual(obj.f2, obj.f2_abs) def test_integer(self): IntegerModel.objects.create(small=12, normal=0, big=-45) obj = IntegerModel.objects.annotate( small_abs=Abs("small"), normal_abs=Abs("normal"), big_abs=Abs("big"), ).first() self.assertIsInstance(obj.small_abs, int) self.assertIsInstance(obj.normal_abs, int) self.assertIsInstance(obj.big_abs, int) self.assertEqual(obj.small, obj.small_abs) self.assertEqual(obj.normal, obj.normal_abs) self.assertEqual(obj.big, -obj.big_abs) def test_transform(self): with register_lookup(DecimalField, Abs): DecimalModel.objects.create(n1=Decimal("-1.5"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-0.5"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__abs__gt=1).get() self.assertEqual(obj.n1, Decimal("-1.5"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_ceil.py
tests/db_functions/math/test_ceil.py
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Ceil from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class CeilTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_ceil=Ceil("normal")).first() self.assertIsNone(obj.null_ceil) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_ceil=Ceil("n1"), n2_ceil=Ceil("n2") ).first() self.assertIsInstance(obj.n1_ceil, Decimal) self.assertIsInstance(obj.n2_ceil, Decimal) self.assertEqual(obj.n1_ceil, Decimal(math.ceil(obj.n1))) self.assertEqual(obj.n2_ceil, Decimal(math.ceil(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-12.5, f2=21.33) obj = FloatModel.objects.annotate( f1_ceil=Ceil("f1"), f2_ceil=Ceil("f2") ).first() self.assertIsInstance(obj.f1_ceil, float) self.assertIsInstance(obj.f2_ceil, float) self.assertEqual(obj.f1_ceil, math.ceil(obj.f1)) self.assertEqual(obj.f2_ceil, math.ceil(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-11, normal=0, big=-100) obj = IntegerModel.objects.annotate( small_ceil=Ceil("small"), normal_ceil=Ceil("normal"), big_ceil=Ceil("big"), ).first() self.assertIsInstance(obj.small_ceil, int) self.assertIsInstance(obj.normal_ceil, int) self.assertIsInstance(obj.big_ceil, int) self.assertEqual(obj.small_ceil, math.ceil(obj.small)) self.assertEqual(obj.normal_ceil, math.ceil(obj.normal)) self.assertEqual(obj.big_ceil, math.ceil(obj.big)) def test_transform(self): with register_lookup(DecimalField, Ceil): DecimalModel.objects.create(n1=Decimal("3.12"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("1.25"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__ceil__gt=3).get() self.assertEqual(obj.n1, Decimal("3.12"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_asin.py
tests/db_functions/math/test_asin.py
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import ASin from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class ASinTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_asin=ASin("normal")).first() self.assertIsNone(obj.null_asin) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("0.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_asin=ASin("n1"), n2_asin=ASin("n2") ).first() self.assertIsInstance(obj.n1_asin, Decimal) self.assertIsInstance(obj.n2_asin, Decimal) self.assertAlmostEqual(obj.n1_asin, Decimal(math.asin(obj.n1))) self.assertAlmostEqual(obj.n2_asin, Decimal(math.asin(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-0.5, f2=0.87) obj = FloatModel.objects.annotate( f1_asin=ASin("f1"), f2_asin=ASin("f2") ).first() self.assertIsInstance(obj.f1_asin, float) self.assertIsInstance(obj.f2_asin, float) self.assertAlmostEqual(obj.f1_asin, math.asin(obj.f1)) self.assertAlmostEqual(obj.f2_asin, math.asin(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=0, normal=1, big=-1) obj = IntegerModel.objects.annotate( small_asin=ASin("small"), normal_asin=ASin("normal"), big_asin=ASin("big"), ).first() self.assertIsInstance(obj.small_asin, float) self.assertIsInstance(obj.normal_asin, float) self.assertIsInstance(obj.big_asin, float) self.assertAlmostEqual(obj.small_asin, math.asin(obj.small)) self.assertAlmostEqual(obj.normal_asin, math.asin(obj.normal)) self.assertAlmostEqual(obj.big_asin, math.asin(obj.big)) def test_transform(self): with register_lookup(DecimalField, ASin): DecimalModel.objects.create(n1=Decimal("0.1"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("1.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__asin__gt=1).get() self.assertEqual(obj.n1, Decimal("1.0"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_atan2.py
tests/db_functions/math/test_atan2.py
import math from decimal import Decimal from django.db.models.functions import ATan2 from django.test import TestCase from ..models import DecimalModel, FloatModel, IntegerModel class ATan2Tests(TestCase): def test_null(self): IntegerModel.objects.create(big=100) obj = IntegerModel.objects.annotate( null_atan2_sn=ATan2("small", "normal"), null_atan2_nb=ATan2("normal", "big"), null_atan2_bn=ATan2("big", "normal"), ).first() self.assertIsNone(obj.null_atan2_sn) self.assertIsNone(obj.null_atan2_nb) self.assertIsNone(obj.null_atan2_bn) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-9.9"), n2=Decimal("4.6")) obj = DecimalModel.objects.annotate(n_atan2=ATan2("n1", "n2")).first() self.assertIsInstance(obj.n_atan2, Decimal) self.assertAlmostEqual(obj.n_atan2, Decimal(math.atan2(obj.n1, obj.n2))) def test_float(self): FloatModel.objects.create(f1=-25, f2=0.33) obj = FloatModel.objects.annotate(f_atan2=ATan2("f1", "f2")).first() self.assertIsInstance(obj.f_atan2, float) self.assertAlmostEqual(obj.f_atan2, math.atan2(obj.f1, obj.f2)) def test_integer(self): IntegerModel.objects.create(small=0, normal=1, big=10) obj = IntegerModel.objects.annotate( atan2_sn=ATan2("small", "normal"), atan2_nb=ATan2("normal", "big"), ).first() self.assertIsInstance(obj.atan2_sn, float) self.assertIsInstance(obj.atan2_nb, float) self.assertAlmostEqual(obj.atan2_sn, math.atan2(obj.small, obj.normal)) self.assertAlmostEqual(obj.atan2_nb, math.atan2(obj.normal, obj.big))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_pi.py
tests/db_functions/math/test_pi.py
import math from django.db.models.functions import Pi from django.test import TestCase from ..models import FloatModel class PiTests(TestCase): def test(self): FloatModel.objects.create(f1=2.5, f2=15.9) obj = FloatModel.objects.annotate(pi=Pi()).first() self.assertIsInstance(obj.pi, float) self.assertAlmostEqual(obj.pi, math.pi, places=5)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/math/test_atan.py
tests/db_functions/math/test_atan.py
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import ATan from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class ATanTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_atan=ATan("normal")).first() self.assertIsNone(obj.null_atan) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_atan=ATan("n1"), n2_atan=ATan("n2") ).first() self.assertIsInstance(obj.n1_atan, Decimal) self.assertIsInstance(obj.n2_atan, Decimal) self.assertAlmostEqual(obj.n1_atan, Decimal(math.atan(obj.n1))) self.assertAlmostEqual(obj.n2_atan, Decimal(math.atan(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate( f1_atan=ATan("f1"), f2_atan=ATan("f2") ).first() self.assertIsInstance(obj.f1_atan, float) self.assertIsInstance(obj.f2_atan, float) self.assertAlmostEqual(obj.f1_atan, math.atan(obj.f1)) self.assertAlmostEqual(obj.f2_atan, math.atan(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_atan=ATan("small"), normal_atan=ATan("normal"), big_atan=ATan("big"), ).first() self.assertIsInstance(obj.small_atan, float) self.assertIsInstance(obj.normal_atan, float) self.assertIsInstance(obj.big_atan, float) self.assertAlmostEqual(obj.small_atan, math.atan(obj.small)) self.assertAlmostEqual(obj.normal_atan, math.atan(obj.normal)) self.assertAlmostEqual(obj.big_atan, math.atan(obj.big)) def test_transform(self): with register_lookup(DecimalField, ATan): DecimalModel.objects.create(n1=Decimal("3.12"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-5"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__atan__gt=0).get() self.assertEqual(obj.n1, Decimal("3.12"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/json/test_json_array.py
tests/db_functions/json/test_json_array.py
import unittest from django.db import NotSupportedError, connection from django.db.models import CharField, F, Value from django.db.models.functions import Cast, JSONArray, JSONObject, Lower from django.test import TestCase from django.test.testcases import skipIfDBFeature, skipUnlessDBFeature from django.utils import timezone from ..models import Article, Author @skipUnlessDBFeature("supports_json_field") class JSONArrayTests(TestCase): @classmethod def setUpTestData(cls): Author.objects.create(name="Ivan Ivanov", alias="iivanov") def test_empty(self): obj = Author.objects.annotate(json_array=JSONArray()).first() self.assertEqual(obj.json_array, []) def test_basic(self): obj = Author.objects.annotate( json_array=JSONArray(Value("name"), F("name")) ).first() self.assertEqual(obj.json_array, ["name", "Ivan Ivanov"]) def test_expressions(self): obj = Author.objects.annotate( json_array=JSONArray( Lower("name"), F("alias"), F("goes_by"), Value(30000.15), F("age") * 2, ) ).first() self.assertEqual( obj.json_array, [ "ivan ivanov", "iivanov", None, 30000.15, 60, ], ) def test_nested_json_array(self): obj = Author.objects.annotate( json_array=JSONArray( F("name"), JSONArray(F("alias"), F("age")), ) ).first() self.assertEqual( obj.json_array, [ "Ivan Ivanov", ["iivanov", 30], ], ) def test_nested_empty_json_array(self): obj = Author.objects.annotate( json_array=JSONArray( F("name"), JSONArray(), ) ).first() self.assertEqual( obj.json_array, [ "Ivan Ivanov", [], ], ) def test_textfield(self): Article.objects.create( title="The Title", text="x" * 4000, written=timezone.now(), ) obj = Article.objects.annotate(json_array=JSONArray(F("text"))).first() self.assertEqual(obj.json_array, ["x" * 4000]) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests") def test_explicit_cast(self): qs = Author.objects.annotate( json_array=JSONArray(Cast("age", CharField())) ).values("json_array") with self.assertNumQueries(1) as ctx: self.assertSequenceEqual(qs, [{"json_array": ["30"]}]) sql = ctx.captured_queries[0]["sql"] self.assertIn("::varchar", sql) self.assertNotIn("::varchar)::varchar", sql) def test_order_by_key(self): qs = Author.objects.annotate(arr=JSONArray(F("alias"))).order_by("arr__0") self.assertQuerySetEqual(qs, Author.objects.order_by("alias")) def test_order_by_nested_key(self): qs = Author.objects.annotate(arr=JSONArray(JSONArray(F("alias")))).order_by( "-arr__0__0" ) self.assertQuerySetEqual(qs, Author.objects.order_by("-alias")) @skipIfDBFeature("supports_json_field") class JSONArrayNotSupportedTests(TestCase): def test_not_supported(self): msg = "JSONFields are not supported on this database backend." with self.assertRaisesMessage(NotSupportedError, msg): Author.objects.annotate(json_array=JSONArray()).first() @skipUnlessDBFeature("has_json_object_function", "supports_json_field") class JSONArrayObjectTests(TestCase): @classmethod def setUpTestData(cls): Author.objects.create(name="Ivan Ivanov", alias="iivanov") def test_nested_json_array_object(self): obj = Author.objects.annotate( json_array=JSONArray( JSONObject( name1="name", nested_json_object1=JSONObject(alias1="alias", age1="age"), ), JSONObject( name2="name", nested_json_object2=JSONObject(alias2="alias", age2="age"), ), ) ).first() self.assertEqual( obj.json_array, [ { "name1": "Ivan Ivanov", "nested_json_object1": {"alias1": "iivanov", "age1": 30}, }, { "name2": "Ivan Ivanov", "nested_json_object2": {"alias2": "iivanov", "age2": 30}, }, ], ) def test_nested_json_object_array(self): obj = Author.objects.annotate( json_object=JSONObject( name="name", nested_json_array=JSONArray( JSONObject(alias1="alias", age1="age"), JSONObject(alias2="alias", age2="age"), ), ) ).first() self.assertEqual( obj.json_object, { "name": "Ivan Ivanov", "nested_json_array": [ {"alias1": "iivanov", "age1": 30}, {"alias2": "iivanov", "age2": 30}, ], }, ) def test_order_by_nested_key(self): qs = Author.objects.annotate( arr=JSONArray(JSONObject(alias=F("alias"))) ).order_by("-arr__0__alias") self.assertQuerySetEqual(qs, Author.objects.order_by("-alias"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/json/test_json_object.py
tests/db_functions/json/test_json_object.py
from django.db import NotSupportedError from django.db.models import F, Value from django.db.models.functions import JSONObject, Lower from django.test import TestCase from django.test.testcases import skipIfDBFeature, skipUnlessDBFeature from django.utils import timezone from ..models import Article, Author @skipUnlessDBFeature("has_json_object_function") class JSONObjectTests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(name="Ivan Ivanov", alias="iivanov"), Author(name="Bertha Berthy", alias="bberthy"), ] ) def test_empty(self): obj = Author.objects.annotate(json_object=JSONObject()).first() self.assertEqual(obj.json_object, {}) def test_basic(self): obj = Author.objects.annotate(json_object=JSONObject(name="name")).first() self.assertEqual(obj.json_object, {"name": "Ivan Ivanov"}) def test_expressions(self): obj = Author.objects.annotate( json_object=JSONObject( name=Lower("name"), alias="alias", goes_by="goes_by", salary=Value(30000.15), age=F("age") * 2, ) ).first() self.assertEqual( obj.json_object, { "name": "ivan ivanov", "alias": "iivanov", "goes_by": None, "salary": 30000.15, "age": 60, }, ) def test_nested_json_object(self): obj = Author.objects.annotate( json_object=JSONObject( name="name", nested_json_object=JSONObject( alias="alias", age="age", ), ) ).first() self.assertEqual( obj.json_object, { "name": "Ivan Ivanov", "nested_json_object": { "alias": "iivanov", "age": 30, }, }, ) def test_nested_empty_json_object(self): obj = Author.objects.annotate( json_object=JSONObject( name="name", nested_json_object=JSONObject(), ) ).first() self.assertEqual( obj.json_object, { "name": "Ivan Ivanov", "nested_json_object": {}, }, ) def test_textfield(self): Article.objects.create( title="The Title", text="x" * 4000, written=timezone.now(), ) obj = Article.objects.annotate(json_object=JSONObject(text=F("text"))).first() self.assertEqual(obj.json_object, {"text": "x" * 4000}) def test_order_by_key(self): qs = Author.objects.annotate(attrs=JSONObject(alias=F("alias"))).order_by( "attrs__alias" ) self.assertQuerySetEqual(qs, Author.objects.order_by("alias")) def test_order_by_nested_key(self): qs = Author.objects.annotate( attrs=JSONObject(nested=JSONObject(alias=F("alias"))) ).order_by("-attrs__nested__alias") self.assertQuerySetEqual(qs, Author.objects.order_by("-alias")) @skipIfDBFeature("has_json_object_function") class JSONObjectNotSupportedTests(TestCase): def test_not_supported(self): msg = "JSONObject() is not supported on this database backend." with self.assertRaisesMessage(NotSupportedError, msg): Author.objects.annotate(json_object=JSONObject()).get()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/json/__init__.py
tests/db_functions/json/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/migrations/0001_setup_extensions.py
tests/db_functions/migrations/0001_setup_extensions.py
from unittest import mock from django.db import migrations try: from django.contrib.postgres.operations import CryptoExtension except ImportError: CryptoExtension = mock.Mock() class Migration(migrations.Migration): # Required for the SHA database functions. operations = [CryptoExtension()]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/migrations/__init__.py
tests/db_functions/migrations/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/migrations/0002_create_test_models.py
tests/db_functions/migrations/0002_create_test_models.py
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("db_functions", "0001_setup_extensions"), ] operations = [ migrations.CreateModel( name="Author", fields=[ ("name", models.CharField(max_length=50)), ("alias", models.CharField(max_length=50, null=True, blank=True)), ("goes_by", models.CharField(max_length=50, null=True, blank=True)), ("age", models.PositiveSmallIntegerField(default=30)), ], ), migrations.CreateModel( name="Article", fields=[ ( "authors", models.ManyToManyField( "db_functions.Author", related_name="articles" ), ), ("title", models.CharField(max_length=50)), ("summary", models.CharField(max_length=200, null=True, blank=True)), ("text", models.TextField()), ("written", models.DateTimeField()), ("published", models.DateTimeField(null=True, blank=True)), ("updated", models.DateTimeField(null=True, blank=True)), ("views", models.PositiveIntegerField(default=0)), ], ), migrations.CreateModel( name="Fan", fields=[ ("name", models.CharField(max_length=50)), ("age", models.PositiveSmallIntegerField(default=30)), ( "author", models.ForeignKey( "db_functions.Author", models.CASCADE, related_name="fans" ), ), ("fan_since", models.DateTimeField(null=True, blank=True)), ], ), migrations.CreateModel( name="DTModel", fields=[ ("name", models.CharField(max_length=32)), ("start_datetime", models.DateTimeField(null=True, blank=True)), ("end_datetime", models.DateTimeField(null=True, blank=True)), ("start_date", models.DateField(null=True, blank=True)), ("end_date", models.DateField(null=True, blank=True)), ("start_time", models.TimeField(null=True, blank=True)), ("end_time", models.TimeField(null=True, blank=True)), ("duration", models.DurationField(null=True, blank=True)), ], ), migrations.CreateModel( name="DecimalModel", fields=[ ("n1", models.DecimalField(decimal_places=2, max_digits=6)), ( "n2", models.DecimalField( decimal_places=7, max_digits=9, null=True, blank=True ), ), ], ), migrations.CreateModel( name="IntegerModel", fields=[ ("big", models.BigIntegerField(null=True, blank=True)), ("normal", models.IntegerField(null=True, blank=True)), ("small", models.SmallIntegerField(null=True, blank=True)), ], ), migrations.CreateModel( name="FloatModel", fields=[ ("f1", models.FloatField(null=True, blank=True)), ("f2", models.FloatField(null=True, blank=True)), ], ), migrations.CreateModel( name="UUIDModel", fields=[ ("uuid", models.UUIDField(null=True)), ("shift", models.DurationField(null=True)), ], ), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_upper.py
tests/db_functions/text/test_upper.py
from django.db.models import CharField from django.db.models.functions import Upper from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class UpperTests(TestCase): def test_basic(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.annotate(upper_name=Upper("name")) self.assertQuerySetEqual( authors.order_by("name"), [ "JOHN SMITH", "RHONDA", ], lambda a: a.upper_name, ) Author.objects.update(name=Upper("name")) self.assertQuerySetEqual( authors.order_by("name"), [ ("JOHN SMITH", "JOHN SMITH"), ("RHONDA", "RHONDA"), ], lambda a: (a.upper_name, a.name), ) def test_transform(self): with register_lookup(CharField, Upper): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.filter(name__upper__exact="JOHN SMITH") self.assertQuerySetEqual( authors.order_by("name"), [ "John Smith", ], lambda a: a.name, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_substr.py
tests/db_functions/text/test_substr.py
from django.db.models import Value as V from django.db.models.functions import Lower, StrIndex, Substr, Upper from django.test import TestCase from ..models import Author class SubstrTests(TestCase): def test_basic(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.annotate(name_part=Substr("name", 5, 3)) self.assertQuerySetEqual( authors.order_by("name"), [" Sm", "da"], lambda a: a.name_part ) authors = Author.objects.annotate(name_part=Substr("name", 2)) self.assertQuerySetEqual( authors.order_by("name"), ["ohn Smith", "honda"], lambda a: a.name_part ) # If alias is null, set to first 5 lower characters of the name. Author.objects.filter(alias__isnull=True).update( alias=Lower(Substr("name", 1, 5)), ) self.assertQuerySetEqual( authors.order_by("name"), ["smithj", "rhond"], lambda a: a.alias ) def test_start(self): Author.objects.create(name="John Smith", alias="smithj") a = Author.objects.annotate( name_part_1=Substr("name", 1), name_part_2=Substr("name", 2), ).get(alias="smithj") self.assertEqual(a.name_part_1[1:], a.name_part_2) def test_pos_gt_zero(self): with self.assertRaisesMessage(ValueError, "'pos' must be greater than 0"): Author.objects.annotate(raises=Substr("name", 0)) def test_expressions(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") substr = Substr(Upper("name"), StrIndex("name", V("h")), 5) authors = Author.objects.annotate(name_part=substr) self.assertQuerySetEqual( authors.order_by("name"), ["HN SM", "HONDA"], lambda a: a.name_part )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_trim.py
tests/db_functions/text/test_trim.py
from django.db.models import CharField from django.db.models.functions import LTrim, RTrim, Trim from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class TrimTests(TestCase): def test_trim(self): Author.objects.create(name=" John ", alias="j") Author.objects.create(name="Rhonda", alias="r") authors = Author.objects.annotate( ltrim=LTrim("name"), rtrim=RTrim("name"), trim=Trim("name"), ) self.assertQuerySetEqual( authors.order_by("alias"), [ ("John ", " John", "John"), ("Rhonda", "Rhonda", "Rhonda"), ], lambda a: (a.ltrim, a.rtrim, a.trim), ) def test_trim_transform(self): Author.objects.create(name=" John ") Author.objects.create(name="Rhonda") tests = ( (LTrim, "John "), (RTrim, " John"), (Trim, "John"), ) for transform, trimmed_name in tests: with self.subTest(transform=transform): with register_lookup(CharField, transform): authors = Author.objects.filter( **{"name__%s" % transform.lookup_name: trimmed_name} ) self.assertQuerySetEqual(authors, [" John "], lambda a: a.name)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_sha384.py
tests/db_functions/text/test_sha384.py
from django.db import connection from django.db.models import CharField from django.db.models.functions import SHA384 from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class SHA384Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(alias="John Smith"), Author(alias="Jordan Élena"), Author(alias="皇帝"), Author(alias=""), Author(alias=None), ] ) def test_basic(self): authors = ( Author.objects.annotate( sha384_alias=SHA384("alias"), ) .values_list("sha384_alias", flat=True) .order_by("pk") ) self.assertSequenceEqual( authors, [ "9df976bfbcf96c66fbe5cba866cd4deaa8248806f15b69c4010a404112906e4ca7b57e" "53b9967b80d77d4f5c2982cbc8", "72202c8005492016cc670219cce82d47d6d2d4273464c742ab5811d691b1e82a748954" "9e3a73ffa119694f90678ba2e3", "eda87fae41e59692c36c49e43279c8111a00d79122a282a944e8ba9a403218f049a483" "26676a43c7ba378621175853b0", "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274ede" "bfe76f65fbd51ad2f14898b95b", ( "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da27" "4edebfe76f65fbd51ad2f14898b95b" if connection.features.interprets_empty_strings_as_nulls else None ), ], ) def test_transform(self): with register_lookup(CharField, SHA384): authors = Author.objects.filter( alias__sha384=( "9df976bfbcf96c66fbe5cba866cd4deaa8248806f15b69c4010a404112906e4ca7" "b57e53b9967b80d77d4f5c2982cbc8" ), ).values_list("alias", flat=True) self.assertSequenceEqual(authors, ["John Smith"])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_repeat.py
tests/db_functions/text/test_repeat.py
from django.db import connection from django.db.models import Value from django.db.models.functions import Length, Repeat from django.test import TestCase from ..models import Author class RepeatTests(TestCase): def test_basic(self): Author.objects.create(name="John", alias="xyz") none_value = ( "" if connection.features.interprets_empty_strings_as_nulls else None ) tests = ( (Repeat("name", 0), ""), (Repeat("name", 2), "JohnJohn"), (Repeat("name", Length("alias")), "JohnJohnJohn"), (Repeat(Value("x"), 3), "xxx"), (Repeat("name", None), none_value), (Repeat(Value(None), 4), none_value), (Repeat("goes_by", 1), none_value), ) for function, repeated_text in tests: with self.subTest(function=function): authors = Author.objects.annotate(repeated_text=function) self.assertQuerySetEqual( authors, [repeated_text], lambda a: a.repeated_text, ordered=False ) def test_negative_number(self): with self.assertRaisesMessage( ValueError, "'number' must be greater or equal to 0." ): Repeat("name", -1)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_strindex.py
tests/db_functions/text/test_strindex.py
from django.db.models import Value from django.db.models.functions import StrIndex from django.test import TestCase from django.utils import timezone from ..models import Article, Author class StrIndexTests(TestCase): def test_annotate_charfield(self): Author.objects.create(name="George. R. R. Martin") Author.objects.create(name="J. R. R. Tolkien") Author.objects.create(name="Terry Pratchett") authors = Author.objects.annotate(fullstop=StrIndex("name", Value("R."))) self.assertQuerySetEqual( authors.order_by("name"), [9, 4, 0], lambda a: a.fullstop ) def test_annotate_textfield(self): Article.objects.create( title="How to Django", text="This is about How to Django.", written=timezone.now(), ) Article.objects.create( title="How to Tango", text="Won't find anything here.", written=timezone.now(), ) articles = Article.objects.annotate(title_pos=StrIndex("text", "title")) self.assertQuerySetEqual( articles.order_by("title"), [15, 0], lambda a: a.title_pos ) def test_order_by(self): Author.objects.create(name="Terry Pratchett") Author.objects.create(name="J. R. R. Tolkien") Author.objects.create(name="George. R. R. Martin") self.assertQuerySetEqual( Author.objects.order_by(StrIndex("name", Value("R.")).asc()), [ "Terry Pratchett", "J. R. R. Tolkien", "George. R. R. Martin", ], lambda a: a.name, ) self.assertQuerySetEqual( Author.objects.order_by(StrIndex("name", Value("R.")).desc()), [ "George. R. R. Martin", "J. R. R. Tolkien", "Terry Pratchett", ], lambda a: a.name, ) def test_unicode_values(self): Author.objects.create(name="ツリー") Author.objects.create(name="皇帝") Author.objects.create(name="皇帝 ツリー") authors = Author.objects.annotate(sb=StrIndex("name", Value("リ"))) self.assertQuerySetEqual(authors.order_by("name"), [2, 0, 5], lambda a: a.sb) def test_filtering(self): Author.objects.create(name="George. R. R. Martin") Author.objects.create(name="Terry Pratchett") self.assertQuerySetEqual( Author.objects.annotate(middle_name=StrIndex("name", Value("R."))).filter( middle_name__gt=0 ), ["George. R. R. Martin"], lambda a: a.name, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_concat.py
tests/db_functions/text/test_concat.py
from unittest import skipUnless from django.db import connection from django.db.models import CharField, TextField from django.db.models import Value as V from django.db.models.functions import Concat, ConcatPair, Upper from django.test import TestCase from django.utils import timezone from ..models import Article, Author lorem_ipsum = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" class ConcatTests(TestCase): def test_basic(self): Author.objects.create(name="Jayden") Author.objects.create(name="John Smith", alias="smithj", goes_by="John") Author.objects.create(name="Margaret", goes_by="Maggie") Author.objects.create(name="Rhonda", alias="adnohR") authors = Author.objects.annotate(joined=Concat("alias", "goes_by")) self.assertQuerySetEqual( authors.order_by("name"), [ "", "smithjJohn", "Maggie", "adnohR", ], lambda a: a.joined, ) def test_gt_two_expressions(self): with self.assertRaisesMessage( ValueError, "Concat must take at least two expressions" ): Author.objects.annotate(joined=Concat("alias")) def test_many(self): Author.objects.create(name="Jayden") Author.objects.create(name="John Smith", alias="smithj", goes_by="John") Author.objects.create(name="Margaret", goes_by="Maggie") Author.objects.create(name="Rhonda", alias="adnohR") authors = Author.objects.annotate( joined=Concat("name", V(" ("), "goes_by", V(")"), output_field=CharField()), ) self.assertQuerySetEqual( authors.order_by("name"), [ "Jayden ()", "John Smith (John)", "Margaret (Maggie)", "Rhonda ()", ], lambda a: a.joined, ) def test_mixed_char_text(self): Article.objects.create( title="The Title", text=lorem_ipsum, written=timezone.now() ) article = Article.objects.annotate( title_text=Concat("title", V(" - "), "text", output_field=TextField()), ).get(title="The Title") self.assertEqual(article.title + " - " + article.text, article.title_text) # Wrap the concat in something else to ensure that text is returned # rather than bytes. article = Article.objects.annotate( title_text=Upper( Concat("title", V(" - "), "text", output_field=TextField()) ), ).get(title="The Title") expected = article.title + " - " + article.text self.assertEqual(expected.upper(), article.title_text) @skipUnless( connection.vendor in ("sqlite", "postgresql"), "SQLite and PostgreSQL specific implementation detail.", ) def test_coalesce_idempotent(self): pair = ConcatPair(V("a"), V("b")) # Check nodes counts self.assertEqual(len(list(pair.flatten())), 3) self.assertEqual( len(list(pair.coalesce().flatten())), 7 ) # + 2 Coalesce + 2 Value() self.assertEqual(len(list(pair.flatten())), 3) def test_sql_generation_idempotency(self): qs = Article.objects.annotate(description=Concat("title", V(": "), "summary")) # Multiple compilations should not alter the generated query. self.assertEqual(str(qs.query), str(qs.all().query)) def test_concat_non_str(self): Author.objects.create(name="The Name", age=42) with self.assertNumQueries(1) as ctx: author = Author.objects.annotate( name_text=Concat( "name", V(":"), "alias", V(":"), "age", output_field=TextField() ), ).get() self.assertEqual(author.name_text, "The Name::42") # Only non-string columns are casted on PostgreSQL. self.assertEqual( ctx.captured_queries[0]["sql"].count("::text"), 1 if connection.vendor == "postgresql" else 0, ) def test_equal(self): self.assertEqual( Concat("foo", "bar", output_field=TextField()), Concat("foo", "bar", output_field=TextField()), ) self.assertNotEqual( Concat("foo", "bar", output_field=TextField()), Concat("foo", "bar", output_field=CharField()), ) self.assertNotEqual( Concat("foo", "bar", output_field=TextField()), Concat("bar", "foo", output_field=TextField()), )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_lower.py
tests/db_functions/text/test_lower.py
from django.db.models import CharField from django.db.models.functions import Lower from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class LowerTests(TestCase): def test_basic(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.annotate(lower_name=Lower("name")) self.assertQuerySetEqual( authors.order_by("name"), ["john smith", "rhonda"], lambda a: a.lower_name ) Author.objects.update(name=Lower("name")) self.assertQuerySetEqual( authors.order_by("name"), [ ("john smith", "john smith"), ("rhonda", "rhonda"), ], lambda a: (a.lower_name, a.name), ) def test_num_args(self): with self.assertRaisesMessage( TypeError, "'Lower' takes exactly 1 argument (2 given)" ): Author.objects.update(name=Lower("name", "name")) def test_transform(self): with register_lookup(CharField, Lower): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.filter(name__lower__exact="john smith") self.assertQuerySetEqual( authors.order_by("name"), ["John Smith"], lambda a: a.name )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_length.py
tests/db_functions/text/test_length.py
from django.db.models import CharField from django.db.models.functions import Length from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class LengthTests(TestCase): def test_basic(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.annotate( name_length=Length("name"), alias_length=Length("alias"), ) self.assertQuerySetEqual( authors.order_by("name"), [(10, 6), (6, None)], lambda a: (a.name_length, a.alias_length), ) self.assertEqual(authors.filter(alias_length__lte=Length("name")).count(), 1) def test_ordering(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="John Smith", alias="smithj1") Author.objects.create(name="Rhonda", alias="ronny") authors = Author.objects.order_by(Length("name"), Length("alias")) self.assertQuerySetEqual( authors, [ ("Rhonda", "ronny"), ("John Smith", "smithj"), ("John Smith", "smithj1"), ], lambda a: (a.name, a.alias), ) def test_transform(self): with register_lookup(CharField, Length): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.filter(name__length__gt=7) self.assertQuerySetEqual( authors.order_by("name"), ["John Smith"], lambda a: a.name )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_sha1.py
tests/db_functions/text/test_sha1.py
from django.db import connection from django.db.models import CharField from django.db.models.functions import SHA1 from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class SHA1Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(alias="John Smith"), Author(alias="Jordan Élena"), Author(alias="皇帝"), Author(alias=""), Author(alias=None), ] ) def test_basic(self): authors = ( Author.objects.annotate( sha1_alias=SHA1("alias"), ) .values_list("sha1_alias", flat=True) .order_by("pk") ) self.assertSequenceEqual( authors, [ "e61a3587b3f7a142b8c7b9263c82f8119398ecb7", "0781e0745a2503e6ded05ed5bc554c421d781b0c", "198d15ea139de04060caf95bc3e0ec5883cba881", "da39a3ee5e6b4b0d3255bfef95601890afd80709", ( "da39a3ee5e6b4b0d3255bfef95601890afd80709" if connection.features.interprets_empty_strings_as_nulls else None ), ], ) def test_transform(self): with register_lookup(CharField, SHA1): authors = Author.objects.filter( alias__sha1="e61a3587b3f7a142b8c7b9263c82f8119398ecb7", ).values_list("alias", flat=True) self.assertSequenceEqual(authors, ["John Smith"])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_replace.py
tests/db_functions/text/test_replace.py
from django.db.models import F, Value from django.db.models.functions import Concat, Replace from django.test import TestCase from ..models import Author class ReplaceTests(TestCase): @classmethod def setUpTestData(cls): Author.objects.create(name="George R. R. Martin") Author.objects.create(name="J. R. R. Tolkien") def test_replace_with_empty_string(self): qs = Author.objects.annotate( without_middlename=Replace(F("name"), Value("R. R. "), Value("")), ) self.assertQuerySetEqual( qs, [ ("George R. R. Martin", "George Martin"), ("J. R. R. Tolkien", "J. Tolkien"), ], transform=lambda x: (x.name, x.without_middlename), ordered=False, ) def test_case_sensitive(self): qs = Author.objects.annotate( same_name=Replace(F("name"), Value("r. r."), Value("")) ) self.assertQuerySetEqual( qs, [ ("George R. R. Martin", "George R. R. Martin"), ("J. R. R. Tolkien", "J. R. R. Tolkien"), ], transform=lambda x: (x.name, x.same_name), ordered=False, ) def test_replace_expression(self): qs = Author.objects.annotate( same_name=Replace( Concat(Value("Author: "), F("name")), Value("Author: "), Value("") ), ) self.assertQuerySetEqual( qs, [ ("George R. R. Martin", "George R. R. Martin"), ("J. R. R. Tolkien", "J. R. R. Tolkien"), ], transform=lambda x: (x.name, x.same_name), ordered=False, ) def test_update(self): Author.objects.update( name=Replace(F("name"), Value("R. R. "), Value("")), ) self.assertQuerySetEqual( Author.objects.all(), [ ("George Martin"), ("J. Tolkien"), ], transform=lambda x: x.name, ordered=False, ) def test_replace_with_default_arg(self): # The default replacement is an empty string. qs = Author.objects.annotate(same_name=Replace(F("name"), Value("R. R. "))) self.assertQuerySetEqual( qs, [ ("George R. R. Martin", "George Martin"), ("J. R. R. Tolkien", "J. Tolkien"), ], transform=lambda x: (x.name, x.same_name), ordered=False, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_left.py
tests/db_functions/text/test_left.py
from django.db.models import IntegerField, Value from django.db.models.functions import Left, Lower from django.test import TestCase from ..models import Author class LeftTests(TestCase): @classmethod def setUpTestData(cls): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") def test_basic(self): authors = Author.objects.annotate(name_part=Left("name", 5)) self.assertQuerySetEqual( authors.order_by("name"), ["John ", "Rhond"], lambda a: a.name_part ) # If alias is null, set it to the first 2 lower characters of the name. Author.objects.filter(alias__isnull=True).update(alias=Lower(Left("name", 2))) self.assertQuerySetEqual( authors.order_by("name"), ["smithj", "rh"], lambda a: a.alias ) def test_invalid_length(self): with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"): Author.objects.annotate(raises=Left("name", 0)) def test_expressions(self): authors = Author.objects.annotate( name_part=Left("name", Value(3, output_field=IntegerField())) ) self.assertQuerySetEqual( authors.order_by("name"), ["Joh", "Rho"], lambda a: a.name_part )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_sha512.py
tests/db_functions/text/test_sha512.py
from django.db import connection from django.db.models import CharField from django.db.models.functions import SHA512 from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class SHA512Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(alias="John Smith"), Author(alias="Jordan Élena"), Author(alias="皇帝"), Author(alias=""), Author(alias=None), ] ) def test_basic(self): authors = ( Author.objects.annotate( sha512_alias=SHA512("alias"), ) .values_list("sha512_alias", flat=True) .order_by("pk") ) self.assertSequenceEqual( authors, [ "ed014a19bb67a85f9c8b1d81e04a0e7101725be8627d79d02ca4f3bd803f33cf" "3b8fed53e80d2a12c0d0e426824d99d110f0919298a5055efff040a3fc091518", "b09c449f3ba49a32ab44754982d4749ac938af293e4af2de28858858080a1611" "2b719514b5e48cb6ce54687e843a4b3e69a04cdb2a9dc99c3b99bdee419fa7d0", "b554d182e25fb487a3f2b4285bb8672f98956b5369138e681b467d1f079af116" "172d88798345a3a7666faf5f35a144c60812d3234dcd35f444624f2faee16857", "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce" "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", ( "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce" "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e" if connection.features.interprets_empty_strings_as_nulls else None ), ], ) def test_transform(self): with register_lookup(CharField, SHA512): authors = Author.objects.filter( alias__sha512=( "ed014a19bb67a85f9c8b1d81e04a0e7101725be8627d79d02ca4f3bd8" "03f33cf3b8fed53e80d2a12c0d0e426824d99d110f0919298a5055eff" "f040a3fc091518" ), ).values_list("alias", flat=True) self.assertSequenceEqual(authors, ["John Smith"])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_sha224.py
tests/db_functions/text/test_sha224.py
import unittest from django.db import NotSupportedError, connection from django.db.models import CharField from django.db.models.functions import SHA224 from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class SHA224Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(alias="John Smith"), Author(alias="Jordan Élena"), Author(alias="皇帝"), Author(alias=""), Author(alias=None), ] ) def test_basic(self): authors = ( Author.objects.annotate( sha224_alias=SHA224("alias"), ) .values_list("sha224_alias", flat=True) .order_by("pk") ) self.assertSequenceEqual( authors, [ "a61303c220731168452cb6acf3759438b1523e768f464e3704e12f70", "2297904883e78183cb118fc3dc21a610d60daada7b6ebdbc85139f4d", "eba942746e5855121d9d8f79e27dfdebed81adc85b6bf41591203080", "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", ( "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f" if connection.features.interprets_empty_strings_as_nulls else None ), ], ) def test_transform(self): with register_lookup(CharField, SHA224): authors = Author.objects.filter( alias__sha224=( "a61303c220731168452cb6acf3759438b1523e768f464e3704e12f70" ), ).values_list("alias", flat=True) self.assertSequenceEqual(authors, ["John Smith"]) @unittest.skipUnless( connection.vendor == "oracle", "Oracle doesn't support SHA224." ) def test_unsupported(self): msg = "SHA224 is not supported on Oracle." with self.assertRaisesMessage(NotSupportedError, msg): Author.objects.annotate(sha224_alias=SHA224("alias")).first()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_md5.py
tests/db_functions/text/test_md5.py
from django.db import connection from django.db.models import CharField from django.db.models.functions import MD5 from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class MD5Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(alias="John Smith"), Author(alias="Jordan Élena"), Author(alias="皇帝"), Author(alias=""), Author(alias=None), ] ) def test_basic(self): authors = ( Author.objects.annotate( md5_alias=MD5("alias"), ) .values_list("md5_alias", flat=True) .order_by("pk") ) self.assertSequenceEqual( authors, [ "6117323d2cabbc17d44c2b44587f682c", "ca6d48f6772000141e66591aee49d56c", "bf2c13bc1154e3d2e7df848cbc8be73d", "d41d8cd98f00b204e9800998ecf8427e", ( "d41d8cd98f00b204e9800998ecf8427e" if connection.features.interprets_empty_strings_as_nulls else None ), ], ) def test_transform(self): with register_lookup(CharField, MD5): authors = Author.objects.filter( alias__md5="6117323d2cabbc17d44c2b44587f682c", ).values_list("alias", flat=True) self.assertSequenceEqual(authors, ["John Smith"])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_right.py
tests/db_functions/text/test_right.py
from django.db import connection from django.db.models import IntegerField, Value from django.db.models.functions import Length, Lower, Right from django.test import TestCase from ..models import Author class RightTests(TestCase): @classmethod def setUpTestData(cls): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") def test_basic(self): authors = Author.objects.annotate(name_part=Right("name", 5)) self.assertQuerySetEqual( authors.order_by("name"), ["Smith", "honda"], lambda a: a.name_part ) # If alias is null, set it to the first 2 lower characters of the name. Author.objects.filter(alias__isnull=True).update(alias=Lower(Right("name", 2))) self.assertQuerySetEqual( authors.order_by("name"), ["smithj", "da"], lambda a: a.alias ) def test_invalid_length(self): with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"): Author.objects.annotate(raises=Right("name", 0)) def test_zero_length(self): Author.objects.create(name="Tom", alias="tom") authors = Author.objects.annotate( name_part=Right("name", Length("name") - Length("alias")) ) self.assertQuerySetEqual( authors.order_by("name"), [ "mith", "" if connection.features.interprets_empty_strings_as_nulls else None, "", ], lambda a: a.name_part, ) def test_expressions(self): authors = Author.objects.annotate( name_part=Right("name", Value(3, output_field=IntegerField())) ) self.assertQuerySetEqual( authors.order_by("name"), ["ith", "nda"], lambda a: a.name_part )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_chr.py
tests/db_functions/text/test_chr.py
from django.db.models import F, IntegerField from django.db.models.functions import Chr, Left, Ord from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class ChrTests(TestCase): @classmethod def setUpTestData(cls): cls.john = Author.objects.create(name="John Smith", alias="smithj") cls.elena = Author.objects.create(name="Élena Jordan", alias="elena") cls.rhonda = Author.objects.create(name="Rhonda") def test_basic(self): authors = Author.objects.annotate(first_initial=Left("name", 1)) self.assertCountEqual(authors.filter(first_initial=Chr(ord("J"))), [self.john]) self.assertCountEqual( authors.exclude(first_initial=Chr(ord("J"))), [self.elena, self.rhonda] ) def test_non_ascii(self): authors = Author.objects.annotate(first_initial=Left("name", 1)) self.assertCountEqual(authors.filter(first_initial=Chr(ord("É"))), [self.elena]) self.assertCountEqual( authors.exclude(first_initial=Chr(ord("É"))), [self.john, self.rhonda] ) def test_transform(self): with register_lookup(IntegerField, Chr): authors = Author.objects.annotate(name_code_point=Ord("name")) self.assertCountEqual( authors.filter(name_code_point__chr=Chr(ord("J"))), [self.john] ) self.assertCountEqual( authors.exclude(name_code_point__chr=Chr(ord("J"))), [self.elena, self.rhonda], ) def test_annotate(self): authors = Author.objects.annotate( first_initial=Left("name", 1), initial_chr=Chr(ord("J")), ) self.assertSequenceEqual( authors.filter(first_initial=F("initial_chr")), [self.john], )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_reverse.py
tests/db_functions/text/test_reverse.py
from django.db import connection from django.db.models import CharField, Value from django.db.models.functions import Length, Reverse, Trim from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class ReverseTests(TestCase): @classmethod def setUpTestData(cls): cls.john = Author.objects.create(name="John Smith", alias="smithj") cls.elena = Author.objects.create(name="Élena Jordan", alias="elena") cls.python = Author.objects.create(name="パイソン") def test_null(self): author = Author.objects.annotate(backward=Reverse("alias")).get( pk=self.python.pk ) self.assertEqual( author.backward, "" if connection.features.interprets_empty_strings_as_nulls else None, ) def test_basic(self): authors = Author.objects.annotate( backward=Reverse("name"), constant=Reverse(Value("static string")), ) self.assertQuerySetEqual( authors, [ ("John Smith", "htimS nhoJ", "gnirts citats"), ("Élena Jordan", "nadroJ anelÉ", "gnirts citats"), ("パイソン", "ンソイパ", "gnirts citats"), ], lambda a: (a.name, a.backward, a.constant), ordered=False, ) def test_transform(self): with register_lookup(CharField, Reverse): authors = Author.objects.all() self.assertCountEqual( authors.filter(name__reverse=self.john.name[::-1]), [self.john] ) self.assertCountEqual( authors.exclude(name__reverse=self.john.name[::-1]), [self.elena, self.python], ) def test_expressions(self): author = Author.objects.annotate(backward=Reverse(Trim("name"))).get( pk=self.john.pk ) self.assertEqual(author.backward, self.john.name[::-1]) with register_lookup(CharField, Reverse), register_lookup(CharField, Length): authors = Author.objects.all() self.assertCountEqual( authors.filter(name__reverse__length__gt=7), [self.john, self.elena] ) self.assertCountEqual( authors.exclude(name__reverse__length__gt=7), [self.python] )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/__init__.py
tests/db_functions/text/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_sha256.py
tests/db_functions/text/test_sha256.py
from django.db import connection from django.db.models import CharField from django.db.models.functions import SHA256 from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class SHA256Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(alias="John Smith"), Author(alias="Jordan Élena"), Author(alias="皇帝"), Author(alias=""), Author(alias=None), ] ) def test_basic(self): authors = ( Author.objects.annotate( sha256_alias=SHA256("alias"), ) .values_list("sha256_alias", flat=True) .order_by("pk") ) self.assertSequenceEqual( authors, [ "ef61a579c907bbed674c0dbcbcf7f7af8f851538eef7b8e58c5bee0b8cfdac4a", "6e4cce20cd83fc7c202f21a8b2452a68509cf24d1c272a045b5e0cfc43f0d94e", "3ad2039e3ec0c88973ae1c0fce5a3dbafdd5a1627da0a92312c54ebfcf43988e", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", ( "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" if connection.features.interprets_empty_strings_as_nulls else None ), ], ) def test_transform(self): with register_lookup(CharField, SHA256): authors = Author.objects.filter( alias__sha256=( "ef61a579c907bbed674c0dbcbcf7f7af8f851538eef7b8e58c5bee0b8cfdac4a" ), ).values_list("alias", flat=True) self.assertSequenceEqual(authors, ["John Smith"])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_pad.py
tests/db_functions/text/test_pad.py
from django.db import connection from django.db.models import Value from django.db.models.functions import Length, LPad, RPad from django.test import TestCase from ..models import Author class PadTests(TestCase): def test_pad(self): Author.objects.create(name="John", alias="j") none_value = ( "" if connection.features.interprets_empty_strings_as_nulls else None ) tests = ( (LPad("name", 7, Value("xy")), "xyxJohn"), (RPad("name", 7, Value("xy")), "Johnxyx"), (LPad("name", 6, Value("x")), "xxJohn"), (RPad("name", 6, Value("x")), "Johnxx"), # The default pad string is a space. (LPad("name", 6), " John"), (RPad("name", 6), "John "), # If string is longer than length it is truncated. (LPad("name", 2), "Jo"), (RPad("name", 2), "Jo"), (LPad("name", 0), ""), (RPad("name", 0), ""), (LPad("name", None), none_value), (RPad("name", None), none_value), (LPad(Value(None), 1), none_value), (RPad(Value(None), 1), none_value), (LPad("goes_by", 1), none_value), (RPad("goes_by", 1), none_value), ) for function, padded_name in tests: with self.subTest(function=function): authors = Author.objects.annotate(padded_name=function) self.assertQuerySetEqual( authors, [padded_name], lambda a: a.padded_name, ordered=False ) def test_pad_negative_length(self): for function in (LPad, RPad): with self.subTest(function=function): with self.assertRaisesMessage( ValueError, "'length' must be greater or equal to 0." ): function("name", -1) def test_combined_with_length(self): Author.objects.create(name="Rhonda", alias="john_smith") Author.objects.create(name="♥♣♠", alias="bytes") authors = Author.objects.annotate(filled=LPad("name", Length("alias"))) self.assertQuerySetEqual( authors.order_by("alias"), [" ♥♣♠", " Rhonda"], lambda a: a.filled, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_functions/text/test_ord.py
tests/db_functions/text/test_ord.py
from django.db.models import CharField, Value from django.db.models.functions import Left, Ord from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class OrdTests(TestCase): @classmethod def setUpTestData(cls): cls.john = Author.objects.create(name="John Smith", alias="smithj") cls.elena = Author.objects.create(name="Élena Jordan", alias="elena") cls.rhonda = Author.objects.create(name="Rhonda") def test_basic(self): authors = Author.objects.annotate(name_part=Ord("name")) self.assertCountEqual( authors.filter(name_part__gt=Ord(Value("John"))), [self.elena, self.rhonda] ) self.assertCountEqual( authors.exclude(name_part__gt=Ord(Value("John"))), [self.john] ) def test_transform(self): with register_lookup(CharField, Ord): authors = Author.objects.annotate(first_initial=Left("name", 1)) self.assertCountEqual( authors.filter(first_initial__ord=ord("J")), [self.john] ) self.assertCountEqual( authors.exclude(first_initial__ord=ord("J")), [self.elena, self.rhonda] )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/prefetch_related/test_uuid.py
tests/prefetch_related/test_uuid.py
from django.test import TestCase from .models import Flea, House, Person, Pet, Room class UUIDPrefetchRelated(TestCase): def test_prefetch_related_from_uuid_model(self): Pet.objects.create(name="Fifi").people.add( Person.objects.create(name="Ellen"), Person.objects.create(name="George"), ) with self.assertNumQueries(2): pet = Pet.objects.prefetch_related("people").get(name="Fifi") with self.assertNumQueries(0): self.assertEqual(2, len(pet.people.all())) def test_prefetch_related_to_uuid_model(self): Person.objects.create(name="Bella").pets.add( Pet.objects.create(name="Socks"), Pet.objects.create(name="Coffee"), ) with self.assertNumQueries(2): person = Person.objects.prefetch_related("pets").get(name="Bella") with self.assertNumQueries(0): self.assertEqual(2, len(person.pets.all())) def test_prefetch_related_from_uuid_model_to_uuid_model(self): fleas = [Flea.objects.create() for i in range(3)] Pet.objects.create(name="Fifi").fleas_hosted.add(*fleas) Pet.objects.create(name="Bobo").fleas_hosted.add(*fleas) with self.assertNumQueries(2): pet = Pet.objects.prefetch_related("fleas_hosted").get(name="Fifi") with self.assertNumQueries(0): self.assertEqual(3, len(pet.fleas_hosted.all())) with self.assertNumQueries(2): flea = Flea.objects.prefetch_related("pets_visited").get(pk=fleas[0].pk) with self.assertNumQueries(0): self.assertEqual(2, len(flea.pets_visited.all())) def test_prefetch_related_from_uuid_model_to_uuid_model_with_values_flat(self): pet = Pet.objects.create(name="Fifi") pet.people.add( Person.objects.create(name="Ellen"), Person.objects.create(name="George"), ) self.assertSequenceEqual( Pet.objects.prefetch_related("fleas_hosted").values_list("id", flat=True), [pet.id], ) class UUIDPrefetchRelatedLookups(TestCase): @classmethod def setUpTestData(cls): house = House.objects.create(name="Redwood", address="Arcata") room = Room.objects.create(name="Racoon", house=house) fleas = [Flea.objects.create(current_room=room) for i in range(3)] pet = Pet.objects.create(name="Spooky") pet.fleas_hosted.add(*fleas) person = Person.objects.create(name="Bob") person.houses.add(house) person.pets.add(pet) person.fleas_hosted.add(*fleas) def test_from_uuid_pk_lookup_uuid_pk_integer_pk(self): # From uuid-pk model, prefetch <uuid-pk model>.<integer-pk model>: with self.assertNumQueries(4): spooky = Pet.objects.prefetch_related( "fleas_hosted__current_room__house" ).get(name="Spooky") with self.assertNumQueries(0): self.assertEqual("Racoon", spooky.fleas_hosted.all()[0].current_room.name) def test_from_uuid_pk_lookup_integer_pk2_uuid_pk2(self): # From uuid-pk model, prefetch # <integer-pk model>.<integer-pk model>.<uuid-pk model>.<uuid-pk # model>: with self.assertNumQueries(5): spooky = Pet.objects.prefetch_related("people__houses__rooms__fleas").get( name="Spooky" ) with self.assertNumQueries(0): self.assertEqual( 3, len(spooky.people.all()[0].houses.all()[0].rooms.all()[0].fleas.all()), ) def test_from_integer_pk_lookup_uuid_pk_integer_pk(self): # From integer-pk model, prefetch <uuid-pk model>.<integer-pk model>: with self.assertNumQueries(3): racoon = Room.objects.prefetch_related("fleas__people_visited").get( name="Racoon" ) with self.assertNumQueries(0): self.assertEqual("Bob", racoon.fleas.all()[0].people_visited.all()[0].name) def test_from_integer_pk_lookup_integer_pk_uuid_pk(self): # From integer-pk model, prefetch <integer-pk model>.<uuid-pk model>: with self.assertNumQueries(3): redwood = House.objects.prefetch_related("rooms__fleas").get(name="Redwood") with self.assertNumQueries(0): self.assertEqual(3, len(redwood.rooms.all()[0].fleas.all())) def test_from_integer_pk_lookup_integer_pk_uuid_pk_uuid_pk(self): # From integer-pk model, prefetch # <integer-pk model>.<uuid-pk model>.<uuid-pk model>: with self.assertNumQueries(4): redwood = House.objects.prefetch_related("rooms__fleas__pets_visited").get( name="Redwood" ) with self.assertNumQueries(0): self.assertEqual( "Spooky", redwood.rooms.all()[0].fleas.all()[0].pets_visited.all()[0].name, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/prefetch_related/models.py
tests/prefetch_related/models.py
import uuid from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from django.db.models.query import ModelIterable from django.utils.functional import cached_property class Author(models.Model): name = models.CharField(max_length=50, unique=True) first_book = models.ForeignKey( "Book", models.CASCADE, related_name="first_time_authors" ) favorite_authors = models.ManyToManyField( "self", through="FavoriteAuthors", symmetrical=False, related_name="favors_me" ) class Meta: ordering = ["id"] def __str__(self): return self.name class AuthorWithAge(Author): author = models.OneToOneField(Author, models.CASCADE, parent_link=True) age = models.IntegerField() class AuthorWithAgeChild(AuthorWithAge): pass class FavoriteAuthors(models.Model): author = models.ForeignKey( Author, models.CASCADE, to_field="name", related_name="i_like" ) likes_author = models.ForeignKey( Author, models.CASCADE, to_field="name", related_name="likes_me" ) is_active = models.BooleanField(default=True) class Meta: ordering = ["id"] class AuthorAddress(models.Model): author = models.ForeignKey( Author, models.CASCADE, to_field="name", related_name="addresses" ) address = models.TextField() class Meta: ordering = ["id"] class Book(models.Model): title = models.CharField(max_length=255) authors = models.ManyToManyField(Author, related_name="books") class Meta: ordering = ["id"] class BookWithYear(Book): book = models.OneToOneField(Book, models.CASCADE, parent_link=True) published_year = models.IntegerField() aged_authors = models.ManyToManyField(AuthorWithAge, related_name="books_with_year") class Bio(models.Model): author = models.OneToOneField( Author, models.CASCADE, primary_key=True, to_field="name", ) books = models.ManyToManyField(Book, blank=True) class Reader(models.Model): name = models.CharField(max_length=50) books_read = models.ManyToManyField(Book, related_name="read_by") class Meta: ordering = ["id"] def __str__(self): return self.name class BookReview(models.Model): # Intentionally does not have a related name. book = models.ForeignKey(BookWithYear, models.CASCADE, null=True) notes = models.TextField(null=True, blank=True) # Models for default manager tests class Qualification(models.Model): name = models.CharField(max_length=10) class Meta: ordering = ["id"] class ModelIterableSubclass(ModelIterable): pass class TeacherQuerySet(models.QuerySet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._iterable_class = ModelIterableSubclass class TeacherManager(models.Manager): def get_queryset(self): return super().get_queryset().prefetch_related("qualifications") class Teacher(models.Model): name = models.CharField(max_length=50) qualifications = models.ManyToManyField(Qualification) objects = TeacherManager() objects_custom = TeacherQuerySet.as_manager() class Meta: ordering = ["id"] def __str__(self): return "%s (%s)" % ( self.name, ", ".join(q.name for q in self.qualifications.all()), ) class Department(models.Model): name = models.CharField(max_length=50) teachers = models.ManyToManyField(Teacher) class Meta: ordering = ["id"] # GenericRelation/GenericForeignKey tests class TaggedItem(models.Model): tag = models.SlugField() content_type = models.ForeignKey( ContentType, models.CASCADE, related_name="taggeditem_set2", ) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") created_by_ct = models.ForeignKey( ContentType, models.SET_NULL, null=True, related_name="taggeditem_set3", ) created_by_fkey = models.PositiveIntegerField(null=True) created_by = GenericForeignKey( "created_by_ct", "created_by_fkey", ) favorite_ct = models.ForeignKey( ContentType, models.SET_NULL, null=True, related_name="taggeditem_set4", ) favorite_fkey = models.CharField(max_length=64, null=True) favorite = GenericForeignKey("favorite_ct", "favorite_fkey") class Meta: ordering = ["id"] class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=20) class Bookmark(models.Model): url = models.URLField() tags = GenericRelation(TaggedItem, related_query_name="bookmarks") favorite_tags = GenericRelation( TaggedItem, content_type_field="favorite_ct", object_id_field="favorite_fkey", related_query_name="favorite_bookmarks", ) class Meta: ordering = ["id"] class Comment(models.Model): comment = models.TextField() # Content-object field content_type = models.ForeignKey(ContentType, models.CASCADE, null=True) object_pk = models.TextField() content_object = GenericForeignKey(ct_field="content_type", fk_field="object_pk") content_type_uuid = models.ForeignKey( ContentType, models.CASCADE, related_name="comments", null=True ) object_pk_uuid = models.TextField() content_object_uuid = GenericForeignKey( ct_field="content_type_uuid", fk_field="object_pk_uuid" ) class Meta: ordering = ["id"] class ArticleCustomUUID(models.Model): class CustomUUIDField(models.UUIDField): def get_prep_value(self, value): return str(value) id = CustomUUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=30) # Models for lookup ordering tests class House(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=255) owner = models.ForeignKey("Person", models.SET_NULL, null=True) main_room = models.OneToOneField( "Room", models.SET_NULL, related_name="main_room_of", null=True ) class Meta: ordering = ["id"] class Room(models.Model): name = models.CharField(max_length=50) house = models.ForeignKey(House, models.CASCADE, related_name="rooms") class Meta: ordering = ["id"] class Person(models.Model): name = models.CharField(max_length=50) houses = models.ManyToManyField(House, related_name="occupants") @property def primary_house(self): # Assume business logic forces every person to have at least one house. return sorted(self.houses.all(), key=lambda house: -house.rooms.count())[0] @property def all_houses(self): return list(self.houses.all()) @cached_property def cached_all_houses(self): return self.all_houses class Meta: ordering = ["id"] # Models for nullable FK tests class Employee(models.Model): name = models.CharField(max_length=50) boss = models.ForeignKey("self", models.SET_NULL, null=True, related_name="serfs") class Meta: ordering = ["id"] class SelfDirectedEmployee(Employee): pass # Ticket #19607 class LessonEntry(models.Model): name1 = models.CharField(max_length=200) name2 = models.CharField(max_length=200) class WordEntry(models.Model): lesson_entry = models.ForeignKey(LessonEntry, models.CASCADE) name = models.CharField(max_length=200) # Ticket #21410: Regression when related_name="+" class Author2(models.Model): name = models.CharField(max_length=50, unique=True) first_book = models.ForeignKey( "Book", models.CASCADE, related_name="first_time_authors+" ) favorite_books = models.ManyToManyField("Book", related_name="+") class Meta: ordering = ["id"] # Models for many-to-many with UUID pk test: class Pet(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=20) people = models.ManyToManyField(Person, related_name="pets") class Flea(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) current_room = models.ForeignKey( Room, models.SET_NULL, related_name="fleas", null=True ) pets_visited = models.ManyToManyField(Pet, related_name="fleas_hosted") people_visited = models.ManyToManyField(Person, related_name="fleas_hosted")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/prefetch_related/test_prefetch_related_objects.py
tests/prefetch_related/test_prefetch_related_objects.py
from collections import deque from django.db.models import Prefetch, prefetch_related_objects from django.test import TestCase from .models import Author, Book, House, Reader, Room class PrefetchRelatedObjectsTests(TestCase): """ Since prefetch_related_objects() is just the inner part of prefetch_related(), only do basic tests to ensure its API hasn't changed. """ @classmethod def setUpTestData(cls): cls.book1 = Book.objects.create(title="Poems") cls.book2 = Book.objects.create(title="Jane Eyre") cls.book3 = Book.objects.create(title="Wuthering Heights") cls.book4 = Book.objects.create(title="Sense and Sensibility") cls.author1 = Author.objects.create(name="Charlotte", first_book=cls.book1) cls.author2 = Author.objects.create(name="Anne", first_book=cls.book1) cls.author3 = Author.objects.create(name="Emily", first_book=cls.book1) cls.author4 = Author.objects.create(name="Jane", first_book=cls.book4) cls.book1.authors.add(cls.author1, cls.author2, cls.author3) cls.book2.authors.add(cls.author1) cls.book3.authors.add(cls.author3) cls.book4.authors.add(cls.author4) cls.reader1 = Reader.objects.create(name="Amy") cls.reader2 = Reader.objects.create(name="Belinda") cls.reader1.books_read.add(cls.book1, cls.book4) cls.reader2.books_read.add(cls.book2, cls.book4) cls.house1 = House.objects.create(name="b1", address="1") cls.house2 = House.objects.create(name="b2", address="2") cls.room1 = Room.objects.create(name="a1", house=cls.house1) cls.room2 = Room.objects.create(name="a2", house=cls.house2) cls.house1.main_room = cls.room1 cls.house1.save() cls.house2.main_room = cls.room2 cls.house2.save() def test_unknown(self): book1 = Book.objects.get(id=self.book1.id) with self.assertRaises(AttributeError): prefetch_related_objects([book1], "unknown_attribute") def test_m2m_forward(self): book1 = Book.objects.get(id=self.book1.id) with self.assertNumQueries(1): prefetch_related_objects([book1], "authors") with self.assertNumQueries(0): self.assertCountEqual( book1.authors.all(), [self.author1, self.author2, self.author3] ) def test_m2m_reverse(self): author1 = Author.objects.get(id=self.author1.id) with self.assertNumQueries(1): prefetch_related_objects([author1], "books") with self.assertNumQueries(0): self.assertCountEqual(author1.books.all(), [self.book1, self.book2]) def test_foreignkey_forward(self): authors = list(Author.objects.all()) with self.assertNumQueries(1) as ctx: prefetch_related_objects(authors, "first_book") self.assertNotIn("ORDER BY", ctx.captured_queries[0]["sql"]) with self.assertNumQueries(0): [author.first_book for author in authors] authors = list(Author.objects.all()) with self.assertNumQueries(1) as ctx: prefetch_related_objects( authors, Prefetch("first_book", queryset=Book.objects.order_by("-title")), ) self.assertNotIn("ORDER BY", ctx.captured_queries[0]["sql"]) def test_foreignkey_reverse(self): books = list(Book.objects.all()) with self.assertNumQueries(1) as ctx: prefetch_related_objects(books, "first_time_authors") self.assertIn("ORDER BY", ctx.captured_queries[0]["sql"]) with self.assertNumQueries(0): [list(book.first_time_authors.all()) for book in books] books = list(Book.objects.all()) with self.assertNumQueries(1) as ctx: prefetch_related_objects( books, Prefetch( "first_time_authors", queryset=Author.objects.order_by("-name"), ), ) self.assertIn("ORDER BY", ctx.captured_queries[0]["sql"]) def test_one_to_one_forward(self): houses = list(House.objects.all()) with self.assertNumQueries(1) as ctx: prefetch_related_objects(houses, "main_room") self.assertNotIn("ORDER BY", ctx.captured_queries[0]["sql"]) with self.assertNumQueries(0): [house.main_room for house in houses] houses = list(House.objects.all()) with self.assertNumQueries(1) as ctx: prefetch_related_objects( houses, Prefetch("main_room", queryset=Room.objects.order_by("-name")), ) self.assertNotIn("ORDER BY", ctx.captured_queries[0]["sql"]) def test_one_to_one_reverse(self): rooms = list(Room.objects.all()) with self.assertNumQueries(1) as ctx: prefetch_related_objects(rooms, "main_room_of") self.assertNotIn("ORDER BY", ctx.captured_queries[0]["sql"]) with self.assertNumQueries(0): [room.main_room_of for room in rooms] rooms = list(Room.objects.all()) with self.assertNumQueries(1) as ctx: prefetch_related_objects( rooms, Prefetch("main_room_of", queryset=House.objects.order_by("-name")), ) self.assertNotIn("ORDER BY", ctx.captured_queries[0]["sql"]) def test_m2m_then_m2m(self): """A m2m can be followed through another m2m.""" authors = list(Author.objects.all()) with self.assertNumQueries(2): prefetch_related_objects(authors, "books__read_by") with self.assertNumQueries(0): self.assertEqual( [ [[str(r) for r in b.read_by.all()] for b in a.books.all()] for a in authors ], [ [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre [["Amy"]], # Anne - Poems [["Amy"], []], # Emily - Poems, Wuthering Heights [["Amy", "Belinda"]], # Jane - Sense and Sense ], ) def test_prefetch_object(self): book1 = Book.objects.get(id=self.book1.id) with self.assertNumQueries(1): prefetch_related_objects([book1], Prefetch("authors")) with self.assertNumQueries(0): self.assertCountEqual( book1.authors.all(), [self.author1, self.author2, self.author3] ) def test_prefetch_object_twice(self): book1 = Book.objects.get(id=self.book1.id) book2 = Book.objects.get(id=self.book2.id) with self.assertNumQueries(1): prefetch_related_objects([book1], Prefetch("authors")) with self.assertNumQueries(1): prefetch_related_objects([book1, book2], Prefetch("authors")) with self.assertNumQueries(0): self.assertCountEqual(book2.authors.all(), [self.author1]) def test_prefetch_object_to_attr(self): book1 = Book.objects.get(id=self.book1.id) with self.assertNumQueries(1): prefetch_related_objects( [book1], Prefetch("authors", to_attr="the_authors") ) with self.assertNumQueries(0): self.assertCountEqual( book1.the_authors, [self.author1, self.author2, self.author3] ) def test_prefetch_object_to_attr_twice(self): book1 = Book.objects.get(id=self.book1.id) book2 = Book.objects.get(id=self.book2.id) with self.assertNumQueries(1): prefetch_related_objects( [book1], Prefetch("authors", to_attr="the_authors"), ) with self.assertNumQueries(1): prefetch_related_objects( [book1, book2], Prefetch("authors", to_attr="the_authors"), ) with self.assertNumQueries(0): self.assertCountEqual(book2.the_authors, [self.author1]) def test_prefetch_queryset(self): book1 = Book.objects.get(id=self.book1.id) with self.assertNumQueries(1): prefetch_related_objects( [book1], Prefetch( "authors", queryset=Author.objects.filter( id__in=[self.author1.id, self.author2.id] ), ), ) with self.assertNumQueries(0): self.assertCountEqual(book1.authors.all(), [self.author1, self.author2]) def test_prefetch_related_objects_with_various_iterables(self): book = self.book1 class MyIterable: def __iter__(self): yield book cases = { "set": {book}, "tuple": (book,), "dict_values": {"a": book}.values(), "frozenset": frozenset([book]), "deque": deque([book]), "custom iterator": MyIterable(), } for case_type, case in cases.items(): with self.subTest(case=case_type): # Clear the prefetch cache. book._prefetched_objects_cache = {} with self.assertNumQueries(1): prefetch_related_objects(case, "authors") with self.assertNumQueries(0): self.assertCountEqual( book.authors.all(), [self.author1, self.author2, self.author3] ) def test_prefetch_related_objects_empty(self): prefetch_related_objects([], "authors")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/prefetch_related/__init__.py
tests/prefetch_related/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/prefetch_related/tests.py
tests/prefetch_related/tests.py
from unittest import mock from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectDoesNotExist from django.db import NotSupportedError, connection from django.db.models import ( FETCH_PEERS, F, Prefetch, QuerySet, prefetch_related_objects, ) from django.db.models.fetch_modes import RAISE from django.db.models.query import get_prefetcher from django.db.models.sql import Query from django.test import ( TestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.utils import CaptureQueriesContext from .models import ( Article, ArticleCustomUUID, Author, Author2, AuthorAddress, AuthorWithAge, AuthorWithAgeChild, Bio, Book, Bookmark, BookReview, BookWithYear, Comment, Department, Employee, FavoriteAuthors, House, LessonEntry, ModelIterableSubclass, Person, Qualification, Reader, Room, SelfDirectedEmployee, TaggedItem, Teacher, WordEntry, ) class TestDataMixin: @classmethod def setUpTestData(cls): cls.book1 = Book.objects.create(title="Poems") cls.book2 = Book.objects.create(title="Jane Eyre") cls.book3 = Book.objects.create(title="Wuthering Heights") cls.book4 = Book.objects.create(title="Sense and Sensibility") cls.author1 = Author.objects.create(name="Charlotte", first_book=cls.book1) cls.author2 = Author.objects.create(name="Anne", first_book=cls.book1) cls.author3 = Author.objects.create(name="Emily", first_book=cls.book1) cls.author4 = Author.objects.create(name="Jane", first_book=cls.book4) cls.book1.authors.add(cls.author1, cls.author2, cls.author3) cls.book2.authors.add(cls.author1) cls.book3.authors.add(cls.author3) cls.book4.authors.add(cls.author4) cls.reader1 = Reader.objects.create(name="Amy") cls.reader2 = Reader.objects.create(name="Belinda") cls.reader1.books_read.add(cls.book1, cls.book4) cls.reader2.books_read.add(cls.book2, cls.book4) class PrefetchRelatedTests(TestDataMixin, TestCase): def assertWhereContains(self, sql, needle): where_idx = sql.index("WHERE") self.assertEqual( sql.count(str(needle), where_idx), 1, msg="WHERE clause doesn't contain %s, actual SQL: %s" % (needle, sql[where_idx:]), ) def test_m2m_forward(self): with self.assertNumQueries(2): lists = [ list(b.authors.all()) for b in Book.objects.prefetch_related("authors") ] normal_lists = [list(b.authors.all()) for b in Book.objects.all()] self.assertEqual(lists, normal_lists) def test_m2m_reverse(self): with self.assertNumQueries(2): lists = [ list(a.books.all()) for a in Author.objects.prefetch_related("books") ] normal_lists = [list(a.books.all()) for a in Author.objects.all()] self.assertEqual(lists, normal_lists) def test_foreignkey_forward(self): with self.assertNumQueries(2): books = [ a.first_book for a in Author.objects.prefetch_related("first_book") ] normal_books = [a.first_book for a in Author.objects.all()] self.assertEqual(books, normal_books) def test_fetch_mode_copied_fetching_one(self): author = ( Author.objects.fetch_mode(FETCH_PEERS) .prefetch_related("first_book") .get(pk=self.author1.pk) ) self.assertEqual(author._state.fetch_mode, FETCH_PEERS) self.assertEqual( author.first_book._state.fetch_mode, FETCH_PEERS, ) def test_fetch_mode_copied_fetching_many(self): authors = list( Author.objects.fetch_mode(FETCH_PEERS).prefetch_related("first_book") ) self.assertEqual(authors[0]._state.fetch_mode, FETCH_PEERS) self.assertEqual( authors[0].first_book._state.fetch_mode, FETCH_PEERS, ) def test_fetch_mode_raise(self): authors = list(Author.objects.fetch_mode(RAISE).prefetch_related("first_book")) authors[0].first_book # No exception, already loaded def test_foreignkey_reverse(self): with self.assertNumQueries(2): [ list(b.first_time_authors.all()) for b in Book.objects.prefetch_related("first_time_authors") ] self.assertSequenceEqual(self.book2.authors.all(), [self.author1]) def test_onetoone_reverse_no_match(self): # Regression for #17439 with self.assertNumQueries(2): book = Book.objects.prefetch_related("bookwithyear").all()[0] with self.assertNumQueries(0): with self.assertRaises(BookWithYear.DoesNotExist): book.bookwithyear def test_onetoone_reverse_with_to_field_pk(self): """ A model (Bio) with a OneToOneField primary key (author) that references a non-pk field (name) on the related model (Author) is prefetchable. """ Bio.objects.bulk_create( [ Bio(author=self.author1), Bio(author=self.author2), Bio(author=self.author3), ] ) authors = Author.objects.filter( name__in=[self.author1, self.author2, self.author3], ).prefetch_related("bio") with self.assertNumQueries(2): for author in authors: self.assertEqual(author.name, author.bio.author.name) def test_survives_clone(self): with self.assertNumQueries(2): [ list(b.first_time_authors.all()) for b in Book.objects.prefetch_related("first_time_authors").exclude( id=1000 ) ] def test_len(self): with self.assertNumQueries(2): qs = Book.objects.prefetch_related("first_time_authors") len(qs) [list(b.first_time_authors.all()) for b in qs] def test_bool(self): with self.assertNumQueries(2): qs = Book.objects.prefetch_related("first_time_authors") bool(qs) [list(b.first_time_authors.all()) for b in qs] def test_count(self): with self.assertNumQueries(2): qs = Book.objects.prefetch_related("first_time_authors") [b.first_time_authors.count() for b in qs] def test_exists(self): with self.assertNumQueries(2): qs = Book.objects.prefetch_related("first_time_authors") [b.first_time_authors.exists() for b in qs] def test_in_and_prefetch_related(self): """ Regression test for #20242 - QuerySet "in" didn't work the first time when using prefetch_related. This was fixed by the removal of chunked reads from QuerySet iteration in 70679243d1786e03557c28929f9762a119e3ac14. """ qs = Book.objects.prefetch_related("first_time_authors") self.assertIn(qs[0], qs) def test_clear(self): with self.assertNumQueries(5): with_prefetch = Author.objects.prefetch_related("books") without_prefetch = with_prefetch.prefetch_related(None) [list(a.books.all()) for a in without_prefetch] def test_m2m_then_m2m(self): """A m2m can be followed through another m2m.""" with self.assertNumQueries(3): qs = Author.objects.prefetch_related("books__read_by") lists = [ [[str(r) for r in b.read_by.all()] for b in a.books.all()] for a in qs ] self.assertEqual( lists, [ [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre [["Amy"]], # Anne - Poems [["Amy"], []], # Emily - Poems, Wuthering Heights [["Amy", "Belinda"]], # Jane - Sense and Sense ], ) def test_overriding_prefetch(self): with self.assertNumQueries(3): qs = Author.objects.prefetch_related("books", "books__read_by") lists = [ [[str(r) for r in b.read_by.all()] for b in a.books.all()] for a in qs ] self.assertEqual( lists, [ [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre [["Amy"]], # Anne - Poems [["Amy"], []], # Emily - Poems, Wuthering Heights [["Amy", "Belinda"]], # Jane - Sense and Sense ], ) with self.assertNumQueries(3): qs = Author.objects.prefetch_related("books__read_by", "books") lists = [ [[str(r) for r in b.read_by.all()] for b in a.books.all()] for a in qs ] self.assertEqual( lists, [ [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre [["Amy"]], # Anne - Poems [["Amy"], []], # Emily - Poems, Wuthering Heights [["Amy", "Belinda"]], # Jane - Sense and Sense ], ) def test_get(self): """ Objects retrieved with .get() get the prefetch behavior. """ # Need a double with self.assertNumQueries(3): author = Author.objects.prefetch_related("books__read_by").get( name="Charlotte" ) lists = [[str(r) for r in b.read_by.all()] for b in author.books.all()] self.assertEqual(lists, [["Amy"], ["Belinda"]]) # Poems, Jane Eyre def test_foreign_key_then_m2m(self): """ A m2m relation can be followed after a relation like ForeignKey that doesn't have many objects. """ with self.assertNumQueries(2): qs = Author.objects.select_related("first_book").prefetch_related( "first_book__read_by" ) lists = [[str(r) for r in a.first_book.read_by.all()] for a in qs] self.assertEqual(lists, [["Amy"], ["Amy"], ["Amy"], ["Amy", "Belinda"]]) def test_reverse_one_to_one_then_m2m(self): """ A m2m relation can be followed after going through the select_related reverse of an o2o. """ qs = Author.objects.prefetch_related("bio__books").select_related("bio") with self.assertNumQueries(1): list(qs.all()) Bio.objects.create(author=self.author1) with self.assertNumQueries(2): list(qs.all()) def test_attribute_error(self): qs = Reader.objects.prefetch_related("books_read__xyz") msg = ( "Cannot find 'xyz' on Book object, 'books_read__xyz' " "is an invalid parameter to prefetch_related()" ) with self.assertRaisesMessage(AttributeError, msg) as cm: list(qs) self.assertIn("prefetch_related", str(cm.exception)) def test_invalid_final_lookup(self): qs = Book.objects.prefetch_related("authors__name") msg = ( "'authors__name' does not resolve to an item that supports " "prefetching - this is an invalid parameter to prefetch_related()." ) with self.assertRaisesMessage(ValueError, msg) as cm: list(qs) self.assertIn("prefetch_related", str(cm.exception)) self.assertIn("name", str(cm.exception)) def test_prefetch_eq(self): prefetch_1 = Prefetch("authors", queryset=Author.objects.all()) prefetch_2 = Prefetch("books", queryset=Book.objects.all()) self.assertEqual(prefetch_1, prefetch_1) self.assertEqual(prefetch_1, mock.ANY) self.assertNotEqual(prefetch_1, prefetch_2) def test_forward_m2m_to_attr_conflict(self): msg = "to_attr=authors conflicts with a field on the Book model." authors = Author.objects.all() with self.assertRaisesMessage(ValueError, msg): list( Book.objects.prefetch_related( Prefetch("authors", queryset=authors, to_attr="authors"), ) ) # Without the ValueError, an author was deleted due to the implicit # save of the relation assignment. self.assertEqual(self.book1.authors.count(), 3) def test_reverse_m2m_to_attr_conflict(self): msg = "to_attr=books conflicts with a field on the Author model." poems = Book.objects.filter(title="Poems") with self.assertRaisesMessage(ValueError, msg): list( Author.objects.prefetch_related( Prefetch("books", queryset=poems, to_attr="books"), ) ) # Without the ValueError, a book was deleted due to the implicit # save of reverse relation assignment. self.assertEqual(self.author1.books.count(), 2) def test_m2m_then_reverse_fk_object_ids(self): with CaptureQueriesContext(connection) as queries: list(Book.objects.prefetch_related("authors__addresses")) sql = queries[-1]["sql"] self.assertWhereContains(sql, self.author1.name) def test_m2m_then_m2m_object_ids(self): with CaptureQueriesContext(connection) as queries: list(Book.objects.prefetch_related("authors__favorite_authors")) sql = queries[-1]["sql"] self.assertWhereContains(sql, self.author1.name) def test_m2m_then_reverse_one_to_one_object_ids(self): with CaptureQueriesContext(connection) as queries: list(Book.objects.prefetch_related("authors__authorwithage")) sql = queries[-1]["sql"] self.assertWhereContains(sql, self.author1.id) def test_filter_deferred(self): """ Related filtering of prefetched querysets is deferred on m2m and reverse m2o relations until necessary. """ add_q = Query.add_q for relation in ["authors", "first_time_authors"]: with self.subTest(relation=relation): with mock.patch.object( Query, "add_q", autospec=True, side_effect=lambda self, q, reuse_all: add_q(self, q), ) as add_q_mock: list(Book.objects.prefetch_related(relation)) self.assertEqual(add_q_mock.call_count, 1) def test_named_values_list(self): qs = Author.objects.prefetch_related("books") self.assertCountEqual( [value.name for value in qs.values_list("name", named=True)], ["Anne", "Charlotte", "Emily", "Jane"], ) def test_m2m_prefetching_iterator_with_chunks(self): with self.assertNumQueries(3): authors = [ b.authors.first() for b in Book.objects.prefetch_related("authors").iterator(chunk_size=2) ] self.assertEqual( authors, [self.author1, self.author1, self.author3, self.author4], ) def test_m2m_prefetching_iterator_without_chunks_error(self): msg = ( "chunk_size must be provided when using QuerySet.iterator() after " "prefetch_related()." ) with self.assertRaisesMessage(ValueError, msg): Book.objects.prefetch_related("authors").iterator() def test_m2m_join_reuse(self): FavoriteAuthors.objects.bulk_create( [ FavoriteAuthors( author=self.author1, likes_author=self.author3, is_active=True ), FavoriteAuthors( author=self.author1, likes_author=self.author4, is_active=False, ), FavoriteAuthors( author=self.author2, likes_author=self.author3, is_active=True ), FavoriteAuthors( author=self.author2, likes_author=self.author4, is_active=True ), ] ) with self.assertNumQueries(2): authors = list( Author.objects.filter( pk__in=[self.author1.pk, self.author2.pk] ).prefetch_related( Prefetch( "favorite_authors", queryset=( Author.objects.annotate( active_favorite=F("likes_me__is_active"), ).filter(active_favorite=True) ), to_attr="active_favorite_authors", ) ) ) self.assertEqual(authors[0].active_favorite_authors, [self.author3]) self.assertEqual( authors[1].active_favorite_authors, [self.author3, self.author4] ) def test_prefetch_queryset_child_class(self): employee = SelfDirectedEmployee.objects.create(name="Foo") employee.boss = employee employee.save() with self.assertNumQueries(2): retrieved_employee = SelfDirectedEmployee.objects.prefetch_related( Prefetch("boss", SelfDirectedEmployee.objects.all()) ).get() with self.assertNumQueries(0): self.assertEqual(retrieved_employee, employee) self.assertEqual(retrieved_employee.boss, retrieved_employee) class RawQuerySetTests(TestDataMixin, TestCase): def test_basic(self): with self.assertNumQueries(2): books = Book.objects.raw( "SELECT * FROM prefetch_related_book WHERE id = %s", (self.book1.id,) ).prefetch_related("authors") book1 = list(books)[0] with self.assertNumQueries(0): self.assertCountEqual( book1.authors.all(), [self.author1, self.author2, self.author3] ) def test_prefetch_before_raw(self): with self.assertNumQueries(2): books = Book.objects.prefetch_related("authors").raw( "SELECT * FROM prefetch_related_book WHERE id = %s", (self.book1.id,) ) book1 = list(books)[0] with self.assertNumQueries(0): self.assertCountEqual( book1.authors.all(), [self.author1, self.author2, self.author3] ) def test_clear(self): with self.assertNumQueries(5): with_prefetch = Author.objects.raw( "SELECT * FROM prefetch_related_author" ).prefetch_related("books") without_prefetch = with_prefetch.prefetch_related(None) [list(a.books.all()) for a in without_prefetch] class CustomPrefetchTests(TestCase): @classmethod def traverse_qs(cls, obj_iter, path): """ Helper method that returns a list containing a list of the objects in the obj_iter. Then for each object in the obj_iter, the path will be recursively travelled and the found objects are added to the return value. """ ret_val = [] if hasattr(obj_iter, "all"): obj_iter = obj_iter.all() try: iter(obj_iter) except TypeError: obj_iter = [obj_iter] for obj in obj_iter: rel_objs = [] for part in path: if not part: continue try: related = getattr(obj, part[0]) except ObjectDoesNotExist: continue if related is not None: rel_objs.extend(cls.traverse_qs(related, [part[1:]])) ret_val.append((obj, rel_objs)) return ret_val @classmethod def setUpTestData(cls): cls.person1 = Person.objects.create(name="Joe") cls.person2 = Person.objects.create(name="Mary") # Set main_room for each house before creating the next one for # databases where supports_nullable_unique_constraints is False. cls.house1 = House.objects.create( name="House 1", address="123 Main St", owner=cls.person1 ) cls.room1_1 = Room.objects.create(name="Dining room", house=cls.house1) cls.room1_2 = Room.objects.create(name="Lounge", house=cls.house1) cls.room1_3 = Room.objects.create(name="Kitchen", house=cls.house1) cls.house1.main_room = cls.room1_1 cls.house1.save() cls.person1.houses.add(cls.house1) cls.house2 = House.objects.create( name="House 2", address="45 Side St", owner=cls.person1 ) cls.room2_1 = Room.objects.create(name="Dining room", house=cls.house2) cls.room2_2 = Room.objects.create(name="Lounge", house=cls.house2) cls.room2_3 = Room.objects.create(name="Kitchen", house=cls.house2) cls.house2.main_room = cls.room2_1 cls.house2.save() cls.person1.houses.add(cls.house2) cls.house3 = House.objects.create( name="House 3", address="6 Downing St", owner=cls.person2 ) cls.room3_1 = Room.objects.create(name="Dining room", house=cls.house3) cls.room3_2 = Room.objects.create(name="Lounge", house=cls.house3) cls.room3_3 = Room.objects.create(name="Kitchen", house=cls.house3) cls.house3.main_room = cls.room3_1 cls.house3.save() cls.person2.houses.add(cls.house3) cls.house4 = House.objects.create( name="house 4", address="7 Regents St", owner=cls.person2 ) cls.room4_1 = Room.objects.create(name="Dining room", house=cls.house4) cls.room4_2 = Room.objects.create(name="Lounge", house=cls.house4) cls.room4_3 = Room.objects.create(name="Kitchen", house=cls.house4) cls.house4.main_room = cls.room4_1 cls.house4.save() cls.person2.houses.add(cls.house4) def test_traverse_qs(self): qs = Person.objects.prefetch_related("houses") related_objs_normal = ([list(p.houses.all()) for p in qs],) related_objs_from_traverse = [ [inner[0] for inner in o[1]] for o in self.traverse_qs(qs, [["houses"]]) ] self.assertEqual(related_objs_normal, (related_objs_from_traverse,)) def test_ambiguous(self): # Ambiguous: Lookup was already seen with a different queryset. msg = ( "'houses' lookup was already seen with a different queryset. You " "may need to adjust the ordering of your lookups." ) # lookup.queryset shouldn't be evaluated. with self.assertNumQueries(3): with self.assertRaisesMessage(ValueError, msg): self.traverse_qs( Person.objects.prefetch_related( "houses__rooms", Prefetch("houses", queryset=House.objects.all()), ), [["houses", "rooms"]], ) # Ambiguous: Lookup houses_lst doesn't yet exist when performing # houses_lst__rooms. msg = ( "Cannot find 'houses_lst' on Person object, 'houses_lst__rooms' is " "an invalid parameter to prefetch_related()" ) with self.assertRaisesMessage(AttributeError, msg): self.traverse_qs( Person.objects.prefetch_related( "houses_lst__rooms", Prefetch( "houses", queryset=House.objects.all(), to_attr="houses_lst" ), ), [["houses", "rooms"]], ) # Not ambiguous. self.traverse_qs( Person.objects.prefetch_related("houses__rooms", "houses"), [["houses", "rooms"]], ) self.traverse_qs( Person.objects.prefetch_related( "houses__rooms", Prefetch("houses", queryset=House.objects.all(), to_attr="houses_lst"), ), [["houses", "rooms"]], ) def test_m2m(self): # Control lookups. with self.assertNumQueries(2): lst1 = self.traverse_qs( Person.objects.prefetch_related("houses"), [["houses"]] ) # Test lookups. with self.assertNumQueries(2): lst2 = self.traverse_qs( Person.objects.prefetch_related(Prefetch("houses")), [["houses"]] ) self.assertEqual(lst1, lst2) with self.assertNumQueries(2): lst2 = self.traverse_qs( Person.objects.prefetch_related( Prefetch("houses", to_attr="houses_lst") ), [["houses_lst"]], ) self.assertEqual(lst1, lst2) def test_reverse_m2m(self): # Control lookups. with self.assertNumQueries(2): lst1 = self.traverse_qs( House.objects.prefetch_related("occupants"), [["occupants"]] ) # Test lookups. with self.assertNumQueries(2): lst2 = self.traverse_qs( House.objects.prefetch_related(Prefetch("occupants")), [["occupants"]] ) self.assertEqual(lst1, lst2) with self.assertNumQueries(2): lst2 = self.traverse_qs( House.objects.prefetch_related( Prefetch("occupants", to_attr="occupants_lst") ), [["occupants_lst"]], ) self.assertEqual(lst1, lst2) def test_m2m_through_fk(self): # Control lookups. with self.assertNumQueries(3): lst1 = self.traverse_qs( Room.objects.prefetch_related("house__occupants"), [["house", "occupants"]], ) # Test lookups. with self.assertNumQueries(3): lst2 = self.traverse_qs( Room.objects.prefetch_related(Prefetch("house__occupants")), [["house", "occupants"]], ) self.assertEqual(lst1, lst2) with self.assertNumQueries(3): lst2 = self.traverse_qs( Room.objects.prefetch_related( Prefetch("house__occupants", to_attr="occupants_lst") ), [["house", "occupants_lst"]], ) self.assertEqual(lst1, lst2) def test_m2m_through_gfk(self): TaggedItem.objects.create(tag="houses", content_object=self.house1) TaggedItem.objects.create(tag="houses", content_object=self.house2) # Control lookups. with self.assertNumQueries(3): lst1 = self.traverse_qs( TaggedItem.objects.filter(tag="houses").prefetch_related( "content_object__rooms" ), [["content_object", "rooms"]], ) # Test lookups. with self.assertNumQueries(3): lst2 = self.traverse_qs( TaggedItem.objects.prefetch_related( Prefetch("content_object"), Prefetch("content_object__rooms", to_attr="rooms_lst"), ), [["content_object", "rooms_lst"]], ) self.assertEqual(lst1, lst2) def test_o2m_through_m2m(self): # Control lookups. with self.assertNumQueries(3): lst1 = self.traverse_qs( Person.objects.prefetch_related("houses", "houses__rooms"), [["houses", "rooms"]], ) # Test lookups. with self.assertNumQueries(3): lst2 = self.traverse_qs( Person.objects.prefetch_related(Prefetch("houses"), "houses__rooms"), [["houses", "rooms"]], ) self.assertEqual(lst1, lst2) with self.assertNumQueries(3): lst2 = self.traverse_qs( Person.objects.prefetch_related( Prefetch("houses"), Prefetch("houses__rooms") ), [["houses", "rooms"]], ) self.assertEqual(lst1, lst2) with self.assertNumQueries(3): lst2 = self.traverse_qs( Person.objects.prefetch_related( Prefetch("houses", to_attr="houses_lst"), "houses_lst__rooms" ), [["houses_lst", "rooms"]], ) self.assertEqual(lst1, lst2) with self.assertNumQueries(3): lst2 = self.traverse_qs( Person.objects.prefetch_related( Prefetch("houses", to_attr="houses_lst"), Prefetch("houses_lst__rooms", to_attr="rooms_lst"), ), [["houses_lst", "rooms_lst"]], ) self.assertEqual(lst1, lst2) def test_generic_rel(self): bookmark = Bookmark.objects.create(url="http://www.djangoproject.com/") TaggedItem.objects.create(content_object=bookmark, tag="django") TaggedItem.objects.create( content_object=bookmark, favorite=bookmark, tag="python" ) # Control lookups. with self.assertNumQueries(4): lst1 = self.traverse_qs( Bookmark.objects.prefetch_related( "tags", "tags__content_object", "favorite_tags" ), [["tags", "content_object"], ["favorite_tags"]], ) # Test lookups. with self.assertNumQueries(4): lst2 = self.traverse_qs( Bookmark.objects.prefetch_related( Prefetch("tags", to_attr="tags_lst"), Prefetch("tags_lst__content_object"), Prefetch("favorite_tags"), ), [["tags_lst", "content_object"], ["favorite_tags"]], ) self.assertEqual(lst1, lst2) def test_traverse_single_item_property(self): # Control lookups. with self.assertNumQueries(5): lst1 = self.traverse_qs( Person.objects.prefetch_related( "houses__rooms", "primary_house__occupants__houses", ), [["primary_house", "occupants", "houses"]], ) # Test lookups. with self.assertNumQueries(5): lst2 = self.traverse_qs( Person.objects.prefetch_related( "houses__rooms", Prefetch("primary_house__occupants", to_attr="occupants_lst"), "primary_house__occupants_lst__houses", ), [["primary_house", "occupants_lst", "houses"]], ) self.assertEqual(lst1, lst2) def test_traverse_multiple_items_property(self): # Control lookups. with self.assertNumQueries(4): lst1 = self.traverse_qs( Person.objects.prefetch_related( "houses", "all_houses__occupants__houses", ), [["all_houses", "occupants", "houses"]], ) # Test lookups. with self.assertNumQueries(4): lst2 = self.traverse_qs( Person.objects.prefetch_related( "houses", Prefetch("all_houses__occupants", to_attr="occupants_lst"), "all_houses__occupants_lst__houses", ), [["all_houses", "occupants_lst", "houses"]], ) self.assertEqual(lst1, lst2) def test_custom_qs(self): # Test basic. with self.assertNumQueries(2): lst1 = list(Person.objects.prefetch_related("houses")) with self.assertNumQueries(2): lst2 = list( Person.objects.prefetch_related( Prefetch( "houses", queryset=House.objects.all(), to_attr="houses_lst" ) ) ) self.assertEqual( self.traverse_qs(lst1, [["houses"]]), self.traverse_qs(lst2, [["houses_lst"]]), ) # Test queryset filtering. with self.assertNumQueries(2): lst2 = list( Person.objects.prefetch_related( Prefetch( "houses", queryset=House.objects.filter(
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/deprecation/test_deprecate_posargs.py
tests/deprecation/test_deprecate_posargs.py
import inspect from django.test import SimpleTestCase from django.utils.deprecation import RemovedAfterNextVersionWarning, deprecate_posargs class DeprecatePosargsTests(SimpleTestCase): # Note: these tests use the generic RemovedAfterNextVersionWarning so they # don't need to be updated each release. In actual use, you must substitute # a specific RemovedInDjangoXXWarning. def assertDeprecated(self, params, name): msg = ( "Passing positional argument(s) {0} to {1}() is deprecated. Use keyword " "arguments instead." ) return self.assertWarnsMessage( RemovedAfterNextVersionWarning, msg.format(params, name) ) def test_all_keyword_only_params(self): """All positional arguments are remapped to keyword-only arguments.""" @deprecate_posargs(RemovedAfterNextVersionWarning, ["a", "b"]) def some_func(*, a=1, b=2): return a, b with ( self.subTest("Multiple affected args"), self.assertDeprecated("'a', 'b'", "some_func"), ): result = some_func(10, 20) self.assertEqual(result, (10, 20)) with ( self.subTest("One affected arg"), self.assertDeprecated("'a'", "some_func"), ): result = some_func(10) self.assertEqual(result, (10, 2)) def test_some_keyword_only_params(self): """Works when keeping some params as positional-or-keyword.""" @deprecate_posargs(RemovedAfterNextVersionWarning, ["b"]) def some_func(a, *, b=1): return a, b with self.assertDeprecated("'b'", "some_func"): result = some_func(10, 20) self.assertEqual(result, (10, 20)) def test_no_warning_when_not_needed(self): @deprecate_posargs(RemovedAfterNextVersionWarning, ["b"]) def some_func(a=0, *, b=1): return a, b with self.subTest("All arguments supplied"), self.assertNoLogs(level="WARNING"): result = some_func(10, b=20) self.assertEqual(result, (10, 20)) with self.subTest("All default arguments"), self.assertNoLogs(level="WARNING"): result = some_func() self.assertEqual(result, (0, 1)) with ( self.subTest("Partial arguments supplied"), self.assertNoLogs(level="WARNING"), ): result = some_func(10) self.assertEqual(result, (10, 1)) def test_allows_reordering_keyword_only_params(self): """Keyword-only params can be freely added and rearranged.""" # Original signature: some_func(b=2, a=1), and remappable_names # reflects the original positional argument order. @deprecate_posargs(RemovedAfterNextVersionWarning, ["b", "a"]) def some_func(*, aa_new=0, a=1, b=2): return aa_new, a, b with self.assertDeprecated("'b', 'a'", "some_func"): result = some_func(20, 10) self.assertEqual(result, (0, 10, 20)) def test_detects_duplicate_arguments(self): @deprecate_posargs(RemovedAfterNextVersionWarning, ["b", "c"]) def func(a, *, b=1, c=2): return a, b, c msg = ( "func() got both deprecated positional and keyword argument values for {0}" ) with ( self.subTest("One duplicate"), self.assertRaisesMessage(TypeError, msg.format("'b'")), ): func(0, 10, b=12) with ( self.subTest("Multiple duplicates"), self.assertRaisesMessage(TypeError, msg.format("'b', 'c'")), ): func(0, 10, 20, b=12, c=22) with ( self.subTest("No false positives for valid kwargs"), # Deprecation warning for 'b', not TypeError for duplicate 'c'. self.assertDeprecated("'b'", "func"), ): result = func(0, 11, c=22) self.assertEqual(result, (0, 11, 22)) def test_detects_extra_positional_arguments(self): @deprecate_posargs(RemovedAfterNextVersionWarning, ["b"]) def func(a, *, b=1): return a, b with self.assertRaisesMessage( TypeError, "func() takes at most 2 positional argument(s) (including 1 deprecated) " "but 3 were given.", ): func(10, 20, 30) def test_avoids_remapping_to_new_keyword_arguments(self): # Only 'b' is moving; 'c' was added later. @deprecate_posargs(RemovedAfterNextVersionWarning, ["b"]) def func(a, *, b=1, c=2): return a, b, c with self.assertRaisesMessage( TypeError, "func() takes at most 2 positional argument(s) (including 1 deprecated) " "but 3 were given.", ): func(10, 20, 30) def test_variable_kwargs(self): """Works with **kwargs.""" @deprecate_posargs(RemovedAfterNextVersionWarning, ["b"]) def some_func(a, *, b=1, **kwargs): return a, b, kwargs with ( self.subTest("Called with additional kwargs"), self.assertDeprecated("'b'", "some_func"), ): result = some_func(10, 20, c=30) self.assertEqual(result, (10, 20, {"c": 30})) with ( self.subTest("Called without additional kwargs"), self.assertDeprecated("'b'", "some_func"), ): result = some_func(10, 20) self.assertEqual(result, (10, 20, {})) with ( self.subTest("Called with too many positional arguments"), # Similar to test_detects_extra_positional_arguments() above, # but verifying logic is not confused by variable **kwargs. self.assertRaisesMessage( TypeError, "some_func() takes at most 2 positional argument(s) (including 1 " "deprecated) but 3 were given.", ), ): some_func(10, 20, 30) with self.subTest("No warning needed"): result = some_func(10, b=20, c=30) self.assertEqual(result, (10, 20, {"c": 30})) def test_positional_only_params(self): @deprecate_posargs(RemovedAfterNextVersionWarning, ["c"]) def some_func(a, /, b, *, c=3): return a, b, c with self.assertDeprecated("'c'", "some_func"): result = some_func(10, 20, 30) self.assertEqual(result, (10, 20, 30)) def test_class_methods(self): """ Deprecations for class methods should be bound properly and should omit the `self` or `cls` argument from the suggested replacement. """ class SomeClass: @deprecate_posargs(RemovedAfterNextVersionWarning, ["a", "b"]) def __init__(self, *, a=0, b=1): self.a = a self.b = b @deprecate_posargs(RemovedAfterNextVersionWarning, ["a", "b"]) def some_method(self, *, a, b=1): return self.a, self.b, a, b @staticmethod @deprecate_posargs(RemovedAfterNextVersionWarning, ["a", "b"]) def some_static_method(*, a, b=1): return a, b @classmethod @deprecate_posargs(RemovedAfterNextVersionWarning, ["a", "b"]) def some_class_method(cls, *, a, b=1): return cls.__name__, a, b with ( self.subTest("Constructor"), # Warning should use the class name, not `__init__()`. self.assertDeprecated("'a', 'b'", "SomeClass"), ): instance = SomeClass(10, 20) self.assertEqual(instance.a, 10) self.assertEqual(instance.b, 20) with ( self.subTest("Instance method"), self.assertDeprecated("'a', 'b'", "some_method"), ): result = SomeClass().some_method(10, 20) self.assertEqual(result, (0, 1, 10, 20)) with ( self.subTest("Static method on instance"), self.assertDeprecated("'a', 'b'", "some_static_method"), ): result = SomeClass().some_static_method(10, 20) self.assertEqual(result, (10, 20)) with ( self.subTest("Static method on class"), self.assertDeprecated("'a', 'b'", "some_static_method"), ): result = SomeClass.some_static_method(10, 20) self.assertEqual(result, (10, 20)) with ( self.subTest("Class method on instance"), self.assertDeprecated("'a', 'b'", "some_class_method"), ): result = SomeClass().some_class_method(10, 20) self.assertEqual(result, ("SomeClass", 10, 20)) with ( self.subTest("Class method on class"), self.assertDeprecated("'a', 'b'", "some_class_method"), ): result = SomeClass.some_class_method(10, 20) self.assertEqual(result, ("SomeClass", 10, 20)) def test_incorrect_classmethod_order(self): """Catch classmethod applied in wrong order.""" with self.assertRaisesMessage( TypeError, "Apply @classmethod before @deprecate_posargs." ): class SomeClass: @deprecate_posargs(RemovedAfterNextVersionWarning, ["a"]) @classmethod def some_class_method(cls, *, a): pass def test_incorrect_staticmethod_order(self): """Catch staticmethod applied in wrong order.""" with self.assertRaisesMessage( TypeError, "Apply @staticmethod before @deprecate_posargs." ): class SomeClass: @deprecate_posargs(RemovedAfterNextVersionWarning, ["a"]) @staticmethod def some_static_method(*, a): pass async def test_async(self): """A decorated async function is still async.""" @deprecate_posargs(RemovedAfterNextVersionWarning, ["a", "b"]) async def some_func(*, a, b=1): return a, b self.assertTrue(inspect.iscoroutinefunction(some_func.__wrapped__)) self.assertTrue(inspect.iscoroutinefunction(some_func)) with ( self.subTest("With deprecation warning"), self.assertDeprecated("'a', 'b'", "some_func"), ): result = await some_func(10, 20) self.assertEqual(result, (10, 20)) with ( self.subTest("Without deprecation warning"), self.assertNoLogs(level="WARNING"), ): result = await some_func(a=10, b=20) self.assertEqual(result, (10, 20)) def test_applied_to_lambda(self): """ Please don't try to deprecate lambda args! What does that even mean?! (But if it happens, the decorator should do something reasonable.) """ lambda_func = deprecate_posargs(RemovedAfterNextVersionWarning, ["b"])( lambda a, *, b=1: (a, b) ) with self.assertDeprecated("'b'", "<lambda>"): result = lambda_func(10, 20) self.assertEqual(result, (10, 20)) def test_bare_init(self): """Can't replace '__init__' with class name if not in a class.""" @deprecate_posargs(RemovedAfterNextVersionWarning, ["a"]) def __init__(*, a): pass with self.assertDeprecated("'a'", "__init__"): __init__(10) def test_warning_source_location(self): """The warning points to caller, not the decorator implementation.""" @deprecate_posargs(RemovedAfterNextVersionWarning, "a") def some_func(*, a): return a with self.assertWarns(RemovedAfterNextVersionWarning) as cm: some_func(10) self.assertEqual(cm.filename, __file__) self.assertEqual(cm.lineno, inspect.currentframe().f_lineno - 2) def test_decorator_requires_keyword_only_params(self): with self.assertRaisesMessage( TypeError, "@deprecate_posargs() requires at least one keyword-only parameter " "(after a `*` entry in the parameters list).", ): @deprecate_posargs(RemovedAfterNextVersionWarning, ["b"]) def func(a, b=1): return a, b def test_decorator_rejects_var_positional_param(self): with self.assertRaisesMessage( TypeError, "@deprecate_posargs() cannot be used with variable positional `*args`.", ): @deprecate_posargs(RemovedAfterNextVersionWarning, ["b"]) def func(*args, b=1): return args, b def test_decorator_does_not_apply_to_class(self): with self.assertRaisesMessage( TypeError, "@deprecate_posargs cannot be applied to a class. (Apply it to the " "__init__ method.)", ): @deprecate_posargs(RemovedAfterNextVersionWarning, ["b"]) class NotThisClass: pass def test_decorator_requires_remappable_names_be_keyword_only(self): """remappable_names cannot refer to positional-or-keyword params.""" with self.assertRaisesMessage( TypeError, "@deprecate_posargs() requires all remappable_names to be keyword-only " "parameters.", ): @deprecate_posargs(RemovedAfterNextVersionWarning, ["a", "b"]) def func(a, *, b=1): return a, b def test_decorator_requires_remappable_names_exist(self): """remappable_names cannot refer to variable kwargs.""" with self.assertRaisesMessage( TypeError, "@deprecate_posargs() requires all remappable_names to be keyword-only " "parameters.", ): @deprecate_posargs(RemovedAfterNextVersionWarning, ["b", "c"]) def func(a, *, b=1, **kwargs): c = kwargs.get("c") return a, b, c def test_decorator_preserves_signature_and_metadata(self): def original(a, b=1, *, c=2): """Docstring.""" return a, b, c decorated = deprecate_posargs(RemovedAfterNextVersionWarning, ["c"])(original) self.assertEqual(original.__name__, decorated.__name__) self.assertEqual(original.__qualname__, decorated.__qualname__) self.assertEqual(original.__doc__, decorated.__doc__) self.assertEqual(inspect.signature(original), inspect.signature(decorated))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/deprecation/__init__.py
tests/deprecation/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/deprecation/tests.py
tests/deprecation/tests.py
import os import warnings import django from django.test import SimpleTestCase from django.utils.deprecation import ( RemovedAfterNextVersionWarning, RenameMethodsBase, django_file_prefixes, ) class DjangoFilePrefixesTests(SimpleTestCase): def setUp(self): django_file_prefixes.cache_clear() self.addCleanup(django_file_prefixes.cache_clear) def test_no_file(self): orig_file = django.__file__ try: del django.__file__ self.assertEqual(django_file_prefixes(), ()) finally: django.__file__ = orig_file def test_with_file(self): prefixes = django_file_prefixes() self.assertIsInstance(prefixes, tuple) self.assertEqual(len(prefixes), 1) self.assertTrue(prefixes[0].endswith(f"{os.path.sep}django")) class RenameManagerMethods(RenameMethodsBase): renamed_methods = (("old", "new", DeprecationWarning),) class RenameMethodsTests(SimpleTestCase): """ Tests the `RenameMethodsBase` type introduced to rename `get_query_set` to `get_queryset` across the code base following #15363. """ def test_class_definition_warnings(self): """ Ensure a warning is raised upon class definition to suggest renaming the faulty method. """ msg = "`Manager.old` method should be renamed `new`." with self.assertWarnsMessage(DeprecationWarning, msg) as ctx: class Manager(metaclass=RenameManagerMethods): def old(self): pass self.assertEqual(ctx.filename, __file__) def test_get_new_defined(self): """ Ensure `old` complains and not `new` when only `new` is defined. """ class Manager(metaclass=RenameManagerMethods): def new(self): pass manager = Manager() with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter("always") manager.new() self.assertEqual(len(recorded), 0) msg = "`Manager.old` is deprecated, use `new` instead." with self.assertWarnsMessage(DeprecationWarning, msg) as ctx: manager.old() self.assertEqual(ctx.filename, __file__) def test_get_old_defined(self): """ Ensure `old` complains when only `old` is defined. """ msg = "`Manager.old` method should be renamed `new`." with self.assertWarnsMessage(DeprecationWarning, msg) as ctx: class Manager(metaclass=RenameManagerMethods): def old(self): pass self.assertEqual(ctx.filename, __file__) manager = Manager() with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter("always") manager.new() self.assertEqual(len(recorded), 0) msg = "`Manager.old` is deprecated, use `new` instead." with self.assertWarnsMessage(DeprecationWarning, msg) as ctx: manager.old() self.assertEqual(ctx.filename, __file__) def test_deprecated_subclass_renamed(self): """ Ensure the correct warnings are raised when a class that didn't rename `old` subclass one that did. """ class Renamed(metaclass=RenameManagerMethods): def new(self): pass msg = "`Deprecated.old` method should be renamed `new`." with self.assertWarnsMessage(DeprecationWarning, msg) as ctx: class Deprecated(Renamed): def old(self): super().old() self.assertEqual(ctx.filename, __file__) deprecated = Deprecated() msg = "`Renamed.old` is deprecated, use `new` instead." with self.assertWarnsMessage(DeprecationWarning, msg) as ctx: deprecated.new() self.assertEqual(ctx.filename, __file__) msg = "`Deprecated.old` is deprecated, use `new` instead." with self.assertWarnsMessage(DeprecationWarning, msg) as ctx: deprecated.old() self.assertEqual(ctx.filename, __file__) def test_renamed_subclass_deprecated(self): """ Ensure the correct warnings are raised when a class that renamed `old` subclass one that didn't. """ msg = "`Deprecated.old` method should be renamed `new`." with self.assertWarnsMessage(DeprecationWarning, msg) as ctx: class Deprecated(metaclass=RenameManagerMethods): def old(self): pass self.assertEqual(ctx.filename, __file__) class Renamed(Deprecated): def new(self): super().new() renamed = Renamed() with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter("always") renamed.new() self.assertEqual(len(recorded), 0) msg = "`Renamed.old` is deprecated, use `new` instead." with self.assertWarnsMessage(DeprecationWarning, msg) as ctx: renamed.old() self.assertEqual(ctx.filename, __file__) def test_deprecated_subclass_renamed_and_mixins(self): """ Ensure the correct warnings are raised when a subclass inherit from a class that renamed `old` and mixins that may or may not have renamed `new`. """ class Renamed(metaclass=RenameManagerMethods): def new(self): pass class RenamedMixin: def new(self): super().new() class DeprecatedMixin: def old(self): super().old() msg = "`DeprecatedMixin.old` method should be renamed `new`." with self.assertWarnsMessage(DeprecationWarning, msg) as ctx: class Deprecated(DeprecatedMixin, RenamedMixin, Renamed): pass self.assertEqual(ctx.filename, __file__) deprecated = Deprecated() msg = "`RenamedMixin.old` is deprecated, use `new` instead." with self.assertWarnsMessage(DeprecationWarning, msg) as ctx: deprecated.new() self.assertEqual(ctx.filename, __file__) msg = "`DeprecatedMixin.old` is deprecated, use `new` instead." with self.assertWarnsMessage(DeprecationWarning, msg) as ctx: deprecated.old() self.assertEqual(ctx.filename, __file__) def test_removedafternextversionwarning_pending(self): self.assertTrue( issubclass(RemovedAfterNextVersionWarning, PendingDeprecationWarning) )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/deprecation/test_middleware_mixin.py
tests/deprecation/test_middleware_mixin.py
import threading from asgiref.sync import async_to_sync, iscoroutinefunction from django.contrib.admindocs.middleware import XViewMiddleware from django.contrib.auth.middleware import ( AuthenticationMiddleware, LoginRequiredMiddleware, ) from django.contrib.flatpages.middleware import FlatpageFallbackMiddleware from django.contrib.messages.middleware import MessageMiddleware from django.contrib.redirects.middleware import RedirectFallbackMiddleware from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.sites.middleware import CurrentSiteMiddleware from django.db import connection from django.http.request import HttpRequest from django.http.response import HttpResponse from django.middleware.cache import ( CacheMiddleware, FetchFromCacheMiddleware, UpdateCacheMiddleware, ) from django.middleware.clickjacking import XFrameOptionsMiddleware from django.middleware.common import BrokenLinkEmailsMiddleware, CommonMiddleware from django.middleware.csrf import CsrfViewMiddleware from django.middleware.gzip import GZipMiddleware from django.middleware.http import ConditionalGetMiddleware from django.middleware.locale import LocaleMiddleware from django.middleware.security import SecurityMiddleware from django.test import SimpleTestCase from django.utils.deprecation import MiddlewareMixin class MiddlewareMixinTests(SimpleTestCase): middlewares = [ AuthenticationMiddleware, LoginRequiredMiddleware, BrokenLinkEmailsMiddleware, CacheMiddleware, CommonMiddleware, ConditionalGetMiddleware, CsrfViewMiddleware, CurrentSiteMiddleware, FetchFromCacheMiddleware, FlatpageFallbackMiddleware, GZipMiddleware, LocaleMiddleware, MessageMiddleware, RedirectFallbackMiddleware, SecurityMiddleware, SessionMiddleware, UpdateCacheMiddleware, XFrameOptionsMiddleware, XViewMiddleware, ] def test_repr(self): class GetResponse: def __call__(self): return HttpResponse() def get_response(): return HttpResponse() self.assertEqual( repr(MiddlewareMixin(GetResponse())), "<MiddlewareMixin get_response=GetResponse>", ) self.assertEqual( repr(MiddlewareMixin(get_response)), "<MiddlewareMixin get_response=" "MiddlewareMixinTests.test_repr.<locals>.get_response>", ) self.assertEqual( repr(CsrfViewMiddleware(GetResponse())), "<CsrfViewMiddleware get_response=GetResponse>", ) self.assertEqual( repr(CsrfViewMiddleware(get_response)), "<CsrfViewMiddleware get_response=" "MiddlewareMixinTests.test_repr.<locals>.get_response>", ) def test_passing_explicit_none(self): msg = "get_response must be provided." for middleware in self.middlewares: with self.subTest(middleware=middleware): with self.assertRaisesMessage(ValueError, msg): middleware(None) def test_coroutine(self): async def async_get_response(request): return HttpResponse() def sync_get_response(request): return HttpResponse() for middleware in self.middlewares: with self.subTest(middleware=middleware.__qualname__): # Middleware appears as coroutine if get_function is # a coroutine. middleware_instance = middleware(async_get_response) self.assertIs(iscoroutinefunction(middleware_instance), True) # Middleware doesn't appear as coroutine if get_function is not # a coroutine. middleware_instance = middleware(sync_get_response) self.assertIs(iscoroutinefunction(middleware_instance), False) def test_sync_to_async_uses_base_thread_and_connection(self): """ The process_request() and process_response() hooks must be called with the sync_to_async thread_sensitive flag enabled, so that database operations use the correct thread and connection. """ def request_lifecycle(): """Fake request_started/request_finished.""" return (threading.get_ident(), id(connection)) async def get_response(self): return HttpResponse() class SimpleMiddleWare(MiddlewareMixin): def process_request(self, request): request.thread_and_connection = request_lifecycle() def process_response(self, request, response): response.thread_and_connection = request_lifecycle() return response threads_and_connections = [] threads_and_connections.append(request_lifecycle()) request = HttpRequest() response = async_to_sync(SimpleMiddleWare(get_response))(request) threads_and_connections.append(request.thread_and_connection) threads_and_connections.append(response.thread_and_connection) threads_and_connections.append(request_lifecycle()) self.assertEqual(len(threads_and_connections), 4) self.assertEqual(len(set(threads_and_connections)), 1)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/bulk_create/models.py
tests/bulk_create/models.py
import datetime import uuid from decimal import Decimal from django.db import models from django.db.models.functions import Now from django.utils import timezone try: from PIL import Image except ImportError: Image = None class Country(models.Model): name = models.CharField(max_length=255) iso_two_letter = models.CharField(max_length=2) description = models.TextField() class Meta: constraints = [ models.UniqueConstraint( fields=["iso_two_letter", "name"], name="country_name_iso_unique", ), ] class ProxyCountry(Country): class Meta: proxy = True class ProxyProxyCountry(ProxyCountry): class Meta: proxy = True class ProxyMultiCountry(ProxyCountry): pass class ProxyMultiProxyCountry(ProxyMultiCountry): class Meta: proxy = True class Place(models.Model): name = models.CharField(max_length=100) class Meta: abstract = True class Restaurant(Place): pass class Pizzeria(Restaurant): pass class State(models.Model): two_letter_code = models.CharField(max_length=2, primary_key=True) class TwoFields(models.Model): f1 = models.IntegerField(unique=True) f2 = models.IntegerField(unique=True) name = models.CharField(max_length=15, null=True) class FieldsWithDbColumns(models.Model): rank = models.IntegerField(unique=True, db_column="rAnK") name = models.CharField(max_length=15, null=True, db_column="oTheRNaMe") class UpsertConflict(models.Model): number = models.IntegerField(unique=True) rank = models.IntegerField() name = models.CharField(max_length=15) class NoFields(models.Model): pass class SmallAutoFieldModel(models.Model): id = models.SmallAutoField(primary_key=True) class BigAutoFieldModel(models.Model): id = models.BigAutoField(primary_key=True) class NullableFields(models.Model): # Fields in db.backends.oracle.BulkInsertMapper big_int_filed = models.BigIntegerField(null=True, default=1) binary_field = models.BinaryField(null=True, default=b"data") date_field = models.DateField(null=True, default=timezone.now) datetime_field = models.DateTimeField(null=True, default=timezone.now) decimal_field = models.DecimalField( null=True, max_digits=2, decimal_places=1, default=Decimal("1.1") ) duration_field = models.DurationField(null=True, default=datetime.timedelta(1)) float_field = models.FloatField(null=True, default=3.2) integer_field = models.IntegerField(null=True, default=2) null_boolean_field = models.BooleanField(null=True, default=False) positive_big_integer_field = models.PositiveBigIntegerField( null=True, default=2**63 - 1 ) positive_integer_field = models.PositiveIntegerField(null=True, default=3) positive_small_integer_field = models.PositiveSmallIntegerField( null=True, default=4 ) small_integer_field = models.SmallIntegerField(null=True, default=5) time_field = models.TimeField(null=True, default=timezone.now) auto_field = models.ForeignKey(NoFields, on_delete=models.CASCADE, null=True) small_auto_field = models.ForeignKey( SmallAutoFieldModel, on_delete=models.CASCADE, null=True ) big_auto_field = models.ForeignKey( BigAutoFieldModel, on_delete=models.CASCADE, null=True ) # Fields not required in BulkInsertMapper char_field = models.CharField(null=True, max_length=4, default="char") email_field = models.EmailField(null=True, default="user@example.com") file_field = models.FileField(null=True, default="file.txt") file_path_field = models.FilePathField(path="/tmp", null=True, default="file.txt") generic_ip_address_field = models.GenericIPAddressField( null=True, default="127.0.0.1" ) if Image: image_field = models.ImageField(null=True, default="image.jpg") slug_field = models.SlugField(null=True, default="slug") text_field = models.TextField(null=True, default="text") url_field = models.URLField(null=True, default="/") uuid_field = models.UUIDField(null=True, default=uuid.uuid4) class RelatedModel(models.Model): name = models.CharField(max_length=15, null=True) country = models.OneToOneField(Country, models.CASCADE, primary_key=True) big_auto_fields = models.ManyToManyField(BigAutoFieldModel) class DbDefaultModel(models.Model): name = models.CharField(max_length=10) created_at = models.DateTimeField(db_default=Now()) class Meta: required_db_features = {"supports_expression_defaults"} class DbDefaultPrimaryKey(models.Model): id = models.DateTimeField(primary_key=True, db_default=Now()) class Meta: required_db_features = {"supports_expression_defaults"}
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/bulk_create/__init__.py
tests/bulk_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/bulk_create/tests.py
tests/bulk_create/tests.py
from datetime import datetime from math import ceil from operator import attrgetter from django.core.exceptions import FieldDoesNotExist from django.db import ( IntegrityError, NotSupportedError, OperationalError, ProgrammingError, connection, ) from django.db.models import FileField, Value from django.db.models.functions import Lower, Now from django.test import ( TestCase, TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.utils import CaptureQueriesContext from django.utils import timezone from .models import ( BigAutoFieldModel, Country, DbDefaultModel, DbDefaultPrimaryKey, FieldsWithDbColumns, NoFields, NullableFields, Pizzeria, ProxyCountry, ProxyMultiCountry, ProxyMultiProxyCountry, ProxyProxyCountry, RelatedModel, Restaurant, SmallAutoFieldModel, State, TwoFields, UpsertConflict, ) class BulkCreateTests(TestCase): def setUp(self): self.data = [ Country(name="United States of America", iso_two_letter="US"), Country(name="The Netherlands", iso_two_letter="NL"), Country(name="Germany", iso_two_letter="DE"), Country(name="Czech Republic", iso_two_letter="CZ"), ] def test_simple(self): created = Country.objects.bulk_create(self.data) self.assertEqual(created, self.data) self.assertQuerySetEqual( Country.objects.order_by("-name"), [ "United States of America", "The Netherlands", "Germany", "Czech Republic", ], attrgetter("name"), ) created = Country.objects.bulk_create([]) self.assertEqual(created, []) self.assertEqual(Country.objects.count(), 4) @skipUnlessDBFeature("has_bulk_insert") def test_efficiency(self): with self.assertNumQueries(1): Country.objects.bulk_create(self.data) @skipUnlessDBFeature("has_bulk_insert") def test_long_non_ascii_text(self): """ Inserting non-ASCII values with a length in the range 2001 to 4000 characters, i.e. 4002 to 8000 bytes, must be set as a CLOB on Oracle (#22144). """ Country.objects.bulk_create([Country(description="Ж" * 3000)]) self.assertEqual(Country.objects.count(), 1) @skipUnlessDBFeature("has_bulk_insert") def test_long_and_short_text(self): Country.objects.bulk_create( [ Country(description="a" * 4001, iso_two_letter="A"), Country(description="a", iso_two_letter="B"), Country(description="Ж" * 2001, iso_two_letter="C"), Country(description="Ж", iso_two_letter="D"), ] ) self.assertEqual(Country.objects.count(), 4) def test_multi_table_inheritance_unsupported(self): expected_message = "Can't bulk create a multi-table inherited model" with self.assertRaisesMessage(ValueError, expected_message): Pizzeria.objects.bulk_create( [ Pizzeria(name="The Art of Pizza"), ] ) with self.assertRaisesMessage(ValueError, expected_message): ProxyMultiCountry.objects.bulk_create( [ ProxyMultiCountry(name="Fillory", iso_two_letter="FL"), ] ) with self.assertRaisesMessage(ValueError, expected_message): ProxyMultiProxyCountry.objects.bulk_create( [ ProxyMultiProxyCountry(name="Fillory", iso_two_letter="FL"), ] ) def test_proxy_inheritance_supported(self): ProxyCountry.objects.bulk_create( [ ProxyCountry(name="Qwghlm", iso_two_letter="QW"), Country(name="Tortall", iso_two_letter="TA"), ] ) self.assertQuerySetEqual( ProxyCountry.objects.all(), {"Qwghlm", "Tortall"}, attrgetter("name"), ordered=False, ) ProxyProxyCountry.objects.bulk_create( [ ProxyProxyCountry(name="Netherlands", iso_two_letter="NT"), ] ) self.assertQuerySetEqual( ProxyProxyCountry.objects.all(), { "Qwghlm", "Tortall", "Netherlands", }, attrgetter("name"), ordered=False, ) def test_non_auto_increment_pk(self): State.objects.bulk_create( [State(two_letter_code=s) for s in ["IL", "NY", "CA", "ME"]] ) self.assertQuerySetEqual( State.objects.order_by("two_letter_code"), [ "CA", "IL", "ME", "NY", ], attrgetter("two_letter_code"), ) @skipUnlessDBFeature("has_bulk_insert") def test_non_auto_increment_pk_efficiency(self): with self.assertNumQueries(1): State.objects.bulk_create( [State(two_letter_code=s) for s in ["IL", "NY", "CA", "ME"]] ) self.assertQuerySetEqual( State.objects.order_by("two_letter_code"), [ "CA", "IL", "ME", "NY", ], attrgetter("two_letter_code"), ) @skipIfDBFeature("allows_auto_pk_0") def test_zero_as_autoval(self): """ Zero as id for AutoField should raise exception in MySQL, because MySQL does not allow zero for automatic primary key if the NO_AUTO_VALUE_ON_ZERO SQL mode is not enabled. """ valid_country = Country(name="Germany", iso_two_letter="DE") invalid_country = Country(id=0, name="Poland", iso_two_letter="PL") msg = "The database backend does not accept 0 as a value for AutoField." with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create([valid_country, invalid_country]) def test_batch_same_vals(self): # SQLite had a problem where all the same-valued models were # collapsed to one insert. Restaurant.objects.bulk_create([Restaurant(name="foo") for i in range(0, 2)]) self.assertEqual(Restaurant.objects.count(), 2) def test_large_batch(self): TwoFields.objects.bulk_create( [TwoFields(f1=i, f2=i + 1) for i in range(0, 1001)] ) self.assertEqual(TwoFields.objects.count(), 1001) self.assertEqual( TwoFields.objects.filter(f1__gte=450, f1__lte=550).count(), 101 ) self.assertEqual(TwoFields.objects.filter(f2__gte=901).count(), 101) @skipUnlessDBFeature("has_bulk_insert") def test_large_single_field_batch(self): # SQLite had a problem with more than 500 UNIONed selects in single # query. Restaurant.objects.bulk_create([Restaurant() for i in range(0, 501)]) @skipUnlessDBFeature("has_bulk_insert") def test_large_batch_efficiency(self): with CaptureQueriesContext(connection) as ctx: TwoFields.objects.bulk_create( [TwoFields(f1=i, f2=i + 1) for i in range(0, 1001)] ) self.assertLess(len(ctx), 10) def test_large_batch_mixed(self): """ Test inserting a large batch with objects having primary key set mixed together with objects without PK set. """ TwoFields.objects.bulk_create( [ TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1) for i in range(100000, 101000) ] ) self.assertEqual(TwoFields.objects.count(), 1000) # We can't assume much about the ID's created, except that the above # created IDs must exist. id_range = range(100000, 101000, 2) self.assertEqual(TwoFields.objects.filter(id__in=id_range).count(), 500) self.assertEqual(TwoFields.objects.exclude(id__in=id_range).count(), 500) @skipUnlessDBFeature("has_bulk_insert") def test_large_batch_mixed_efficiency(self): """ Test inserting a large batch with objects having primary key set mixed together with objects without PK set. """ with CaptureQueriesContext(connection) as ctx: TwoFields.objects.bulk_create( [ TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1) for i in range(100000, 101000) ] ) self.assertLess(len(ctx), 10) def test_explicit_batch_size(self): objs = [TwoFields(f1=i, f2=i) for i in range(0, 4)] num_objs = len(objs) TwoFields.objects.bulk_create(objs, batch_size=1) self.assertEqual(TwoFields.objects.count(), num_objs) TwoFields.objects.all().delete() TwoFields.objects.bulk_create(objs, batch_size=2) self.assertEqual(TwoFields.objects.count(), num_objs) TwoFields.objects.all().delete() TwoFields.objects.bulk_create(objs, batch_size=3) self.assertEqual(TwoFields.objects.count(), num_objs) TwoFields.objects.all().delete() TwoFields.objects.bulk_create(objs, batch_size=num_objs) self.assertEqual(TwoFields.objects.count(), num_objs) def test_empty_model(self): NoFields.objects.bulk_create([NoFields() for i in range(2)]) self.assertEqual(NoFields.objects.count(), 2) @skipUnlessDBFeature("has_bulk_insert") def test_explicit_batch_size_efficiency(self): objs = [TwoFields(f1=i, f2=i) for i in range(0, 100)] with self.assertNumQueries(2): TwoFields.objects.bulk_create(objs, 50) TwoFields.objects.all().delete() with self.assertNumQueries(1): TwoFields.objects.bulk_create(objs, len(objs)) @skipUnlessDBFeature("has_bulk_insert") def test_explicit_batch_size_respects_max_batch_size(self): objs = [Country(name=f"Country {i}") for i in range(1000)] fields = ["name", "iso_two_letter", "description"] max_batch_size = max(connection.ops.bulk_batch_size(fields, objs), 1) with self.assertNumQueries(ceil(len(objs) / max_batch_size)): Country.objects.bulk_create(objs, batch_size=max_batch_size + 1) @skipUnlessDBFeature("has_bulk_insert") def test_max_batch_size(self): objs = [Country(name=f"Country {i}") for i in range(1000)] fields = ["name", "iso_two_letter", "description"] max_batch_size = connection.ops.bulk_batch_size(fields, objs) with self.assertNumQueries(ceil(len(objs) / max_batch_size)): Country.objects.bulk_create(objs) @skipUnlessDBFeature("has_bulk_insert") def test_bulk_insert_expressions(self): Restaurant.objects.bulk_create( [ Restaurant(name="Sam's Shake Shack"), Restaurant(name=Lower(Value("Betty's Beetroot Bar"))), ] ) bbb = Restaurant.objects.filter(name="betty's beetroot bar") self.assertEqual(bbb.count(), 1) @skipUnlessDBFeature("has_bulk_insert") def test_bulk_insert_now(self): NullableFields.objects.bulk_create( [ NullableFields(datetime_field=Now()), NullableFields(datetime_field=Now()), ] ) self.assertEqual( NullableFields.objects.filter(datetime_field__isnull=False).count(), 2, ) @skipUnlessDBFeature("has_bulk_insert") def test_bulk_insert_nullable_fields(self): fk_to_auto_fields = { "auto_field": NoFields.objects.create(), "small_auto_field": SmallAutoFieldModel.objects.create(), "big_auto_field": BigAutoFieldModel.objects.create(), } # NULL can be mixed with other values in nullable fields nullable_fields = [ field for field in NullableFields._meta.get_fields() if field.name != "id" ] NullableFields.objects.bulk_create( [ NullableFields(**{**fk_to_auto_fields, field.name: None}) for field in nullable_fields ] ) self.assertEqual(NullableFields.objects.count(), len(nullable_fields)) for field in nullable_fields: with self.subTest(field=field): field_value = "" if isinstance(field, FileField) else None self.assertEqual( NullableFields.objects.filter(**{field.name: field_value}).count(), 1, ) @skipUnlessDBFeature("can_return_rows_from_bulk_insert") def test_set_pk_and_insert_single_item(self): with self.assertNumQueries(1): countries = Country.objects.bulk_create([self.data[0]]) self.assertEqual(len(countries), 1) self.assertEqual(Country.objects.get(pk=countries[0].pk), countries[0]) @skipUnlessDBFeature("can_return_rows_from_bulk_insert") def test_set_pk_and_query_efficiency(self): with self.assertNumQueries(1): countries = Country.objects.bulk_create(self.data) self.assertEqual(len(countries), 4) self.assertEqual(Country.objects.get(pk=countries[0].pk), countries[0]) self.assertEqual(Country.objects.get(pk=countries[1].pk), countries[1]) self.assertEqual(Country.objects.get(pk=countries[2].pk), countries[2]) self.assertEqual(Country.objects.get(pk=countries[3].pk), countries[3]) @skipUnlessDBFeature("can_return_rows_from_bulk_insert") def test_set_state(self): country_nl = Country(name="Netherlands", iso_two_letter="NL") country_be = Country(name="Belgium", iso_two_letter="BE") Country.objects.bulk_create([country_nl]) country_be.save() # Objects save via bulk_create() and save() should have equal state. self.assertEqual(country_nl._state.adding, country_be._state.adding) self.assertEqual(country_nl._state.db, country_be._state.db) def test_set_state_with_pk_specified(self): state_ca = State(two_letter_code="CA") state_ny = State(two_letter_code="NY") State.objects.bulk_create([state_ca]) state_ny.save() # Objects save via bulk_create() and save() should have equal state. self.assertEqual(state_ca._state.adding, state_ny._state.adding) self.assertEqual(state_ca._state.db, state_ny._state.db) @skipIfDBFeature("supports_ignore_conflicts") def test_ignore_conflicts_value_error(self): message = "This database backend does not support ignoring conflicts." with self.assertRaisesMessage(NotSupportedError, message): TwoFields.objects.bulk_create(self.data, ignore_conflicts=True) @skipUnlessDBFeature("supports_ignore_conflicts") def test_ignore_conflicts_ignore(self): data = [ TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2), TwoFields(f1=3, f2=3), ] TwoFields.objects.bulk_create(data) self.assertEqual(TwoFields.objects.count(), 3) # With ignore_conflicts=True, conflicts are ignored. conflicting_objects = [ TwoFields(f1=2, f2=2), TwoFields(f1=3, f2=3), ] TwoFields.objects.bulk_create([conflicting_objects[0]], ignore_conflicts=True) TwoFields.objects.bulk_create(conflicting_objects, ignore_conflicts=True) self.assertEqual(TwoFields.objects.count(), 3) self.assertIsNone(conflicting_objects[0].pk) self.assertIsNone(conflicting_objects[1].pk) # New objects are created and conflicts are ignored. new_object = TwoFields(f1=4, f2=4) TwoFields.objects.bulk_create( conflicting_objects + [new_object], ignore_conflicts=True ) self.assertEqual(TwoFields.objects.count(), 4) self.assertIsNone(new_object.pk) # Without ignore_conflicts=True, there's a problem. with self.assertRaises(IntegrityError): TwoFields.objects.bulk_create(conflicting_objects) def test_nullable_fk_after_parent(self): parent = NoFields() child = NullableFields(auto_field=parent, integer_field=88) parent.save() NullableFields.objects.bulk_create([child]) child = NullableFields.objects.get(integer_field=88) self.assertEqual(child.auto_field, parent) @skipUnlessDBFeature("can_return_rows_from_bulk_insert") def test_nullable_fk_after_parent_bulk_create(self): parent = NoFields() child = NullableFields(auto_field=parent, integer_field=88) NoFields.objects.bulk_create([parent]) NullableFields.objects.bulk_create([child]) child = NullableFields.objects.get(integer_field=88) self.assertEqual(child.auto_field, parent) def test_unsaved_parent(self): parent = NoFields() msg = ( "bulk_create() prohibited to prevent data loss due to unsaved " "related object 'auto_field'." ) with self.assertRaisesMessage(ValueError, msg): NullableFields.objects.bulk_create([NullableFields(auto_field=parent)]) def test_invalid_batch_size_exception(self): msg = "Batch size must be a positive integer." with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create([], batch_size=-1) @skipIfDBFeature("supports_update_conflicts") def test_update_conflicts_unsupported(self): msg = "This database backend does not support updating conflicts." with self.assertRaisesMessage(NotSupportedError, msg): Country.objects.bulk_create(self.data, update_conflicts=True) @skipUnlessDBFeature("supports_ignore_conflicts", "supports_update_conflicts") def test_ignore_update_conflicts_exclusive(self): msg = "ignore_conflicts and update_conflicts are mutually exclusive" with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create( self.data, ignore_conflicts=True, update_conflicts=True, ) @skipUnlessDBFeature("supports_update_conflicts") def test_update_conflicts_no_update_fields(self): msg = ( "Fields that will be updated when a row insertion fails on " "conflicts must be provided." ) with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create(self.data, update_conflicts=True) @skipUnlessDBFeature("supports_update_conflicts") @skipIfDBFeature("supports_update_conflicts_with_target") def test_update_conflicts_unique_field_unsupported(self): msg = ( "This database backend does not support updating conflicts with " "specifying unique fields that can trigger the upsert." ) with self.assertRaisesMessage(NotSupportedError, msg): TwoFields.objects.bulk_create( [TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2)], update_conflicts=True, update_fields=["f2"], unique_fields=["f1"], ) @skipUnlessDBFeature("supports_update_conflicts") def test_update_conflicts_nonexistent_update_fields(self): unique_fields = None if connection.features.supports_update_conflicts_with_target: unique_fields = ["f1"] msg = "TwoFields has no field named 'nonexistent'" with self.assertRaisesMessage(FieldDoesNotExist, msg): TwoFields.objects.bulk_create( [TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2)], update_conflicts=True, update_fields=["nonexistent"], unique_fields=unique_fields, ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target", ) def test_update_conflicts_unique_fields_required(self): msg = "Unique fields that can trigger the upsert must be provided." with self.assertRaisesMessage(ValueError, msg): TwoFields.objects.bulk_create( [TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2)], update_conflicts=True, update_fields=["f1"], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target", ) def test_update_conflicts_invalid_update_fields(self): msg = "bulk_create() can only be used with concrete fields in update_fields." # Reverse one-to-one relationship. with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create( self.data, update_conflicts=True, update_fields=["relatedmodel"], unique_fields=["pk"], ) # Many-to-many relationship. with self.assertRaisesMessage(ValueError, msg): RelatedModel.objects.bulk_create( [RelatedModel(country=self.data[0])], update_conflicts=True, update_fields=["big_auto_fields"], unique_fields=["country"], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target", ) def test_update_conflicts_pk_in_update_fields(self): msg = "bulk_create() cannot be used with primary keys in update_fields." with self.assertRaisesMessage(ValueError, msg): BigAutoFieldModel.objects.bulk_create( [BigAutoFieldModel()], update_conflicts=True, update_fields=["id"], unique_fields=["id"], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target", ) def test_update_conflicts_invalid_unique_fields(self): msg = "bulk_create() can only be used with concrete fields in unique_fields." # Reverse one-to-one relationship. with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create( self.data, update_conflicts=True, update_fields=["name"], unique_fields=["relatedmodel"], ) # Many-to-many relationship. with self.assertRaisesMessage(ValueError, msg): RelatedModel.objects.bulk_create( [RelatedModel(country=self.data[0])], update_conflicts=True, update_fields=["name"], unique_fields=["big_auto_fields"], ) def _test_update_conflicts_two_fields(self, unique_fields): TwoFields.objects.bulk_create( [ TwoFields(f1=1, f2=1, name="a"), TwoFields(f1=2, f2=2, name="b"), ] ) self.assertEqual(TwoFields.objects.count(), 2) conflicting_objects = [ TwoFields(f1=1, f2=1, name="c"), TwoFields(f1=2, f2=2, name="d"), ] results = TwoFields.objects.bulk_create( conflicting_objects, update_conflicts=True, unique_fields=unique_fields, update_fields=["name"], ) self.assertEqual(len(results), len(conflicting_objects)) if connection.features.can_return_rows_from_bulk_insert: for instance in results: self.assertIsNotNone(instance.pk) self.assertEqual(TwoFields.objects.count(), 2) self.assertCountEqual( TwoFields.objects.values("f1", "f2", "name"), [ {"f1": 1, "f2": 1, "name": "c"}, {"f1": 2, "f2": 2, "name": "d"}, ], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_two_fields_unique_fields_first(self): self._test_update_conflicts_two_fields(["f1"]) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_two_fields_unique_fields_second(self): self._test_update_conflicts_two_fields(["f2"]) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_unique_fields_pk(self): TwoFields.objects.bulk_create( [ TwoFields(f1=1, f2=1, name="a"), TwoFields(f1=2, f2=2, name="b"), ] ) obj1 = TwoFields.objects.get(f1=1) obj2 = TwoFields.objects.get(f1=2) conflicting_objects = [ TwoFields(pk=obj1.pk, f1=3, f2=3, name="c"), TwoFields(pk=obj2.pk, f1=4, f2=4, name="d"), ] results = TwoFields.objects.bulk_create( conflicting_objects, update_conflicts=True, unique_fields=["pk"], update_fields=["name"], ) self.assertEqual(len(results), len(conflicting_objects)) if connection.features.can_return_rows_from_bulk_insert: for instance in results: self.assertIsNotNone(instance.pk) self.assertEqual(TwoFields.objects.count(), 2) self.assertCountEqual( TwoFields.objects.values("f1", "f2", "name"), [ {"f1": 1, "f2": 1, "name": "c"}, {"f1": 2, "f2": 2, "name": "d"}, ], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_two_fields_unique_fields_both(self): with self.assertRaises((OperationalError, ProgrammingError)): self._test_update_conflicts_two_fields(["f1", "f2"]) @skipUnlessDBFeature("supports_update_conflicts") @skipIfDBFeature("supports_update_conflicts_with_target") def test_update_conflicts_two_fields_no_unique_fields(self): self._test_update_conflicts_two_fields([]) def _test_update_conflicts_unique_two_fields(self, unique_fields): Country.objects.bulk_create(self.data) self.assertEqual(Country.objects.count(), 4) new_data = [ # Conflicting countries. Country( name="Germany", iso_two_letter="DE", description=("Germany is a country in Central Europe."), ), Country( name="Czech Republic", iso_two_letter="CZ", description=( "The Czech Republic is a landlocked country in Central Europe." ), ), # New countries. Country(name="Australia", iso_two_letter="AU"), Country( name="Japan", iso_two_letter="JP", description=("Japan is an island country in East Asia."), ), ] results = Country.objects.bulk_create( new_data, update_conflicts=True, update_fields=["description"], unique_fields=unique_fields, ) self.assertEqual(len(results), len(new_data)) if connection.features.can_return_rows_from_bulk_insert: for instance in results: self.assertIsNotNone(instance.pk) self.assertEqual(Country.objects.count(), 6) self.assertCountEqual( Country.objects.values("iso_two_letter", "description"), [ {"iso_two_letter": "US", "description": ""}, {"iso_two_letter": "NL", "description": ""}, { "iso_two_letter": "DE", "description": ("Germany is a country in Central Europe."), }, { "iso_two_letter": "CZ", "description": ( "The Czech Republic is a landlocked country in Central Europe." ), }, {"iso_two_letter": "AU", "description": ""}, { "iso_two_letter": "JP", "description": ("Japan is an island country in East Asia."), }, ], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_unique_two_fields_unique_fields_both(self): self._test_update_conflicts_unique_two_fields(["iso_two_letter", "name"]) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_unique_two_fields_unique_fields_one(self): with self.assertRaises((OperationalError, ProgrammingError)): self._test_update_conflicts_unique_two_fields(["iso_two_letter"]) @skipUnlessDBFeature("supports_update_conflicts") @skipIfDBFeature("supports_update_conflicts_with_target") def test_update_conflicts_unique_two_fields_unique_no_unique_fields(self): self._test_update_conflicts_unique_two_fields([]) def _test_update_conflicts(self, unique_fields): UpsertConflict.objects.bulk_create( [ UpsertConflict(number=1, rank=1, name="John"), UpsertConflict(number=2, rank=2, name="Mary"), UpsertConflict(number=3, rank=3, name="Hannah"), ] ) self.assertEqual(UpsertConflict.objects.count(), 3) conflicting_objects = [ UpsertConflict(number=1, rank=4, name="Steve"), UpsertConflict(number=2, rank=2, name="Olivia"), UpsertConflict(number=3, rank=1, name="Hannah"), ] results = UpsertConflict.objects.bulk_create( conflicting_objects, update_conflicts=True, update_fields=["name", "rank"], unique_fields=unique_fields, ) self.assertEqual(len(results), len(conflicting_objects)) if connection.features.can_return_rows_from_bulk_insert: for instance in results: self.assertIsNotNone(instance.pk) self.assertEqual(UpsertConflict.objects.count(), 3) self.assertCountEqual( UpsertConflict.objects.values("number", "rank", "name"), [ {"number": 1, "rank": 4, "name": "Steve"}, {"number": 2, "rank": 2, "name": "Olivia"}, {"number": 3, "rank": 1, "name": "Hannah"}, ], ) results = UpsertConflict.objects.bulk_create( conflicting_objects + [UpsertConflict(number=4, rank=4, name="Mark")], update_conflicts=True, update_fields=["name", "rank"], unique_fields=unique_fields, ) self.assertEqual(len(results), 4) if connection.features.can_return_rows_from_bulk_insert: for instance in results: self.assertIsNotNone(instance.pk) self.assertEqual(UpsertConflict.objects.count(), 4) self.assertCountEqual( UpsertConflict.objects.values("number", "rank", "name"), [ {"number": 1, "rank": 4, "name": "Steve"}, {"number": 2, "rank": 2, "name": "Olivia"}, {"number": 3, "rank": 1, "name": "Hannah"}, {"number": 4, "rank": 4, "name": "Mark"}, ], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_unique_fields(self): self._test_update_conflicts(unique_fields=["number"]) @skipUnlessDBFeature("supports_update_conflicts") @skipIfDBFeature("supports_update_conflicts_with_target") def test_update_conflicts_no_unique_fields(self): self._test_update_conflicts([]) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_unique_fields_update_fields_db_column(self): FieldsWithDbColumns.objects.bulk_create( [ FieldsWithDbColumns(rank=1, name="a"), FieldsWithDbColumns(rank=2, name="b"), ] ) self.assertEqual(FieldsWithDbColumns.objects.count(), 2) conflicting_objects = [ FieldsWithDbColumns(rank=1, name="c"),
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/pagination/models.py
tests/pagination/models.py
from django.db import models class Article(models.Model): headline = models.CharField(max_length=100, default="Default headline") pub_date = models.DateTimeField() 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/pagination/__init__.py
tests/pagination/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/pagination/tests.py
tests/pagination/tests.py
import collections.abc import inspect import pathlib import unittest.mock import warnings from datetime import datetime from django.core.paginator import ( AsyncPaginator, BasePaginator, EmptyPage, InvalidPage, PageNotAnInteger, Paginator, UnorderedObjectListWarning, ) from django.test import SimpleTestCase, TestCase from django.utils.deprecation import RemovedInDjango70Warning from .custom import AsyncValidAdjacentNumsPaginator, ValidAdjacentNumsPaginator from .models import Article class PaginationTests(SimpleTestCase): """ Tests for the Paginator and Page classes. """ def check_paginator(self, params, output): """ Helper method that instantiates a Paginator object from the passed params and then checks that its attributes match the passed output. """ count, num_pages, page_range = output paginator = Paginator(*params) self.check_attribute("count", paginator, count, params) self.check_attribute("num_pages", paginator, num_pages, params) self.check_attribute("page_range", paginator, page_range, params, coerce=list) async def check_paginator_async(self, params, output): """See check_paginator.""" count, num_pages, page_range = output paginator = AsyncPaginator(*params) await self.check_attribute_async("acount", paginator, count, params) await self.check_attribute_async("anum_pages", paginator, num_pages, params) def check_attribute(self, name, paginator, expected, params, coerce=None): """ Helper method that checks a single attribute and gives a nice error message upon test failure. """ got = getattr(paginator, name) if coerce is not None: got = coerce(got) self.assertEqual( expected, got, "For '%s', expected %s but got %s. Paginator parameters were: %s" % (name, expected, got, params), ) async def check_attribute_async(self, name, paginator, expected, params): """See check_attribute.""" got = getattr(paginator, name) self.assertEqual( expected, await got(), "For '%s', expected %s but got %s. Paginator parameters were: %s" % (name, expected, got, params), ) def get_test_cases_for_test_paginator(self): nine = [1, 2, 3, 4, 5, 6, 7, 8, 9] ten = nine + [10] eleven = ten + [11] return ( # Each item is 2-tuple: # First tuple is Paginator parameters - object_list, per_page, # orphans, and allow_empty_first_page. # Second tuple is resulting Paginator attributes - count, # num_pages, and page_range. # Ten items, varying orphans, no empty first page. ((ten, 4, 0, False), (10, 3, [1, 2, 3])), ((ten, 4, 1, False), (10, 3, [1, 2, 3])), ((ten, 4, 2, False), (10, 2, [1, 2])), # Ten items, varying orphans, allow empty first page. ((ten, 4, 0, True), (10, 3, [1, 2, 3])), ((ten, 4, 1, True), (10, 3, [1, 2, 3])), ((ten, 4, 2, True), (10, 2, [1, 2])), # One item, varying orphans, no empty first page. (([1], 4, 0, False), (1, 1, [1])), (([1], 4, 1, False), (1, 1, [1])), (([1], 4, 2, False), (1, 1, [1])), # One item, varying orphans, allow empty first page. (([1], 4, 0, True), (1, 1, [1])), (([1], 4, 1, True), (1, 1, [1])), (([1], 4, 2, True), (1, 1, [1])), # Zero items, varying orphans, no empty first page. (([], 4, 0, False), (0, 0, [])), (([], 4, 1, False), (0, 0, [])), (([], 4, 2, False), (0, 0, [])), # Zero items, varying orphans, allow empty first page. (([], 4, 0, True), (0, 1, [1])), (([], 4, 1, True), (0, 1, [1])), (([], 4, 2, True), (0, 1, [1])), # Number if items one less than per_page. (([], 1, 0, True), (0, 1, [1])), (([], 1, 0, False), (0, 0, [])), (([1], 2, 0, True), (1, 1, [1])), ((nine, 10, 0, True), (9, 1, [1])), # Number if items equal to per_page. (([1], 1, 0, True), (1, 1, [1])), (([1, 2], 2, 0, True), (2, 1, [1])), ((ten, 10, 0, True), (10, 1, [1])), # Number if items one more than per_page. (([1, 2], 1, 0, True), (2, 2, [1, 2])), (([1, 2, 3], 2, 0, True), (3, 2, [1, 2])), ((eleven, 10, 0, True), (11, 2, [1, 2])), # Number if items one more than per_page with one orphan. (([1, 2, 3], 2, 1, True), (3, 1, [1])), ((eleven, 10, 1, True), (11, 1, [1])), # Non-integer inputs ((ten, "4", 1, False), (10, 3, [1, 2, 3])), ((ten, "4", 1, False), (10, 3, [1, 2, 3])), ((ten, 4, "1", False), (10, 3, [1, 2, 3])), ((ten, 4, "1", False), (10, 3, [1, 2, 3])), ) def test_paginator(self): tests = self.get_test_cases_for_test_paginator() for params, output in tests: self.check_paginator(params, output) async def test_paginator_async(self): tests = self.get_test_cases_for_test_paginator() for params, output in tests: await self.check_paginator_async(params, output) def test_invalid_page_number(self): """ Invalid page numbers result in the correct exception being raised. """ paginator = Paginator([1, 2, 3], 2) with self.assertRaises(InvalidPage): paginator.page(3) with self.assertRaises(PageNotAnInteger): paginator.validate_number(None) with self.assertRaises(PageNotAnInteger): paginator.validate_number("x") with self.assertRaises(PageNotAnInteger): paginator.validate_number(1.2) async def test_invalid_apage_number_async(self): """See test_invalid_page_number.""" paginator = AsyncPaginator([1, 2, 3], 2) with self.assertRaises(InvalidPage): await paginator.apage(3) def test_orphans_value_larger_than_per_page_value(self): # RemovedInDjango70Warning: When the deprecation ends, replace with: # msg = ( # "The orphans argument cannot be larger than or equal to the " # "per_page argument." # ) msg = ( "Support for the orphans argument being larger than or equal to the " "per_page argument is deprecated. This will raise a ValueError in " "Django 7.0." ) for paginator_class in [Paginator, AsyncPaginator]: for orphans in [2, 3]: with self.subTest(paginator_class=paginator_class, msg=msg): # RemovedInDjango70Warning: When the deprecation ends, # replace with: # with self.assertRaisesMessage(ValueError, msg): with self.assertWarnsMessage(RemovedInDjango70Warning, msg): paginator_class([1, 2, 3], 2, orphans) def test_error_messages(self): error_messages = { "invalid_page": "Wrong page number", "min_page": "Too small", "no_results": "There is nothing here", } paginator = Paginator([1, 2, 3], 2, error_messages=error_messages) msg = "Wrong page number" with self.assertRaisesMessage(PageNotAnInteger, msg): paginator.validate_number(1.2) msg = "Too small" with self.assertRaisesMessage(EmptyPage, msg): paginator.validate_number(-1) msg = "There is nothing here" with self.assertRaisesMessage(EmptyPage, msg): paginator.validate_number(3) error_messages = {"min_page": "Too small"} paginator = Paginator([1, 2, 3], 2, error_messages=error_messages) # Custom message. msg = "Too small" with self.assertRaisesMessage(EmptyPage, msg): paginator.validate_number(-1) # Default message. msg = "That page contains no results" with self.assertRaisesMessage(EmptyPage, msg): paginator.validate_number(3) def test_float_integer_page(self): paginator = Paginator([1, 2, 3], 2) self.assertEqual(paginator.validate_number(1.0), 1) def test_no_content_allow_empty_first_page(self): # With no content and allow_empty_first_page=True, 1 is a valid page. paginator = Paginator([], 2) self.assertEqual(paginator.validate_number(1), 1) def test_paginate_misc_classes(self): class CountContainer: def count(self): return 42 # Paginator can be passed other objects with a count() method. paginator = Paginator(CountContainer(), 10) self.assertEqual(42, paginator.count) self.assertEqual(5, paginator.num_pages) self.assertEqual([1, 2, 3, 4, 5], list(paginator.page_range)) # Paginator can be passed other objects that implement __len__. class LenContainer: def __len__(self): return 42 paginator = Paginator(LenContainer(), 10) self.assertEqual(42, paginator.count) self.assertEqual(5, paginator.num_pages) self.assertEqual([1, 2, 3, 4, 5], list(paginator.page_range)) async def test_paginate_misc_classes_async(self): class CountContainer: async def acount(self): return 42 # AsyncPaginator can be passed other objects with an acount() method. paginator = AsyncPaginator(CountContainer(), 10) self.assertEqual(42, await paginator.acount()) self.assertEqual(5, await paginator.anum_pages()) self.assertEqual([1, 2, 3, 4, 5], list(await paginator.apage_range())) # AsyncPaginator can be passed other objects that implement __len__. class LenContainer: def __len__(self): return 42 paginator = AsyncPaginator(LenContainer(), 10) self.assertEqual(42, await paginator.acount()) self.assertEqual(5, await paginator.anum_pages()) self.assertEqual([1, 2, 3, 4, 5], list(await paginator.apage_range())) def test_count_does_not_silence_attribute_error(self): class AttributeErrorContainer: def count(self): raise AttributeError("abc") with self.assertRaisesMessage(AttributeError, "abc"): Paginator(AttributeErrorContainer(), 10).count async def test_acount_does_not_silence_attribute_error_async(self): class AttributeErrorContainer: async def acount(self): raise AttributeError("abc") with self.assertRaisesMessage(AttributeError, "abc"): await AsyncPaginator(AttributeErrorContainer(), 10).acount() def test_count_does_not_silence_type_error(self): class TypeErrorContainer: def count(self): raise TypeError("abc") with self.assertRaisesMessage(TypeError, "abc"): Paginator(TypeErrorContainer(), 10).count async def test_acount_does_not_silence_type_error_async(self): class TypeErrorContainer: async def acount(self): raise TypeError("abc") with self.assertRaisesMessage(TypeError, "abc"): await AsyncPaginator(TypeErrorContainer(), 10).acount() def check_indexes(self, params, page_num, indexes): """ Helper method that instantiates a Paginator object from the passed params and then checks that the start and end indexes of the passed page_num match those given as a 2-tuple in indexes. """ paginator = Paginator(*params) if page_num == "first": page_num = 1 elif page_num == "last": page_num = paginator.num_pages page = paginator.page(page_num) start, end = indexes msg = "For %s of page %s, expected %s but got %s. Paginator parameters were: %s" self.assertEqual( start, page.start_index(), msg % ("start index", page_num, start, page.start_index(), params), ) self.assertEqual( end, page.end_index(), msg % ("end index", page_num, end, page.end_index(), params), ) async def check_indexes_async(self, params, page_num, indexes): """See check_indexes.""" paginator = AsyncPaginator(*params) if page_num == "first": page_num = 1 elif page_num == "last": page_num = await paginator.anum_pages() page = await paginator.apage(page_num) start, end = indexes msg = "For %s of page %s, expected %s but got %s. Paginator parameters were: %s" self.assertEqual( start, await page.astart_index(), msg % ("start index", page_num, start, await page.astart_index(), params), ) self.assertEqual( end, await page.aend_index(), msg % ("end index", page_num, end, await page.aend_index(), params), ) def get_test_cases_for_test_page_indexes(self): ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] return ( # Each item is 3-tuple: # First tuple is Paginator parameters - object_list, per_page, # orphans, and allow_empty_first_page. # Second tuple is the start and end indexes of the first page. # Third tuple is the start and end indexes of the last page. # Ten items, varying per_page, no orphans. ((ten, 1, 0, True), (1, 1), (10, 10)), ((ten, 2, 0, True), (1, 2), (9, 10)), ((ten, 3, 0, True), (1, 3), (10, 10)), ((ten, 5, 0, True), (1, 5), (6, 10)), # Ten items, varying per_page, with orphans. ((ten, 3, 1, True), (1, 3), (7, 10)), ((ten, 3, 2, True), (1, 3), (7, 10)), ((ten, 5, 1, True), (1, 5), (6, 10)), ((ten, 5, 2, True), (1, 5), (6, 10)), # One item, varying orphans, no empty first page. (([1], 4, 0, False), (1, 1), (1, 1)), (([1], 4, 1, False), (1, 1), (1, 1)), (([1], 4, 2, False), (1, 1), (1, 1)), # One item, varying orphans, allow empty first page. (([1], 4, 0, True), (1, 1), (1, 1)), (([1], 4, 1, True), (1, 1), (1, 1)), (([1], 4, 2, True), (1, 1), (1, 1)), # Zero items, varying orphans, allow empty first page. (([], 4, 0, True), (0, 0), (0, 0)), (([], 4, 1, True), (0, 0), (0, 0)), (([], 4, 2, True), (0, 0), (0, 0)), ) def test_page_indexes(self): """ Paginator pages have the correct start and end indexes. """ tests = self.get_test_cases_for_test_page_indexes() for params, first, last in tests: self.check_indexes(params, "first", first) self.check_indexes(params, "last", last) # When no items and no empty first page, we should get EmptyPage error. with self.assertRaises(EmptyPage): self.check_indexes(([], 4, 0, False), 1, None) with self.assertRaises(EmptyPage): self.check_indexes(([], 4, 1, False), 1, None) with self.assertRaises(EmptyPage): self.check_indexes(([], 4, 2, False), 1, None) async def test_page_indexes_async(self): """See test_page_indexes""" tests = self.get_test_cases_for_test_page_indexes() for params, first, last in tests: await self.check_indexes_async(params, "first", first) await self.check_indexes_async(params, "last", last) # When no items and no empty first page, we should get EmptyPage error. with self.assertRaises(EmptyPage): await self.check_indexes_async(([], 4, 0, False), 1, None) with self.assertRaises(EmptyPage): await self.check_indexes_async(([], 4, 1, False), 1, None) with self.assertRaises(EmptyPage): await self.check_indexes_async(([], 4, 2, False), 1, None) def test_page_sequence(self): """ A paginator page acts like a standard sequence. """ eleven = "abcdefghijk" page2 = Paginator(eleven, per_page=5, orphans=1).page(2) self.assertEqual(len(page2), 6) self.assertIn("k", page2) self.assertNotIn("a", page2) self.assertEqual("".join(page2), "fghijk") self.assertEqual("".join(reversed(page2)), "kjihgf") async def test_page_sequence_async(self): eleven = "abcdefghijk" page2 = await AsyncPaginator(eleven, per_page=5, orphans=1).apage(2) await page2.aget_object_list() self.assertEqual(len(page2), 6) self.assertIn("k", page2) self.assertNotIn("a", page2) self.assertEqual("".join(page2), "fghijk") self.assertEqual("".join(reversed(page2)), "kjihgf") def test_get_page_hook(self): """ A Paginator subclass can use the ``_get_page`` hook to return an alternative to the standard Page class. """ eleven = "abcdefghijk" paginator = ValidAdjacentNumsPaginator(eleven, per_page=6) page1 = paginator.page(1) page2 = paginator.page(2) self.assertIsNone(page1.previous_page_number()) self.assertEqual(page1.next_page_number(), 2) self.assertEqual(page2.previous_page_number(), 1) self.assertIsNone(page2.next_page_number()) async def test_get_page_hook_async(self): """ An AsyncPaginator subclass can use the ``_get_page`` hook to return an alternative to the standard AsyncPage class. """ eleven = "abcdefghijk" paginator = AsyncValidAdjacentNumsPaginator(eleven, per_page=6) page1 = await paginator.apage(1) page2 = await paginator.apage(2) self.assertIsNone(await page1.aprevious_page_number()) self.assertEqual(await page1.anext_page_number(), 2) self.assertEqual(await page2.aprevious_page_number(), 1) self.assertIsNone(await page2.anext_page_number()) def test_page_range_iterator(self): """ Paginator.page_range should be an iterator. """ self.assertIsInstance(Paginator([1, 2, 3], 2).page_range, type(range(0))) def test_get_page(self): """ Paginator.get_page() returns a valid page even with invalid page arguments. """ paginator = Paginator([1, 2, 3], 2) page = paginator.get_page(1) self.assertEqual(page.number, 1) self.assertEqual(page.object_list, [1, 2]) # An empty page returns the last page. self.assertEqual(paginator.get_page(3).number, 2) # Non-integer page returns the first page. self.assertEqual(paginator.get_page(None).number, 1) async def test_aget_page_async(self): """ AsyncPaginator.aget_page() returns a valid page even with invalid page arguments. """ paginator = AsyncPaginator([1, 2, 3], 2) page = await paginator.aget_page(1) self.assertEqual(page.number, 1) self.assertEqual(page.object_list, [1, 2]) # An empty page returns the last page. self.assertEqual((await paginator.aget_page(3)).number, 2) # Non-integer page returns the first page. self.assertEqual((await paginator.aget_page(None)).number, 1) def test_get_page_empty_object_list(self): """Paginator.get_page() with an empty object_list.""" paginator = Paginator([], 2) # An empty page returns the last page. self.assertEqual(paginator.get_page(1).number, 1) self.assertEqual(paginator.get_page(2).number, 1) # Non-integer page returns the first page. self.assertEqual(paginator.get_page(None).number, 1) async def test_aget_page_empty_object_list_async(self): """AsyncPaginator.aget_page() with an empty object_list.""" paginator = AsyncPaginator([], 2) # An empty page returns the last page. self.assertEqual((await paginator.aget_page(1)).number, 1) self.assertEqual((await paginator.aget_page(2)).number, 1) # Non-integer page returns the first page. self.assertEqual((await paginator.aget_page(None)).number, 1) def test_get_page_empty_object_list_and_allow_empty_first_page_false(self): """ Paginator.get_page() raises EmptyPage if allow_empty_first_page=False and object_list is empty. """ paginator = Paginator([], 2, allow_empty_first_page=False) with self.assertRaises(EmptyPage): paginator.get_page(1) async def test_aget_page_empty_obj_list_and_allow_empty_first_page_false_async( self, ): """ AsyncPaginator.aget_page() raises EmptyPage if allow_empty_first_page=False and object_list is empty. """ paginator = AsyncPaginator([], 2, allow_empty_first_page=False) with self.assertRaises(EmptyPage): await paginator.aget_page(1) def test_paginator_iteration(self): paginator = Paginator([1, 2, 3], 2) page_iterator = iter(paginator) for page, expected in enumerate(([1, 2], [3]), start=1): with self.subTest(page=page): self.assertEqual(expected, list(next(page_iterator))) self.assertEqual( [str(page) for page in iter(paginator)], ["<Page 1 of 2>", "<Page 2 of 2>"], ) async def test_paginator_iteration_async(self): paginator = AsyncPaginator([1, 2, 3], 2) page_iterator = aiter(paginator) for page, expected in enumerate(([1, 2], [3]), start=1): with self.subTest(page=page): async_page = await anext(page_iterator) self.assertEqual(expected, [obj async for obj in async_page]) self.assertEqual( [str(page) async for page in aiter(paginator)], ["<Async Page 1>", "<Async Page 2>"], ) def get_test_cases_for_test_get_elided_page_range(self): ELLIPSIS = Paginator.ELLIPSIS return [ # on_each_side=2, on_ends=1 (1, 2, 1, [1, 2, 3, ELLIPSIS, 50]), (4, 2, 1, [1, 2, 3, 4, 5, 6, ELLIPSIS, 50]), (5, 2, 1, [1, 2, 3, 4, 5, 6, 7, ELLIPSIS, 50]), (6, 2, 1, [1, ELLIPSIS, 4, 5, 6, 7, 8, ELLIPSIS, 50]), (45, 2, 1, [1, ELLIPSIS, 43, 44, 45, 46, 47, ELLIPSIS, 50]), (46, 2, 1, [1, ELLIPSIS, 44, 45, 46, 47, 48, 49, 50]), (47, 2, 1, [1, ELLIPSIS, 45, 46, 47, 48, 49, 50]), (50, 2, 1, [1, ELLIPSIS, 48, 49, 50]), # on_each_side=1, on_ends=3 (1, 1, 3, [1, 2, ELLIPSIS, 48, 49, 50]), (5, 1, 3, [1, 2, 3, 4, 5, 6, ELLIPSIS, 48, 49, 50]), (6, 1, 3, [1, 2, 3, 4, 5, 6, 7, ELLIPSIS, 48, 49, 50]), (7, 1, 3, [1, 2, 3, ELLIPSIS, 6, 7, 8, ELLIPSIS, 48, 49, 50]), (44, 1, 3, [1, 2, 3, ELLIPSIS, 43, 44, 45, ELLIPSIS, 48, 49, 50]), (45, 1, 3, [1, 2, 3, ELLIPSIS, 44, 45, 46, 47, 48, 49, 50]), (46, 1, 3, [1, 2, 3, ELLIPSIS, 45, 46, 47, 48, 49, 50]), (50, 1, 3, [1, 2, 3, ELLIPSIS, 49, 50]), # on_each_side=4, on_ends=0 (1, 4, 0, [1, 2, 3, 4, 5, ELLIPSIS]), (5, 4, 0, [1, 2, 3, 4, 5, 6, 7, 8, 9, ELLIPSIS]), (6, 4, 0, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ELLIPSIS]), (7, 4, 0, [ELLIPSIS, 3, 4, 5, 6, 7, 8, 9, 10, 11, ELLIPSIS]), (44, 4, 0, [ELLIPSIS, 40, 41, 42, 43, 44, 45, 46, 47, 48, ELLIPSIS]), (45, 4, 0, [ELLIPSIS, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]), (46, 4, 0, [ELLIPSIS, 42, 43, 44, 45, 46, 47, 48, 49, 50]), (50, 4, 0, [ELLIPSIS, 46, 47, 48, 49, 50]), # on_each_side=0, on_ends=1 (1, 0, 1, [1, ELLIPSIS, 50]), (2, 0, 1, [1, 2, ELLIPSIS, 50]), (3, 0, 1, [1, 2, 3, ELLIPSIS, 50]), (4, 0, 1, [1, ELLIPSIS, 4, ELLIPSIS, 50]), (47, 0, 1, [1, ELLIPSIS, 47, ELLIPSIS, 50]), (48, 0, 1, [1, ELLIPSIS, 48, 49, 50]), (49, 0, 1, [1, ELLIPSIS, 49, 50]), (50, 0, 1, [1, ELLIPSIS, 50]), # on_each_side=0, on_ends=0 (1, 0, 0, [1, ELLIPSIS]), (2, 0, 0, [1, 2, ELLIPSIS]), (3, 0, 0, [ELLIPSIS, 3, ELLIPSIS]), (48, 0, 0, [ELLIPSIS, 48, ELLIPSIS]), (49, 0, 0, [ELLIPSIS, 49, 50]), (50, 0, 0, [ELLIPSIS, 50]), ] def test_get_elided_page_range(self): # Paginator.validate_number() must be called: paginator = Paginator([1, 2, 3], 2) with unittest.mock.patch.object(paginator, "validate_number") as mock: mock.assert_not_called() list(paginator.get_elided_page_range(2)) mock.assert_called_with(2) ELLIPSIS = Paginator.ELLIPSIS # Range is not elided if not enough pages when using default arguments: paginator = Paginator(range(10 * 100), 100) page_range = paginator.get_elided_page_range(1) self.assertIsInstance(page_range, collections.abc.Generator) self.assertNotIn(ELLIPSIS, page_range) paginator = Paginator(range(10 * 100 + 1), 100) self.assertIsInstance(page_range, collections.abc.Generator) page_range = paginator.get_elided_page_range(1) self.assertIn(ELLIPSIS, page_range) # Range should be elided if enough pages when using default arguments: tests = [ # on_each_side=3, on_ends=2 (1, [1, 2, 3, 4, ELLIPSIS, 49, 50]), (6, [1, 2, 3, 4, 5, 6, 7, 8, 9, ELLIPSIS, 49, 50]), (7, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ELLIPSIS, 49, 50]), (8, [1, 2, ELLIPSIS, 5, 6, 7, 8, 9, 10, 11, ELLIPSIS, 49, 50]), (43, [1, 2, ELLIPSIS, 40, 41, 42, 43, 44, 45, 46, ELLIPSIS, 49, 50]), (44, [1, 2, ELLIPSIS, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]), (45, [1, 2, ELLIPSIS, 42, 43, 44, 45, 46, 47, 48, 49, 50]), (50, [1, 2, ELLIPSIS, 47, 48, 49, 50]), ] paginator = Paginator(range(5000), 100) for number, expected in tests: with self.subTest(number=number): page_range = paginator.get_elided_page_range(number) self.assertIsInstance(page_range, collections.abc.Generator) self.assertEqual(list(page_range), expected) # Range is not elided if not enough pages when using custom arguments: tests = [ (6, 2, 1, 1), (8, 1, 3, 1), (8, 4, 0, 1), (4, 1, 1, 1), # When on_each_side and on_ends are both <= 1 but not both == 1 it # is a special case where the range is not elided until an extra # page is added. (2, 0, 1, 2), (2, 1, 0, 2), (1, 0, 0, 2), ] for pages, on_each_side, on_ends, elided_after in tests: for offset in range(elided_after + 1): with self.subTest( pages=pages, offset=elided_after, on_each_side=on_each_side, on_ends=on_ends, ): paginator = Paginator(range((pages + offset) * 100), 100) page_range = paginator.get_elided_page_range( 1, on_each_side=on_each_side, on_ends=on_ends, ) self.assertIsInstance(page_range, collections.abc.Generator) if offset < elided_after: self.assertNotIn(ELLIPSIS, page_range) else: self.assertIn(ELLIPSIS, page_range) # Range should be elided if enough pages when using custom arguments: tests = self.get_test_cases_for_test_get_elided_page_range() paginator = Paginator(range(5000), 100) for number, on_each_side, on_ends, expected in tests: with self.subTest( number=number, on_each_side=on_each_side, on_ends=on_ends ): page_range = paginator.get_elided_page_range( number, on_each_side=on_each_side, on_ends=on_ends, ) self.assertIsInstance(page_range, collections.abc.Generator) self.assertEqual(list(page_range), expected) async def test_aget_elided_page_range_async(self): # AsyncPaginator.avalidate_number() must be called: paginator = AsyncPaginator([1, 2, 3], 2) with unittest.mock.patch.object(paginator, "avalidate_number") as mock: mock.assert_not_called() [p async for p in paginator.aget_elided_page_range(2)] mock.assert_called_with(2) ELLIPSIS = Paginator.ELLIPSIS # Range is not elided if not enough pages when using default arguments: paginator = AsyncPaginator(range(10 * 100), 100) page_range = paginator.aget_elided_page_range(1) self.assertIsInstance(page_range, collections.abc.AsyncGenerator) self.assertNotIn(ELLIPSIS, [p async for p in page_range]) paginator = AsyncPaginator(range(10 * 100 + 1), 100) self.assertIsInstance(page_range, collections.abc.AsyncGenerator) page_range = paginator.aget_elided_page_range(1) self.assertIn(ELLIPSIS, [p async for p in page_range]) # Range should be elided if enough pages when using default arguments: tests = [ # on_each_side=3, on_ends=2 (1, [1, 2, 3, 4, ELLIPSIS, 49, 50]), (6, [1, 2, 3, 4, 5, 6, 7, 8, 9, ELLIPSIS, 49, 50]), (7, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ELLIPSIS, 49, 50]), (8, [1, 2, ELLIPSIS, 5, 6, 7, 8, 9, 10, 11, ELLIPSIS, 49, 50]), (43, [1, 2, ELLIPSIS, 40, 41, 42, 43, 44, 45, 46, ELLIPSIS, 49, 50]), (44, [1, 2, ELLIPSIS, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]), (45, [1, 2, ELLIPSIS, 42, 43, 44, 45, 46, 47, 48, 49, 50]), (50, [1, 2, ELLIPSIS, 47, 48, 49, 50]), ] paginator = AsyncPaginator(range(5000), 100) for number, expected in tests: with self.subTest(number=number): page_range = paginator.aget_elided_page_range(number) self.assertIsInstance(page_range, collections.abc.AsyncGenerator) self.assertEqual([p async for p in page_range], expected) # Range is not elided if not enough pages when using custom arguments: tests = [ (6, 2, 1, 1), (8, 1, 3, 1), (8, 4, 0, 1), (4, 1, 1, 1), # When on_each_side and on_ends are both <= 1 but not both == 1 it # is a special case where the range is not elided until an extra # page is added. (2, 0, 1, 2), (2, 1, 0, 2), (1, 0, 0, 2), ] for pages, on_each_side, on_ends, elided_after in tests: for offset in range(elided_after + 1): with self.subTest( pages=pages, offset=elided_after, on_each_side=on_each_side, on_ends=on_ends, ): paginator = AsyncPaginator(range((pages + offset) * 100), 100) page_range = paginator.aget_elided_page_range( 1, on_each_side=on_each_side, on_ends=on_ends, ) self.assertIsInstance(page_range, collections.abc.AsyncGenerator) page_list = [p async for p in page_range] if offset < elided_after: self.assertNotIn(ELLIPSIS, page_list) else: self.assertIn(ELLIPSIS, page_list) # Range should be elided if enough pages when using custom arguments: tests = self.get_test_cases_for_test_get_elided_page_range() paginator = AsyncPaginator(range(5000), 100)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/pagination/custom.py
tests/pagination/custom.py
from django.core.paginator import AsyncPage, AsyncPaginator, Page, Paginator class ValidAdjacentNumsPage(Page): def next_page_number(self): if not self.has_next(): return None return super().next_page_number() def previous_page_number(self): if not self.has_previous(): return None return super().previous_page_number() class ValidAdjacentNumsPaginator(Paginator): def _get_page(self, *args, **kwargs): return ValidAdjacentNumsPage(*args, **kwargs) class AsyncValidAdjacentNumsPage(AsyncPage): async def anext_page_number(self): if not await self.ahas_next(): return None return await super().anext_page_number() async def aprevious_page_number(self): if not await self.ahas_previous(): return None return await super().aprevious_page_number() class AsyncValidAdjacentNumsPaginator(AsyncPaginator): def _get_page(self, *args, **kwargs): return AsyncValidAdjacentNumsPage(*args, **kwargs)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/order_with_respect_to/models.py
tests/order_with_respect_to/models.py
""" Tests for the order_with_respect_to Meta attribute. """ from django.db import models class Question(models.Model): text = models.CharField(max_length=200) class Answer(models.Model): text = models.CharField(max_length=200) question = models.ForeignKey(Question, models.CASCADE) class Meta: order_with_respect_to = "question" def __str__(self): return self.text class Post(models.Model): title = models.CharField(max_length=200) parent = models.ForeignKey( "self", models.SET_NULL, related_name="children", null=True ) class Meta: order_with_respect_to = "parent" def __str__(self): return self.title # order_with_respect_to points to a model with a OneToOneField primary key. class Entity(models.Model): pass class Dimension(models.Model): entity = models.OneToOneField("Entity", primary_key=True, on_delete=models.CASCADE) class Component(models.Model): dimension = models.ForeignKey("Dimension", on_delete=models.CASCADE) class Meta: order_with_respect_to = "dimension"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/order_with_respect_to/base_tests.py
tests/order_with_respect_to/base_tests.py
""" The tests are shared with contenttypes_tests and so shouldn't import or reference any models directly. Subclasses should inherit django.test.TestCase. """ from operator import attrgetter class BaseOrderWithRespectToTests: databases = {"default", "other"} # Hook to allow subclasses to run these tests with alternate models. Answer = None Post = None Question = None @classmethod def setUpTestData(cls): cls.q1 = cls.Question.objects.create( text="Which Beatle starts with the letter 'R'?" ) cls.Answer.objects.create(text="John", question=cls.q1) cls.Answer.objects.create(text="Paul", question=cls.q1) cls.Answer.objects.create(text="George", question=cls.q1) cls.Answer.objects.create(text="Ringo", question=cls.q1) def test_default_to_insertion_order(self): # Answers will always be ordered in the order they were inserted. self.assertQuerySetEqual( self.q1.answer_set.all(), [ "John", "Paul", "George", "Ringo", ], attrgetter("text"), ) def test_previous_and_next_in_order(self): # We can retrieve the answers related to a particular object, in the # order they were created, once we have a particular object. a1 = self.q1.answer_set.all()[0] self.assertEqual(a1.text, "John") self.assertEqual(a1.get_next_in_order().text, "Paul") a2 = list(self.q1.answer_set.all())[-1] self.assertEqual(a2.text, "Ringo") self.assertEqual(a2.get_previous_in_order().text, "George") def test_item_ordering(self): # We can retrieve the ordering of the queryset from a particular item. a1 = self.q1.answer_set.all()[1] id_list = [o.pk for o in self.q1.answer_set.all()] self.assertSequenceEqual(a1.question.get_answer_order(), id_list) # It doesn't matter which answer we use to check the order, it will # always be the same. a2 = self.Answer.objects.create(text="Number five", question=self.q1) self.assertEqual( list(a1.question.get_answer_order()), list(a2.question.get_answer_order()) ) def test_set_order_unrelated_object(self): """An answer that's not related isn't updated.""" q = self.Question.objects.create(text="other") a = self.Answer.objects.create(text="Number five", question=q) self.q1.set_answer_order([o.pk for o in self.q1.answer_set.all()] + [a.pk]) self.assertEqual(self.Answer.objects.get(pk=a.pk)._order, 0) def test_change_ordering(self): # The ordering can be altered a = self.Answer.objects.create(text="Number five", question=self.q1) # Swap the last two items in the order list id_list = [o.pk for o in self.q1.answer_set.all()] x = id_list.pop() id_list.insert(-1, x) # By default, the ordering is different from the swapped version self.assertNotEqual(list(a.question.get_answer_order()), id_list) # Change the ordering to the swapped version - # this changes the ordering of the queryset. a.question.set_answer_order(id_list) self.assertQuerySetEqual( self.q1.answer_set.all(), ["John", "Paul", "George", "Number five", "Ringo"], attrgetter("text"), ) def test_recursive_ordering(self): p1 = self.Post.objects.create(title="1") p2 = self.Post.objects.create(title="2") p1_1 = self.Post.objects.create(title="1.1", parent=p1) p1_2 = self.Post.objects.create(title="1.2", parent=p1) self.Post.objects.create(title="2.1", parent=p2) p1_3 = self.Post.objects.create(title="1.3", parent=p1) self.assertSequenceEqual(p1.get_post_order(), [p1_1.pk, p1_2.pk, p1_3.pk]) def test_delete_and_insert(self): q1 = self.Question.objects.create(text="What is your favorite color?") q2 = self.Question.objects.create(text="What color is it?") a1 = self.Answer.objects.create(text="Blue", question=q1) a2 = self.Answer.objects.create(text="Red", question=q1) a3 = self.Answer.objects.create(text="Green", question=q1) a4 = self.Answer.objects.create(text="Yellow", question=q1) self.assertSequenceEqual(q1.answer_set.all(), [a1, a2, a3, a4]) a3.question = q2 a3.save() a1.delete() new_answer = self.Answer.objects.create(text="Black", question=q1) self.assertSequenceEqual(q1.answer_set.all(), [a2, a4, new_answer]) def test_database_routing(self): class WriteToOtherRouter: def db_for_write(self, model, **hints): return "other" with self.settings(DATABASE_ROUTERS=[WriteToOtherRouter()]): with ( self.assertNumQueries(0, using="default"), self.assertNumQueries( 1, using="other", ), ): self.q1.set_answer_order([3, 1, 2, 4]) def test_bulk_create_with_empty_parent(self): """ bulk_create() should properly set _order when parent has no existing children. """ question = self.Question.objects.create(text="Test Question") answers = [self.Answer(question=question, text=f"Answer {i}") for i in range(3)] answer0, answer1, answer2 = self.Answer.objects.bulk_create(answers) self.assertEqual(answer0._order, 0) self.assertEqual(answer1._order, 1) self.assertEqual(answer2._order, 2) def test_bulk_create_with_existing_children(self): """ bulk_create() should continue _order sequence from existing children. """ question = self.Question.objects.create(text="Test Question") self.Answer.objects.create(question=question, text="Existing 0") self.Answer.objects.create(question=question, text="Existing 1") new_answers = [ self.Answer(question=question, text=f"New Answer {i}") for i in range(2) ] answer2, answer3 = self.Answer.objects.bulk_create(new_answers) self.assertEqual(answer2._order, 2) self.assertEqual(answer3._order, 3) def test_bulk_create_multiple_parents(self): """ bulk_create() should maintain separate _order sequences for different parents. """ question0 = self.Question.objects.create(text="Question 0") question1 = self.Question.objects.create(text="Question 1") answers = [ self.Answer(question=question0, text="Q0 Answer 0"), self.Answer(question=question1, text="Q1 Answer 0"), self.Answer(question=question0, text="Q0 Answer 1"), self.Answer(question=question1, text="Q1 Answer 1"), ] created_answers = self.Answer.objects.bulk_create(answers) answer_q0_0, answer_q1_0, answer_q0_1, answer_q1_1 = created_answers self.assertEqual(answer_q0_0._order, 0) self.assertEqual(answer_q0_1._order, 1) self.assertEqual(answer_q1_0._order, 0) self.assertEqual(answer_q1_1._order, 1) def test_bulk_create_mixed_scenario(self): """ The _order field should be correctly set for new Answer objects based on the count of existing Answers for each related Question. """ question0 = self.Question.objects.create(text="Question 0") question1 = self.Question.objects.create(text="Question 1") self.Answer.objects.create(question=question1, text="Q1 Existing 0") self.Answer.objects.create(question=question1, text="Q1 Existing 1") new_answers = [ self.Answer(question=question0, text="Q0 New 0"), self.Answer(question=question1, text="Q1 New 0"), self.Answer(question=question0, text="Q0 New 1"), ] created_answers = self.Answer.objects.bulk_create(new_answers) answer_q0_0, answer_q1_2, answer_q0_1 = created_answers self.assertEqual(answer_q0_0._order, 0) self.assertEqual(answer_q0_1._order, 1) self.assertEqual(answer_q1_2._order, 2) def test_bulk_create_respects_mixed_manual_order(self): """ bulk_create() should assign _order automatically only for instances where it is not manually set. Mixed objects with and without _order should result in expected final order values. """ question_a = self.Question.objects.create(text="Question A") question_b = self.Question.objects.create(text="Question B") # Existing answers to push initial _order forward. self.Answer.objects.create(question=question_a, text="Q-A Existing 0") self.Answer.objects.create(question=question_b, text="Q-B Existing 0") self.Answer.objects.create(question=question_b, text="Q-B Existing 1") answers = [ self.Answer(question=question_a, text="Q-A Manual 4", _order=4), self.Answer(question=question_b, text="Q-B Auto 2"), self.Answer(question=question_a, text="Q-A Auto"), self.Answer(question=question_b, text="Q-B Manual 10", _order=10), self.Answer(question=question_a, text="Q-A Manual 7", _order=7), self.Answer(question=question_b, text="Q-B Auto 3"), ] created_answers = self.Answer.objects.bulk_create(answers) ( qa_manual_4, qb_auto_2, qa_auto, qb_manual_10, qa_manual_7, qb_auto_3, ) = created_answers # Manual values should stay untouched. self.assertEqual(qa_manual_4._order, 4) self.assertEqual(qb_manual_10._order, 10) self.assertEqual(qa_manual_7._order, 7) # Existing max was 0 → auto should get _order=1. self.assertEqual(qa_auto._order, 1) # Existing max was 1 → next auto gets 2, then 3 (manual 10 is skipped). self.assertEqual(qb_auto_2._order, 2) self.assertEqual(qb_auto_3._order, 3) def test_bulk_create_allows_duplicate_order_values(self): """ bulk_create() should allow duplicate _order values if the model does not enforce uniqueness on the _order field. """ question = self.Question.objects.create(text="Duplicated Test") # Existing answer to set initial _order=0. self.Answer.objects.create(question=question, text="Existing Answer") # Two manually set _order=1 and one auto (which may also be assigned # 1). answers = [ self.Answer(question=question, text="Manual Order 1", _order=1), self.Answer(question=question, text="Auto Order 1"), self.Answer(question=question, text="Auto Order 2"), self.Answer(question=question, text="Manual Order 1 Duplicate", _order=1), ] created_answers = self.Answer.objects.bulk_create(answers) manual_1, auto_1, auto_2, manual_2 = created_answers # Manual values are as assigned, even if duplicated. self.assertEqual(manual_1._order, 1) self.assertEqual(manual_2._order, 1) # Auto-assigned orders may also use 1 or any value, depending on # implementation. If no collision logic, they may overlap with manual # values. self.assertEqual(auto_1._order, 1) self.assertEqual(auto_2._order, 2)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/order_with_respect_to/__init__.py
tests/order_with_respect_to/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/order_with_respect_to/tests.py
tests/order_with_respect_to/tests.py
from operator import attrgetter from django.db import models from django.test import SimpleTestCase, TestCase from django.test.utils import isolate_apps from .base_tests import BaseOrderWithRespectToTests from .models import Answer, Dimension, Entity, Post, Question class OrderWithRespectToBaseTests(BaseOrderWithRespectToTests, TestCase): Answer = Answer Post = Post Question = Question class OrderWithRespectToTests(SimpleTestCase): @isolate_apps("order_with_respect_to") def test_duplicate_order_field(self): class Bar(models.Model): class Meta: app_label = "order_with_respect_to" class Foo(models.Model): bar = models.ForeignKey(Bar, models.CASCADE) order = models.OrderWrt() class Meta: order_with_respect_to = "bar" app_label = "order_with_respect_to" count = 0 for field in Foo._meta.local_fields: if isinstance(field, models.OrderWrt): count += 1 self.assertEqual(count, 1) class TestOrderWithRespectToOneToOnePK(TestCase): def test_set_order(self): e = Entity.objects.create() d = Dimension.objects.create(entity=e) c1 = d.component_set.create() c2 = d.component_set.create() d.set_component_order([c1.id, c2.id]) self.assertQuerySetEqual( d.component_set.all(), [c1.id, c2.id], attrgetter("pk") )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/inspectdb/models.py
tests/inspectdb/models.py
from django.db import connection, models from django.db.models.functions import Lower from django.utils.functional import SimpleLazyObject class People(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey("self", models.CASCADE) class Message(models.Model): from_field = models.ForeignKey(People, models.CASCADE, db_column="from_id") author = models.ForeignKey(People, models.CASCADE, related_name="message_authors") class PeopleData(models.Model): people_pk = models.ForeignKey(People, models.CASCADE, primary_key=True) ssn = models.CharField(max_length=11) class PeopleMoreData(models.Model): people_unique = models.ForeignKey(People, models.CASCADE, unique=True) message = models.ForeignKey(Message, models.CASCADE, blank=True, null=True) license = models.CharField(max_length=255) class ForeignKeyToField(models.Model): to_field_fk = models.ForeignKey( PeopleMoreData, models.CASCADE, to_field="people_unique", ) class DigitsInColumnName(models.Model): all_digits = models.CharField(max_length=11, db_column="123") leading_digit = models.CharField(max_length=11, db_column="4extra") leading_digits = models.CharField(max_length=11, db_column="45extra") class SpecialName(models.Model): field = models.IntegerField(db_column="field") # Underscores field_field_0 = models.IntegerField(db_column="Field_") field_field_1 = models.IntegerField(db_column="Field__") field_field_2 = models.IntegerField(db_column="__field") # Other chars prc_x = models.IntegerField(db_column="prc(%) x") non_ascii = models.IntegerField(db_column="tamaño") class Meta: db_table = "inspectdb_special.table name" class PascalCaseName(models.Model): class Meta: db_table = "inspectdb_pascal.PascalCase" class ColumnTypes(models.Model): id = models.AutoField(primary_key=True) big_int_field = models.BigIntegerField() bool_field = models.BooleanField(default=False) null_bool_field = models.BooleanField(null=True) char_field = models.CharField(max_length=10) null_char_field = models.CharField(max_length=10, blank=True, null=True) date_field = models.DateField() date_time_field = models.DateTimeField() decimal_field = models.DecimalField(max_digits=6, decimal_places=1) email_field = models.EmailField() file_field = models.FileField(upload_to="unused") file_path_field = models.FilePathField() float_field = models.FloatField() int_field = models.IntegerField() gen_ip_address_field = models.GenericIPAddressField(protocol="ipv4") pos_big_int_field = models.PositiveBigIntegerField() pos_int_field = models.PositiveIntegerField() pos_small_int_field = models.PositiveSmallIntegerField() slug_field = models.SlugField() small_int_field = models.SmallIntegerField() text_field = models.TextField() time_field = models.TimeField() url_field = models.URLField() uuid_field = models.UUIDField() class JSONFieldColumnType(models.Model): json_field = models.JSONField() null_json_field = models.JSONField(blank=True, null=True) class Meta: required_db_features = { "can_introspect_json_field", "supports_json_field", } test_collation = SimpleLazyObject( lambda: connection.features.test_collations.get("non_default") ) class CharFieldDbCollation(models.Model): char_field = models.CharField(max_length=10, db_collation=test_collation) class Meta: required_db_features = {"supports_collation_on_charfield"} class TextFieldDbCollation(models.Model): text_field = models.TextField(db_collation=test_collation) class Meta: required_db_features = {"supports_collation_on_textfield"} class CharFieldUnlimited(models.Model): char_field = models.CharField(max_length=None) class Meta: required_db_features = {"supports_unlimited_charfield"} class DecimalFieldNoPrec(models.Model): decimal_field_no_precision = models.DecimalField( max_digits=None, decimal_places=None ) class Meta: required_db_features = {"supports_no_precision_decimalfield"} class UniqueTogether(models.Model): field1 = models.IntegerField() field2 = models.CharField(max_length=10) from_field = models.IntegerField(db_column="from") non_unique = models.IntegerField(db_column="non__unique_column") non_unique_0 = models.IntegerField(db_column="non_unique__column") class Meta: unique_together = [ ("field1", "field2"), ("from_field", "field1"), ("non_unique", "non_unique_0"), ] class FuncUniqueConstraint(models.Model): name = models.CharField(max_length=255) rank = models.IntegerField() class Meta: constraints = [ models.UniqueConstraint( Lower("name"), models.F("rank"), name="index_lower_name" ) ] required_db_features = {"supports_expression_indexes"} class DbComment(models.Model): rank = models.IntegerField(db_comment="'Rank' column comment") class Meta: db_table_comment = "Custom table comment" required_db_features = {"supports_comments"} class CompositePKModel(models.Model): pk = models.CompositePrimaryKey("column_1", "column_2") column_1 = models.IntegerField() column_2 = models.IntegerField() class DbOnDeleteModel(models.Model): fk_do_nothing = models.ForeignKey(UniqueTogether, on_delete=models.DO_NOTHING) fk_db_cascade = models.ForeignKey(ColumnTypes, on_delete=models.DB_CASCADE) fk_set_null = models.ForeignKey( DigitsInColumnName, on_delete=models.DB_SET_NULL, null=True ) class Meta: required_db_features = { "supports_on_delete_db_cascade", "supports_on_delete_db_null", }
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/inspectdb/__init__.py
tests/inspectdb/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/inspectdb/tests.py
tests/inspectdb/tests.py
import re from io import StringIO from unittest import mock, skipUnless from django.core.management import call_command from django.core.management.commands import inspectdb from django.db import connection from django.db.backends.base.introspection import TableInfo from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature from .models import PeopleMoreData, test_collation def inspectdb_tables_only(table_name): """ Limit introspection to tables created for models of this app. Some databases such as Oracle are extremely slow at introspection. """ return table_name.startswith("inspectdb_") def inspectdb_views_only(table_name): return table_name.startswith("inspectdb_") and table_name.endswith( ("_materialized", "_view") ) def special_table_only(table_name): return table_name.startswith("inspectdb_special") def cursor_execute(*queries): """ Execute SQL queries using a new cursor on the default database connection. """ results = [] with connection.cursor() as cursor: for q in queries: results.append(cursor.execute(q)) return results class InspectDBTestCase(TestCase): unique_re = re.compile(r".*unique_together = \((.+),\).*") def test_stealth_table_name_filter_option(self): out = StringIO() call_command("inspectdb", table_name_filter=inspectdb_tables_only, stdout=out) error_message = ( "inspectdb has examined a table that should have been filtered out." ) # contrib.contenttypes is one of the apps always installed when running # the Django test suite, check that one of its tables hasn't been # inspected self.assertNotIn( "class DjangoContentType(models.Model):", out.getvalue(), msg=error_message ) def test_table_option(self): """ inspectdb can inspect a subset of tables by passing the table names as arguments. """ out = StringIO() call_command("inspectdb", "inspectdb_people", stdout=out) output = out.getvalue() self.assertIn("class InspectdbPeople(models.Model):", output) self.assertNotIn("InspectdbPeopledata", output) def make_field_type_asserter(self): """ Call inspectdb and return a function to validate a field type in its output. """ out = StringIO() call_command("inspectdb", "inspectdb_columntypes", stdout=out) output = out.getvalue() def assertFieldType(name, definition): out_def = re.search(r"^\s*%s = (models.*)$" % name, output, re.MULTILINE)[1] self.assertEqual(definition, out_def) return assertFieldType def test_field_types(self): """Test introspection of various Django field types""" assertFieldType = self.make_field_type_asserter() introspected_field_types = connection.features.introspected_field_types char_field_type = introspected_field_types["CharField"] # Inspecting Oracle DB doesn't produce correct results (#19884): # - it reports fields as blank=True when they aren't. if ( not connection.features.interprets_empty_strings_as_nulls and char_field_type == "CharField" ): assertFieldType("char_field", "models.CharField(max_length=10)") assertFieldType( "null_char_field", "models.CharField(max_length=10, blank=True, null=True)", ) assertFieldType("email_field", "models.CharField(max_length=254)") assertFieldType("file_field", "models.CharField(max_length=100)") assertFieldType("file_path_field", "models.CharField(max_length=100)") assertFieldType("slug_field", "models.CharField(max_length=50)") assertFieldType("text_field", "models.TextField()") assertFieldType("url_field", "models.CharField(max_length=200)") if char_field_type == "TextField": assertFieldType("char_field", "models.TextField()") assertFieldType( "null_char_field", "models.TextField(blank=True, null=True)" ) assertFieldType("email_field", "models.TextField()") assertFieldType("file_field", "models.TextField()") assertFieldType("file_path_field", "models.TextField()") assertFieldType("slug_field", "models.TextField()") assertFieldType("text_field", "models.TextField()") assertFieldType("url_field", "models.TextField()") assertFieldType("date_field", "models.DateField()") assertFieldType("date_time_field", "models.DateTimeField()") if introspected_field_types["GenericIPAddressField"] == "GenericIPAddressField": assertFieldType("gen_ip_address_field", "models.GenericIPAddressField()") elif not connection.features.interprets_empty_strings_as_nulls: assertFieldType("gen_ip_address_field", "models.CharField(max_length=39)") assertFieldType( "time_field", "models.%s()" % introspected_field_types["TimeField"] ) if connection.features.has_native_uuid_field: assertFieldType("uuid_field", "models.UUIDField()") elif not connection.features.interprets_empty_strings_as_nulls: assertFieldType("uuid_field", "models.CharField(max_length=32)") @skipUnlessDBFeature("can_introspect_json_field", "supports_json_field") def test_json_field(self): out = StringIO() call_command("inspectdb", "inspectdb_jsonfieldcolumntype", stdout=out) output = out.getvalue() if not connection.features.interprets_empty_strings_as_nulls: self.assertIn("json_field = models.JSONField()", output) self.assertIn( "null_json_field = models.JSONField(blank=True, null=True)", output ) @skipUnlessDBFeature("supports_comments") def test_db_comments(self): out = StringIO() call_command("inspectdb", "inspectdb_dbcomment", stdout=out) output = out.getvalue() integer_field_type = connection.features.introspected_field_types[ "IntegerField" ] self.assertIn( f"rank = models.{integer_field_type}(" f"db_comment=\"'Rank' column comment\")", output, ) self.assertIn( " db_table_comment = 'Custom table comment'", output, ) @skipUnlessDBFeature("supports_collation_on_charfield") @skipUnless(test_collation, "Language collations are not supported.") def test_char_field_db_collation(self): out = StringIO() call_command("inspectdb", "inspectdb_charfielddbcollation", stdout=out) output = out.getvalue() if not connection.features.interprets_empty_strings_as_nulls: self.assertIn( "char_field = models.CharField(max_length=10, " "db_collation='%s')" % test_collation, output, ) else: self.assertIn( "char_field = models.CharField(max_length=10, " "db_collation='%s', blank=True, null=True)" % test_collation, output, ) @skipUnlessDBFeature("supports_collation_on_textfield") @skipUnless(test_collation, "Language collations are not supported.") def test_text_field_db_collation(self): out = StringIO() call_command("inspectdb", "inspectdb_textfielddbcollation", stdout=out) output = out.getvalue() if not connection.features.interprets_empty_strings_as_nulls: self.assertIn( "text_field = models.TextField(db_collation='%s')" % test_collation, output, ) else: self.assertIn( "text_field = models.TextField(db_collation='%s, blank=True, " "null=True)" % test_collation, output, ) @skipUnlessDBFeature("supports_unlimited_charfield") def test_char_field_unlimited(self): out = StringIO() call_command("inspectdb", "inspectdb_charfieldunlimited", stdout=out) output = out.getvalue() self.assertIn("char_field = models.CharField()", output) @skipUnlessDBFeature("supports_no_precision_decimalfield") def test_decimal_field_no_precision(self): out = StringIO() call_command("inspectdb", "inspectdb_decimalfieldnoprec", stdout=out) output = out.getvalue() self.assertIn("decimal_field_no_precision = models.DecimalField()", output) def test_number_field_types(self): """Test introspection of various Django field types""" assertFieldType = self.make_field_type_asserter() introspected_field_types = connection.features.introspected_field_types auto_field_type = connection.features.introspected_field_types["AutoField"] if auto_field_type != "AutoField": assertFieldType( "id", "models.%s(primary_key=True) # AutoField?" % auto_field_type ) assertFieldType( "big_int_field", "models.%s()" % introspected_field_types["BigIntegerField"] ) bool_field_type = introspected_field_types["BooleanField"] assertFieldType("bool_field", "models.{}()".format(bool_field_type)) assertFieldType( "null_bool_field", "models.{}(blank=True, null=True)".format(bool_field_type), ) if connection.vendor != "sqlite": assertFieldType( "decimal_field", "models.DecimalField(max_digits=6, decimal_places=1)" ) else: assertFieldType("decimal_field", "models.DecimalField()") assertFieldType("float_field", "models.FloatField()") assertFieldType( "int_field", "models.%s()" % introspected_field_types["IntegerField"] ) assertFieldType( "pos_int_field", "models.%s()" % introspected_field_types["PositiveIntegerField"], ) assertFieldType( "pos_big_int_field", "models.%s()" % introspected_field_types["PositiveBigIntegerField"], ) assertFieldType( "pos_small_int_field", "models.%s()" % introspected_field_types["PositiveSmallIntegerField"], ) assertFieldType( "small_int_field", "models.%s()" % introspected_field_types["SmallIntegerField"], ) @skipUnlessDBFeature("can_introspect_foreign_keys") def test_attribute_name_not_python_keyword(self): out = StringIO() call_command("inspectdb", table_name_filter=inspectdb_tables_only, stdout=out) output = out.getvalue() error_message = ( "inspectdb generated an attribute name which is a Python keyword" ) # Recursive foreign keys should be set to 'self' self.assertIn("parent = models.ForeignKey('self', models.DO_NOTHING)", output) self.assertNotIn( "from = models.ForeignKey(InspectdbPeople, models.DO_NOTHING)", output, msg=error_message, ) # As InspectdbPeople model is defined after InspectdbMessage, it should # be quoted. self.assertIn( "from_field = models.ForeignKey('InspectdbPeople', models.DO_NOTHING, " "db_column='from_id')", output, ) self.assertIn( "people_pk = models.OneToOneField(InspectdbPeople, models.DO_NOTHING, " "primary_key=True)", output, ) self.assertIn( "people_unique = models.OneToOneField(InspectdbPeople, models.DO_NOTHING)", output, ) @skipUnlessDBFeature("can_introspect_foreign_keys") def test_foreign_key_to_field(self): out = StringIO() call_command("inspectdb", "inspectdb_foreignkeytofield", stdout=out) self.assertIn( "to_field_fk = models.ForeignKey('InspectdbPeoplemoredata', " "models.DO_NOTHING, to_field='people_unique_id')", out.getvalue(), ) @skipUnlessDBFeature( "can_introspect_foreign_keys", "supports_on_delete_db_cascade", "supports_on_delete_db_null", ) def test_foreign_key_db_on_delete(self): out = StringIO() call_command("inspectdb", "inspectdb_dbondeletemodel", stdout=out) output = out.getvalue() self.assertIn( "fk_do_nothing = models.ForeignKey('InspectdbUniquetogether', " "models.DO_NOTHING)", output, ) self.assertIn( "fk_db_cascade = models.ForeignKey('InspectdbColumntypes', " "models.DB_CASCADE)", output, ) self.assertIn( "fk_set_null = models.ForeignKey('InspectdbDigitsincolumnname', " "models.DB_SET_NULL, blank=True, null=True)", output, ) def test_digits_column_name_introspection(self): """ Introspection of column names consist/start with digits (#16536/#17676) """ char_field_type = connection.features.introspected_field_types["CharField"] out = StringIO() call_command("inspectdb", "inspectdb_digitsincolumnname", stdout=out) output = out.getvalue() error_message = "inspectdb generated a model field name which is a number" self.assertNotIn( " 123 = models.%s" % char_field_type, output, msg=error_message ) self.assertIn("number_123 = models.%s" % char_field_type, output) error_message = ( "inspectdb generated a model field name which starts with a digit" ) self.assertNotIn( " 4extra = models.%s" % char_field_type, output, msg=error_message ) self.assertIn("number_4extra = models.%s" % char_field_type, output) self.assertNotIn( " 45extra = models.%s" % char_field_type, output, msg=error_message ) self.assertIn("number_45extra = models.%s" % char_field_type, output) def test_special_column_name_introspection(self): """ Introspection of column names containing special characters, unsuitable for Python identifiers """ out = StringIO() call_command("inspectdb", table_name_filter=special_table_only, stdout=out) output = out.getvalue() base_name = connection.introspection.identifier_converter("Field") integer_field_type = connection.features.introspected_field_types[ "IntegerField" ] self.assertIn("field = models.%s()" % integer_field_type, output) self.assertIn( "field_field = models.%s(db_column='%s_')" % (integer_field_type, base_name), output, ) self.assertIn( "field_field_0 = models.%s(db_column='%s__')" % (integer_field_type, base_name), output, ) self.assertIn( "field_field_1 = models.%s(db_column='__field')" % integer_field_type, output, ) self.assertIn( "prc_x = models.{}(db_column='prc(%) x')".format(integer_field_type), output ) self.assertIn("tamaño = models.%s()" % integer_field_type, output) def test_table_name_introspection(self): """ Introspection of table names containing special characters, unsuitable for Python identifiers """ out = StringIO() call_command("inspectdb", table_name_filter=special_table_only, stdout=out) output = out.getvalue() self.assertIn("class InspectdbSpecialTableName(models.Model):", output) def test_custom_normalize_table_name(self): def pascal_case_table_only(table_name): return table_name.startswith("inspectdb_pascal") class MyCommand(inspectdb.Command): def normalize_table_name(self, table_name): normalized_name = table_name.split(".")[1] if connection.features.ignores_table_name_case: normalized_name = normalized_name.lower() return normalized_name out = StringIO() call_command(MyCommand(), table_name_filter=pascal_case_table_only, stdout=out) if connection.features.ignores_table_name_case: expected_model_name = "pascalcase" else: expected_model_name = "PascalCase" self.assertIn(f"class {expected_model_name}(models.Model):", out.getvalue()) @skipUnlessDBFeature("supports_expression_indexes") def test_table_with_func_unique_constraint(self): out = StringIO() call_command("inspectdb", "inspectdb_funcuniqueconstraint", stdout=out) output = out.getvalue() self.assertIn("class InspectdbFuncuniqueconstraint(models.Model):", output) def test_managed_models(self): """ By default the command generates models with `Meta.managed = False`. """ out = StringIO() call_command("inspectdb", "inspectdb_columntypes", stdout=out) output = out.getvalue() self.longMessage = False self.assertIn( " managed = False", output, msg="inspectdb should generate unmanaged models.", ) def test_unique_together_meta(self): out = StringIO() call_command("inspectdb", "inspectdb_uniquetogether", stdout=out) output = out.getvalue() self.assertIn(" unique_together = (('", output) unique_together_match = self.unique_re.findall(output) # There should be one unique_together tuple. self.assertEqual(len(unique_together_match), 1) fields = unique_together_match[0] # Fields with db_column = field name. self.assertIn("('field1', 'field2')", fields) # Fields from columns whose names are Python keywords. self.assertIn("('field1', 'field2')", fields) # Fields whose names normalize to the same Python field name and hence # are given an integer suffix. self.assertIn("('non_unique_column', 'non_unique_column_0')", fields) @skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL") def test_unsupported_unique_together(self): """Unsupported index types (COALESCE here) are skipped.""" cursor_execute( "CREATE UNIQUE INDEX Findex ON %s " "(id, people_unique_id, COALESCE(message_id, -1))" % PeopleMoreData._meta.db_table ) self.addCleanup(cursor_execute, "DROP INDEX Findex") out = StringIO() call_command( "inspectdb", table_name_filter=lambda tn: tn.startswith(PeopleMoreData._meta.db_table), stdout=out, ) output = out.getvalue() self.assertIn("# A unique constraint could not be introspected.", output) self.assertEqual(self.unique_re.findall(output), ["('id', 'people_unique')"]) @skipUnless( connection.vendor == "sqlite", "Only patched sqlite's DatabaseIntrospection.data_types_reverse for this test", ) def test_custom_fields(self): """ Introspection of columns with a custom field (#21090) """ out = StringIO() with mock.patch( "django.db.connection.introspection.data_types_reverse." "base_data_types_reverse", { "text": "myfields.TextField", "bigint": "BigIntegerField", }, ): call_command("inspectdb", "inspectdb_columntypes", stdout=out) output = out.getvalue() self.assertIn("text_field = myfields.TextField()", output) self.assertIn("big_int_field = models.BigIntegerField()", output) def test_introspection_errors(self): """ Introspection errors should not crash the command, and the error should be visible in the output. """ out = StringIO() with mock.patch( "django.db.connection.introspection.get_table_list", return_value=[TableInfo(name="nonexistent", type="t")], ): call_command("inspectdb", stdout=out) output = out.getvalue() self.assertIn("# Unable to inspect table 'nonexistent'", output) # The error message depends on the backend self.assertIn("# The error was:", output) def test_same_relations(self): out = StringIO() call_command("inspectdb", "inspectdb_message", stdout=out) self.assertIn( "author = models.ForeignKey('InspectdbPeople', models.DO_NOTHING, " "related_name='inspectdbmessage_author_set')", out.getvalue(), ) class InspectDBTransactionalTests(TransactionTestCase): available_apps = ["inspectdb"] def test_include_views(self): """inspectdb --include-views creates models for database views.""" cursor_execute( "CREATE VIEW inspectdb_people_view AS " "SELECT id, name FROM inspectdb_people" ) self.addCleanup(cursor_execute, "DROP VIEW inspectdb_people_view") out = StringIO() view_model = "class InspectdbPeopleView(models.Model):" view_managed = "managed = False # Created from a view." call_command( "inspectdb", table_name_filter=inspectdb_views_only, stdout=out, ) no_views_output = out.getvalue() self.assertNotIn(view_model, no_views_output) self.assertNotIn(view_managed, no_views_output) call_command( "inspectdb", table_name_filter=inspectdb_views_only, include_views=True, stdout=out, ) with_views_output = out.getvalue() self.assertIn(view_model, with_views_output) self.assertIn(view_managed, with_views_output) @skipUnlessDBFeature("can_introspect_materialized_views") def test_include_materialized_views(self): """inspectdb --include-views creates models for materialized views.""" cursor_execute( "CREATE MATERIALIZED VIEW inspectdb_people_materialized AS " "SELECT id, name FROM inspectdb_people" ) self.addCleanup( cursor_execute, "DROP MATERIALIZED VIEW inspectdb_people_materialized" ) out = StringIO() view_model = "class InspectdbPeopleMaterialized(models.Model):" view_managed = "managed = False # Created from a view." call_command( "inspectdb", table_name_filter=inspectdb_views_only, stdout=out, ) no_views_output = out.getvalue() self.assertNotIn(view_model, no_views_output) self.assertNotIn(view_managed, no_views_output) call_command( "inspectdb", table_name_filter=inspectdb_views_only, include_views=True, stdout=out, ) with_views_output = out.getvalue() self.assertIn(view_model, with_views_output) self.assertIn(view_managed, with_views_output) @skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL") def test_include_partitions(self): """inspectdb --include-partitions creates models for partitions.""" cursor_execute( """ CREATE TABLE inspectdb_partition_parent (name text not null) PARTITION BY LIST (left(upper(name), 1)) """, """ CREATE TABLE inspectdb_partition_child PARTITION OF inspectdb_partition_parent FOR VALUES IN ('A', 'B', 'C') """, ) self.addCleanup( cursor_execute, "DROP TABLE IF EXISTS inspectdb_partition_child", "DROP TABLE IF EXISTS inspectdb_partition_parent", ) out = StringIO() partition_model_parent = "class InspectdbPartitionParent(models.Model):" partition_model_child = "class InspectdbPartitionChild(models.Model):" partition_managed = "managed = False # Created from a partition." call_command("inspectdb", table_name_filter=inspectdb_tables_only, stdout=out) no_partitions_output = out.getvalue() self.assertIn(partition_model_parent, no_partitions_output) self.assertNotIn(partition_model_child, no_partitions_output) self.assertNotIn(partition_managed, no_partitions_output) call_command( "inspectdb", table_name_filter=inspectdb_tables_only, include_partitions=True, stdout=out, ) with_partitions_output = out.getvalue() self.assertIn(partition_model_parent, with_partitions_output) self.assertIn(partition_model_child, with_partitions_output) self.assertIn(partition_managed, with_partitions_output) @skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL") def test_foreign_data_wrapper(self): cursor_execute( "CREATE EXTENSION IF NOT EXISTS file_fdw", "CREATE SERVER inspectdb_server FOREIGN DATA WRAPPER file_fdw", """ CREATE FOREIGN TABLE inspectdb_iris_foreign_table ( petal_length real, petal_width real, sepal_length real, sepal_width real ) SERVER inspectdb_server OPTIONS ( program 'echo 1,2,3,4', format 'csv' ) """, ) self.addCleanup( cursor_execute, "DROP FOREIGN TABLE IF EXISTS inspectdb_iris_foreign_table", "DROP SERVER IF EXISTS inspectdb_server", "DROP EXTENSION IF EXISTS file_fdw", ) out = StringIO() foreign_table_model = "class InspectdbIrisForeignTable(models.Model):" foreign_table_managed = "managed = False" call_command( "inspectdb", table_name_filter=inspectdb_tables_only, stdout=out, ) output = out.getvalue() self.assertIn(foreign_table_model, output) self.assertIn(foreign_table_managed, output) def test_composite_primary_key(self): out = StringIO() field_type = connection.features.introspected_field_types["IntegerField"] call_command("inspectdb", "inspectdb_compositepkmodel", stdout=out) output = out.getvalue() self.assertIn( "pk = models.CompositePrimaryKey('column_1', 'column_2')", output, ) self.assertIn(f"column_1 = models.{field_type}()", output) self.assertIn(f"column_2 = models.{field_type}()", output) def test_composite_primary_key_not_unique_together(self): out = StringIO() call_command("inspectdb", "inspectdb_compositepkmodel", stdout=out) self.assertNotIn("unique_together", out.getvalue())
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_registration/models.py
tests/admin_registration/models.py
""" Tests for various ways of registering models with the admin site. """ from django.db import models class Person(models.Model): name = models.CharField(max_length=200) class Traveler(Person): pass class Location(models.Model): class Meta: abstract = True class Place(Location): name = models.CharField(max_length=200) class Guest(models.Model): pk = models.CompositePrimaryKey("traveler", "place") traveler = models.ForeignKey(Traveler, on_delete=models.CASCADE) place = models.ForeignKey(Place, 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/admin_registration/__init__.py
tests/admin_registration/__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_registration/tests.py
tests/admin_registration/tests.py
from django.contrib import admin from django.contrib.admin.decorators import register from django.contrib.admin.exceptions import AlreadyRegistered, NotRegistered from django.contrib.admin.sites import site from django.core.exceptions import ImproperlyConfigured from django.test import SimpleTestCase from .models import Guest, Location, Person, Place, Traveler class NameAdmin(admin.ModelAdmin): list_display = ["name"] save_on_top = True class CustomSite(admin.AdminSite): pass class TestRegistration(SimpleTestCase): def setUp(self): self.site = admin.AdminSite() def test_bare_registration(self): self.site.register(Person) self.assertIsInstance(self.site.get_model_admin(Person), admin.ModelAdmin) self.site.unregister(Person) self.assertEqual(self.site._registry, {}) def test_registration_with_model_admin(self): self.site.register(Person, NameAdmin) self.assertIsInstance(self.site.get_model_admin(Person), NameAdmin) self.site.unregister(Person) self.assertEqual(self.site._registry, {}) def test_prevent_double_registration(self): self.site.register(Person) msg = "The model Person is already registered in app 'admin_registration'." with self.assertRaisesMessage(AlreadyRegistered, msg): self.site.register(Person) def test_prevent_double_registration_for_custom_admin(self): class PersonAdmin(admin.ModelAdmin): pass self.site.register(Person, PersonAdmin) msg = ( "The model Person is already registered with " "'admin_registration.PersonAdmin'." ) with self.assertRaisesMessage(AlreadyRegistered, msg): self.site.register(Person, PersonAdmin) def test_unregister_unregistered_model(self): msg = "The model Person is not registered" with self.assertRaisesMessage(NotRegistered, msg): self.site.unregister(Person) def test_registration_with_star_star_options(self): self.site.register(Person, search_fields=["name"]) self.assertEqual(self.site.get_model_admin(Person).search_fields, ["name"]) def test_get_model_admin_unregister_model(self): msg = "The model Person is not registered." with self.assertRaisesMessage(NotRegistered, msg): self.site.get_model_admin(Person) def test_star_star_overrides(self): self.site.register( Person, NameAdmin, search_fields=["name"], list_display=["__str__"] ) person_admin = self.site.get_model_admin(Person) self.assertEqual(person_admin.search_fields, ["name"]) self.assertEqual(person_admin.list_display, ["__str__"]) self.assertIs(person_admin.save_on_top, True) def test_iterable_registration(self): self.site.register([Person, Place], search_fields=["name"]) self.assertIsInstance(self.site.get_model_admin(Person), admin.ModelAdmin) self.assertEqual(self.site.get_model_admin(Person).search_fields, ["name"]) self.assertIsInstance(self.site.get_model_admin(Place), admin.ModelAdmin) self.assertEqual(self.site.get_model_admin(Place).search_fields, ["name"]) self.site.unregister([Person, Place]) self.assertEqual(self.site._registry, {}) def test_abstract_model(self): """ Exception is raised when trying to register an abstract model. Refs #12004. """ msg = "The model Location is abstract, so it cannot be registered with admin." with self.assertRaisesMessage(ImproperlyConfigured, msg): self.site.register(Location) def test_composite_pk_model(self): msg = ( "The model Guest has a composite primary key, so it cannot be registered " "with admin." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): self.site.register(Guest) def test_is_registered_model(self): "Checks for registered models should return true." self.site.register(Person) self.assertTrue(self.site.is_registered(Person)) def test_is_registered_not_registered_model(self): "Checks for unregistered models should return false." self.assertFalse(self.site.is_registered(Person)) class TestRegistrationDecorator(SimpleTestCase): """ Tests the register decorator in admin.decorators For clarity: @register(Person) class AuthorAdmin(ModelAdmin): pass is functionally equal to (the way it is written in these tests): AuthorAdmin = register(Person)(AuthorAdmin) """ def setUp(self): self.default_site = site self.custom_site = CustomSite() def test_basic_registration(self): register(Person)(NameAdmin) self.assertIsInstance( self.default_site.get_model_admin(Person), admin.ModelAdmin ) self.default_site.unregister(Person) def test_custom_site_registration(self): register(Person, site=self.custom_site)(NameAdmin) self.assertIsInstance( self.custom_site.get_model_admin(Person), admin.ModelAdmin ) def test_multiple_registration(self): register(Traveler, Place)(NameAdmin) self.assertIsInstance( self.default_site.get_model_admin(Traveler), admin.ModelAdmin ) self.default_site.unregister(Traveler) self.assertIsInstance( self.default_site.get_model_admin(Place), admin.ModelAdmin ) self.default_site.unregister(Place) def test_wrapped_class_not_a_model_admin(self): with self.assertRaisesMessage( ValueError, "Wrapped class must subclass ModelAdmin." ): register(Person)(CustomSite) def test_custom_site_not_an_admin_site(self): with self.assertRaisesMessage(ValueError, "site must subclass AdminSite"): register(Person, site=Traveler)(NameAdmin) def test_empty_models_list_registration_fails(self): with self.assertRaisesMessage( ValueError, "At least one model must be passed to register." ): register()(NameAdmin)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/app_loading/__init__.py
tests/app_loading/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/app_loading/tests.py
tests/app_loading/tests.py
import os from django.apps import apps from django.test import SimpleTestCase from django.test.utils import extend_sys_path class EggLoadingTest(SimpleTestCase): def setUp(self): self.egg_dir = "%s/eggs" % os.path.dirname(__file__) self.addCleanup(apps.clear_cache) def test_egg1(self): """Models module can be loaded from an app in an egg""" egg_name = "%s/modelapp.egg" % self.egg_dir with extend_sys_path(egg_name): with self.settings(INSTALLED_APPS=["app_with_models"]): models_module = apps.get_app_config("app_with_models").models_module self.assertIsNotNone(models_module) del apps.all_models["app_with_models"] def test_egg2(self): """ Loading an app from an egg that has no models returns no models (and no error). """ egg_name = "%s/nomodelapp.egg" % self.egg_dir with extend_sys_path(egg_name): with self.settings(INSTALLED_APPS=["app_no_models"]): models_module = apps.get_app_config("app_no_models").models_module self.assertIsNone(models_module) del apps.all_models["app_no_models"] def test_egg3(self): """ Models module can be loaded from an app located under an egg's top-level package. """ egg_name = "%s/omelet.egg" % self.egg_dir with extend_sys_path(egg_name): with self.settings(INSTALLED_APPS=["omelet.app_with_models"]): models_module = apps.get_app_config("app_with_models").models_module self.assertIsNotNone(models_module) del apps.all_models["app_with_models"] def test_egg4(self): """ Loading an app with no models from under the top-level egg package generates no error. """ egg_name = "%s/omelet.egg" % self.egg_dir with extend_sys_path(egg_name): with self.settings(INSTALLED_APPS=["omelet.app_no_models"]): models_module = apps.get_app_config("app_no_models").models_module self.assertIsNone(models_module) del apps.all_models["app_no_models"] def test_egg5(self): """ Loading an app from an egg that has an import error in its models module raises that error. """ egg_name = "%s/brokenapp.egg" % self.egg_dir with extend_sys_path(egg_name): with self.assertRaisesMessage(ImportError, "modelz"): with self.settings(INSTALLED_APPS=["broken_app"]): pass class GetModelsTest(SimpleTestCase): def setUp(self): from .not_installed import models self.not_installed_module = models def test_get_model_only_returns_installed_models(self): with self.assertRaises(LookupError): apps.get_model("not_installed", "NotInstalledModel") def test_get_models_only_returns_installed_models(self): self.assertNotIn("NotInstalledModel", [m.__name__ for m in apps.get_models()])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/app_loading/not_installed/models.py
tests/app_loading/not_installed/models.py
from django.db import models class NotInstalledModel(models.Model): class Meta: app_label = "not_installed" class RelatedModel(models.Model): class Meta: app_label = "not_installed" not_installed = models.ForeignKey(NotInstalledModel, models.CASCADE) class M2MRelatedModel(models.Model): class Meta: app_label = "not_installed" not_installed = models.ManyToManyField(NotInstalledModel)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false