db.models import F, Sum
from django.test import TestCase

from .models import Product, Stock

class DecimalFieldLookupTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.p1 = Product.objects.create(name="Product1", qty_target=10)
        Stock.objects.create(product=cls.p1, qty_available=5)
        Stock.objects.create(product=cls.p1, qty_available=6)
        cls.p2 = Product.objects.create(name="Product2", qty_target=10)
        Stock.objects.create(product=cls.p2, qty_available=5)

ct=cls.p3, qty_available=4)
        cls.queryset = Product.objects.annotate(
            qty_available_sum=Sum("stock__qty_available"),
        ).annotate(qty_needed=F("qty_target") - F("qty_available_sum"))

    def test_gt(self):
        qs = self.querys

       Stock.objects.create(product=cls.p2, qty_available=5)
        cls.p3 = Product.objects.create(name="Product3", qty_target=10)
        Stock.objects.create(product=cls.p3, qty_available=5)
        Stock.objects.create(produ


mock

from django.db.models import DateTimeField, Value
from django.db.models.lookups import Lookup, YearLookup
from django.test import SimpleTestCase

class CustomLookup(Lookup):
    pass

class LookupTests(SimpleTestCase):
    def test_equality(self):
        lookup = Lookup(Value(1), Value(2))
        self.assertEqual(lookup, lookup)
        self.assertEqual(lookup, Lookup(lookup.lhs, lookup.rhs))
        self.assertEqual(lookup, mock.ANY)
        self.assertNotEqual(lookup, Lookup(lookup.lhs, Value(3)

 "Lookup(Value(1), Value('a'))"),
            (
                YearLookup(
                    Value(datetime(2010, 1, 1, 0, 0, 0)),
                    Value(datetime(2010, 1, 1, 23, 59, 59)),
                ),
                "YearLookup("

))
        self.assertNotEqual(lookup, Lookup(Value(3), lookup.rhs))
        self.assertNotEqual(lookup, CustomLookup(lookup.lhs, lookup.rhs))

    def test_repr(self):
        tests = [
            (Lookup(Value(1), Value("a")),


 TestCase

from .models import Alarm

class TimeFieldLookupTests(TestCase):
    @classmethod
    def setUpTestData(self):
        # Create a few Alarms
        self.al1 = Alarm.objects.create(desc="Early", time="05:30")
        self.al2 = Alarm.objects.create(desc="Late", time="10:00")
        self.al3 = Alarm.objects.create(desc="Precise", time="12:34:56")

    def test_hour_lookups(self):
        self.assertSequenceEqual(
            Alarm.objects.filter(time__hour=5),
            [self.al1],
        )

rtSequenceEqual(
            Alarm.objects.filter(time__minute=30),
            [self.al1],
        )

    def test_second_lookups(self):
        self.assertSequenceEqual(
            Alarm.objects.filter(time__second=56),
            [self.al3],
        )

    def test_minute_lookups(self):
        self.asse


         Article.objects.filter(id__iexact=str(self.a1.id)),
            [self.a1],
        )

    @skipUnlessDBFeature("supports_date_lookup_using_string")
    def test_lookup_date_as_str(self):
        # A date lookup can be performed using a string search
        self.assertSequenceEqual(
            Article.objects.filter(pub_date__startswith="2005"),
            [self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1],
        )

    def test_iterator(self):
        # Each QuerySet gets iterator

rticle.objects.iterator(),
            [
                "Article 5",
                "Article 6",
                "Article 4",
                "Article 2",
                "Article 3",
                "Article 7",
                "Article 1",

(), which is a generator that "lazily"
        # returns results using database-level iteration.
        self.assertIsInstance(Article.objects.iterator(), collections.abc.Iterator)

        self.assertQuerySetEqual(
            A


.db import models
from django.db.models.query_utils import DeferredAttribute

class CustomTypedField(models.TextField):
    def db_type(self, connection):
        return "custom_field"

class CustomDeferredAttribute(DeferredAttribute):
    def __get__(self, instance, cls=None):
        self._count_call(instance, "get")
        return super().__get__(instance, cls)

    def __set__(self, instance, value):
        self._count_call(instance, "set")
        instance.__dict__[self.field.attname] = value

    d

count_attr = "_%s_%s_count" % (self.field.attname, get_or_set)
        count = getattr(instance, count_attr, 0)
        setattr(instance, count_attr, count + 1)

class CustomDescriptorField(models.CharField):
    descriptor_class = CustomDeferredAttribute

ef _count_call(self, instance, get_or_set):


jango.db import connection, models
from django.test import SimpleTestCase

from .fields import CustomDescriptorField, CustomTypedField

class TestDbType(SimpleTestCase):
    def test_db_parameters_respects_db_type(self):
        f = CustomTypedField()
        self.assertEqual(f.db_parameters(connection)["type"], "custom_field")

class DescriptorClassTest(SimpleTestCase):
    def test_descriptor_class(self):
        class CustomDescriptorModel(models.Model):
            name = CustomDescriptorField(max_len

e = "foo"
        self.assertFalse(hasattr(m, "_name_get_count"))
        self.assertEqual(m._name_set_count, 2)
        self.assertEqual(m.name, "foo")
        self.assertEqual(m._name_get_count, 1)
        self.assertEqual(m._name_set_count, 2)
        m

gth=32)

        m = CustomDescriptorModel()
        self.assertFalse(hasattr(m, "_name_get_count"))
        # The field is set to its default in the model constructor.
        self.assertEqual(m._name_set_count, 1)
        m.nam


t (
    RECURSIVE_RELATIONSHIP_CONSTANT,
    ManyToManyDescriptor,
    RelatedField,
    create_many_to_many_intermediary_model,
)

class CustomManyToManyField(RelatedField):
    """
    Ticket #24104 - Need to have a custom ManyToManyField,
    which is not an inheritor of ManyToManyField.
    """

    many_to_many = True

    def __init__(
        self,
        to,
        db_constraint=True,
        swappable=True,
        related_name=None,
        related_query_name=None,
        limit_choices_to=None

gs["rel"] = models.ManyToManyRel(
            self,
            to,
            related_name=related_name,
            related_query_name=related_query_name,
            limit_choices_to=limit_choices_to,
            symmetrical=(
                symmetric

,
        symmetrical=None,
        through=None,
        through_fields=None,
        db_table=None,
        **kwargs,
    ):
        try:
            to._meta
        except AttributeError:
            to = str(to)
        kwar


 main test
# runner doesn't migrate them.

new_apps = Apps()

class Author(models.Model):
    name = models.CharField(max_length=255)
    height = models.PositiveIntegerField(null=True, blank=True)
    weight = models.IntegerField(null=True, blank=True)
    uuid = models.UUIDField(null=True)

    class Meta:
        apps = new_apps

class AuthorCharFieldWithIndex(models.Model):
    char_field = models.CharField(max_length=31, db_index=True)

    class Meta:
        apps = new_apps

class AuthorTextFieldW

tiveIntegerField(null=True, blank=True, default=42)

    class Meta:
        apps = new_apps

class AuthorWithEvenLongerName(models.Model):
    name = models.CharField(max_length=255)
    height = models.PositiveIntegerField(null=True, blank=True)

    cl

ithIndex(models.Model):
    text_field = models.TextField(db_index=True)

    class Meta:
        apps = new_apps

class AuthorWithDefaultHeight(models.Model):
    name = models.CharField(max_length=255)
    height = models.Posi


"
        Get the constraints on a table using a new cursor.
        """
        with connection.cursor() as cursor:
            return connection.introspection.get_constraints(cursor, table)

    def get_constraints_for_column(self, model, column_name):
        constraints = self.get_constraints(model._meta.db_table)
        constraints_for_column = []
        for name, details in constraints.items():
            if details["columns"] == [column_name]:
                constraints_for_column.append(name)

s AS oc
                JOIN pg_index as i on oc.oid = ANY(i.indclass)
                JOIN pg_class as c on c.oid = i.indexrelid
                WHERE c.relname = %s
            """
            cursor.execute(sql, [constraint_name])
            return [ro

      return sorted(constraints_for_column)

    def get_constraint_opclasses(self, constraint_name):
        with connection.cursor() as cursor:
            sql = """
                SELECT opcname
                FROM pg_opclas


rom unittest import mock

from django.core.checks import Error
from django.db import connections, models
from django.test import SimpleTestCase
from django.test.utils import isolate_apps

def dummy_allow_migrate(db, app_label, **hints):
    # Prevent checks from being run on the 'other' database, which doesn't have
    # its check_field() method mocked in the test.
    return db == "default"

@isolate_apps("invalid_models_tests")
class BackendSpecificChecksTests(SimpleTestCase):
    @mock.patch("django.db

         field = models.IntegerField()

        field = Model._meta.get_field("field")
        with mock.patch.object(
            connections["default"].validation, "check_field", return_value=[error]
        ):
            self.assertEqual(field.check(da

.models.fields.router.allow_migrate", new=dummy_allow_migrate)
    def test_check_field(self):
        """Test if backend specific checks are performed."""
        error = Error("an error")

        class Model(models.Model):


@isolate_apps("invalid_models_tests")
class DeprecatedFieldsTests(SimpleTestCase):
    def test_IPAddressField_deprecated(self):
        class IPAddressModel(models.Model):
            ip = models.IPAddressField()

        model = IPAddressModel()
        self.assertEqual(
            model.check(),
            [
                checks.Error(
                    "IPAddressField has been removed except for support in "
                    "historical migrations.",
                    hint="Use GenericIPAdd

  class CommaSeparatedIntegerModel(models.Model):
            csi = models.CommaSeparatedIntegerField(max_length=64)

        model = CommaSeparatedIntegerModel()
        self.assertEqual(
            model.check(),
            [
                checks.Err

ressField instead.",
                    obj=IPAddressModel._meta.get_field("ip"),
                    id="fields.E900",
                )
            ],
        )

    def test_CommaSeparatedIntegerField_deprecated(self):


            class Meta:
                unique_together = [["m2m"]]

        self.assertEqual(
            Model.check(),
            [
                Error(
                    "'unique_together' refers to a ManyToManyField 'm2m', but "
                    "ManyToManyFields are not permitted in 'unique_together'.",
                    obj=Model,
                    id="models.E013",
                ),
            ],
        )

    def test_pointing_to_fk(self):
        class Foo(models.Model):

e=models.CASCADE, related_name="bar_2"
            )

            class Meta:
                unique_together = [["foo_1_id", "foo_2"]]

        self.assertEqual(Bar.check(), [])

    def test_pointing_to_composite_primary_key(self):
        class Model(mo

 pass

        class Bar(models.Model):
            foo_1 = models.ForeignKey(
                Foo, on_delete=models.CASCADE, related_name="bar_1"
            )
            foo_2 = models.ForeignKey(
                Foo, on_delet


     auto = models.AutoField(primary_key=True, max_length=2)

        field = Model._meta.get_field("auto")
        self.assertEqual(
            field.check(),
            [
                DjangoWarning(
                    "'max_length' is ignored when used with %s."
                    % field.__class__.__name__,
                    hint="Remove 'max_length' from field",
                    obj=field,
                    id="fields.W122",
                ),
            ],
        )

@isolate_apps("inva

d(default=None)

        for field_name in ("field1", "field2"):
            field = Model._meta.get_field(field_name)
            self.assertEqual(field.check(), [])

    def test_str_default_value(self):
        class Model(models.Model):
            fie

lid_models_tests")
class BinaryFieldTests(SimpleTestCase):
    def test_valid_default_value(self):
        class Model(models.Model):
            field1 = models.BinaryField(default=b"test")
            field2 = models.BinaryFiel


.Model):
            many_to_many_rel = models.ManyToManyField(OtherModel)

        class O2OModel(models.Model):
            one_to_one_rel = models.OneToOneField(
                "invalid_models_tests.M2MModel_many_to_many_rel",
                on_delete=models.CASCADE,
            )

        field = O2OModel._meta.get_field("one_to_one_rel")
        self.assertEqual(field.check(from_model=O2OModel), [])

    def test_many_to_many_with_useless_options(self):
        class Model(models.Model):

  field = ModelM2M._meta.get_field("m2m")
        self.assertEqual(
            ModelM2M.check(),
            [
                DjangoWarning(
                    "null has no effect on ManyToManyField.",
                    obj=field,

name = models.CharField(max_length=20)

        class ModelM2M(models.Model):
            m2m = models.ManyToManyField(
                Model, null=True, validators=[lambda x: x], db_comment="Column comment"
            )


d_model_traverse(self):
        a1 = Article.objects.create(
            title="First one",
            pub_date=datetime.datetime(2005, 7, 28, 9, 0, 0),
        )
        a2 = Article.objects.create(
            title="Another one",
            pub_date=datetime.datetime(2010, 7, 28, 10, 0, 0),
        )
        a3 = Article.objects.create(
            title="Third one, in the first day",
            pub_date=datetime.datetime(2005, 7, 28, 17, 0, 0),
        )

        a1.comments.create(
            text=

 a2.comments.create(
            text="LMAO",
            pub_date=datetime.datetime(2010, 7, 28, 10, 10, 10),
        )
        a3.comments.create(
            text="+1",
            pub_date=datetime.datetime(2005, 8, 29, 10, 10, 10),
        )

"Im the HULK!",
            pub_date=datetime.datetime(2005, 7, 28, 9, 30, 0),
        )
        a1.comments.create(
            text="HULK SMASH!",
            pub_date=datetime.datetime(2005, 7, 29, 1, 30, 0),
        )


nals" for WarnAboutExternalUseTests.
#
# Every function in this module ends up calling deprecated_function(), which
# calls warn_about_external_use(). The other functions provide various stack
# depths and qualnames for test purposes. All functions pass their arguments
# through to warn_about_external_use().
#
# The tests set internal_modules to treat this module (only) as the "internal"
# Django code. Pass internal_modules=None for the original default behavior or
# internal_modules=tuple(...) to make some

 category=None, **kwargs):
    kwargs.setdefault("internal_modules", (__name__,))
    warn_about_external_use(
        message or "Message",
        category or RemovedInNextVersionWarning,
        **kwargs,
    )

def one_indirection(*args, **kwargs):

 other modules "internal."

from django.utils.deprecation import (
    RemovedAfterNextVersionWarning,
    RemovedInNextVersionWarning,
    deprecate_posargs,
    warn_about_external_use,
)

def deprecated_function(message=None,


# 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 a

cted args"),
            self.assertDeprecated("'a', 'b'", "some_func"),
        ):
            result = some_func(10, 20)
            self.assertEqual(result, (10, 20))

        with (
            self.subTest("One affected arg"),
            self.assertD

re remapped to keyword-only arguments."""

        @deprecate_posargs(RemovedAfterNextVersionWarning, ["a", "b"])
        def some_func(*, a=1, b=2):
            return a, b

        with (
            self.subTest("Multiple affe


onMiddleware,
    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 HttpRespons

nLinkEmailsMiddleware, CommonMiddleware
from django.middleware.csrf import CsrfViewMiddleware
from django.middleware.gzip import GZipMiddleware
from django.middleware.http import ConditionalGetMiddleware
from django.middleware.locale import LocaleMiddlewar

e
from django.middleware.cache import (
    CacheMiddleware,
    FetchFromCacheMiddleware,
    UpdateCacheMiddleware,
)
from django.middleware.clickjacking import XFrameOptionsMiddleware
from django.middleware.common import Broke


rom types import ModuleType

from django.conf import (
    USE_BLANK_CHOICE_DASH_DEPRECATED_MSG,
    LazySettings,
    Settings,
    settings,
)
from django.test import SimpleTestCase
from django.utils.deprecation import RemovedInDjango70Warning

# RemovedInDjango70Warning.
class UseBlankChoiceDashDeprecationTests(SimpleTestCase):
    msg = USE_BLANK_CHOICE_DASH_DEPRECATED_MSG

    def test_override_settings_warning(self):
        with self.assertRaisesMessage(RemovedInDjango70Warning, self.msg):

gs_module.USE_BLANK_CHOICE_DASH = True
        sys.modules["fake_settings_module"] = settings_module
        try:
            with self.assertRaisesMessage(RemovedInDjango70Warning, self.msg):
                Settings("fake_settings_module")
        finall

   with self.settings(USE_BLANK_CHOICE_DASH=True):
                pass

    def test_settings_init_warning(self):
        settings_module = ModuleType("fake_settings_module")
        settings_module.USE_TZ = False
        settin


rnal

class WarnAboutExternalUseTests(SimpleTestCase):
    @contextmanager
    def assertNotWarns(self, category, **kwargs):
        with warnings.catch_warnings(record=True) as caught_warnings:
            warnings.filterwarnings("always", category=category, **kwargs)
            yield caught_warnings
        self.assertEqual([str(warning) for warning in caught_warnings], [])

    def assertWarningPointsHere(self, warning, *, offset=-1):
        caller_frame = inspect.currentframe().f_back
        self.as

ssertWarnsMessage(RemovedInNextVersionWarning, msg) as warning:
            internal.deprecated_function(msg, RemovedInNextVersionWarning)
        self.assertWarningPointsHere(warning)

    def test_internal_use_does_not_warn(self):
        with self.asser

sertEqual(warning.filename, caller_frame.f_code.co_filename)
        self.assertEqual(warning.lineno, caller_frame.f_lineno + offset)

    def test_external_use_warns(self):
        msg = "This is deprecated."
        with self.a


   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:
            # Depending on the cwd, Python might give a local checkout
            # precedence over installed Django, producing None.
            django.__file__ = None
            self.assertEqual(django_file_prefixes(), ())

IsInstance(prefixes, tuple)
        self.assertEqual(len(prefixes), 1)
        self.assertTrue(prefixes[0].endswith(f"{os.path.sep}django{os.path.sep}"))

    def test_does_not_match_packages_prefixed_with_django(self):
        other_file = Path(django.__f

   del django.__file__
            self.assertEqual(django_file_prefixes(), ())
        finally:
            django.__file__ = orig_file

    def test_with_file(self):
        prefixes = django_file_prefixes()
        self.assert


o.contrib.admindocs app.
"""

from django.db import models
from django.utils.functional import cached_property

class Company(models.Model):
    name = models.CharField(max_length=200)

class Group(models.Model):
    name = models.CharField(max_length=200)

class Family(models.Model):
    """
    Links with different link text.

    This is a line with tag :tag:`extends <built_in-extends>`
    This is a line with model :model:`Family <myapp.Family>`
    This is a line with view :view:`Index <myapp.views.

.Model):
    """
    Stores information about a person, related to :model:`myapp.Company`.

    **Notes**

    Use ``save_changes()`` when saving this object.

    ``company``
        Field storing :model:`myapp.Company` where the person works.

    (DESCR

Index>`
    This is a line with template :template:`index template <Index.html>`
    This is a line with filter :filter:`example filter <filtername>`
    """

    last_name = models.CharField(max_length=200)

class Person(models


go.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_

rticle.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()
        )

ipsum,
            written=timezone.now(),
        )
        a2 = Article.objects.create(
            title="How to Time Travel",
            text=lorem_ipsum,
            written=timezone.now(),
        )
        num_updated = A


r
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"))

r, "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.obje

        self.assertQuerySetEqual(
            authors.order_by("name"), ["smithj", "Rhonda"], lambda a: a.display_name
        )

    def test_gt_two_expressions(self):
        with self.assertRaisesMessage(
            ValueErro


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=

re("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("writte

before, published=now
        )
        articles = Article.objects.annotate(
            last_updated=Greatest("written", "published")
        )
        self.assertEqual(articles.first().last_updated, now)

    @skipUnlessDBFeatu


Unless

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(

nterprets_empty_strings_as_nulls
                        else None
                    ),
                ),
            ],
        )

    def test_null_argument(self):
        authors = Author.objects.annotate(
            nullif=NullIf("name", Value(None

"nullif"
        )
        self.assertCountEqual(
            authors,
            [
                ("smithj",),
                (
                    (
                        ""
                        if connection.features.i


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_ba

     obj = Author.objects.annotate(
            json_array=JSONArray(
                Lower("name"),
                F("alias"),
                F("goes_by"),
                Value(30000.15),
                F("age") * 2,
            )
        ).first()

sic(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):


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")

.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

)
        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


o.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"), n

cimal)
        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.o

2=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, De


o.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"),

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 = FloatMode

 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,


o.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"),

ecimal)
        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.an

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, D


o.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=D

tEqual(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

ecimal("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.assertAlmos


o.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=De

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.crea

cimal("-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.


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)

otate(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 = F

    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.ann


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)

    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(o

 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)


els 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("p


o.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

.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 = FloatM

.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


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"),
        )

rim, a.trim),
        )

    def test_trim_transform(self):
        Author.objects.create(name=" John  ")
        Author.objects.create(name="Rhonda")
        tests = (
            (LTrim, "John  "),
            (RTrim, " John"),
            (Trim, "John")

      self.assertQuerySetEqual(
            authors.order_by("alias"),
            [
                ("John ", "  John", "John"),
                ("Rhonda", "Rhonda", "Rhonda"),
            ],
            lambda a: (a.ltrim, a.rt


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

    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.bas

 = 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):


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

_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"),
        )

, published=now
        )
        articles = Article.objects.annotate(first_updated=Least("written", "published"))
        self.assertEqual(articles.first().first_updated, before)

    @skipUnlessDBFeature("greatest_least_ignores


ctions 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):
            NthVal

    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):

ue(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)


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_s

ts.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

n)
        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.objec


o.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=D

tEqual(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"),

ecimal("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.assertAlmos


o.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

1_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")).f

("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.n


o.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=De

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.crea

cimal("-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.


odels.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

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("

.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.",


els 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 b

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

ackend 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 =


o.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"),

ecimal)
        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.

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, D


o.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=D

tEqual(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"),

ecimal("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.assertAlmos


al

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

bjects.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)

)
        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.o


  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

 = 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)

_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


import forms
from django.contrib import admin

from .models import Article, ArticleProxy, Site

class ArticleAdminForm(forms.ModelForm):
    nolabel_form_field = forms.BooleanField(required=False)

    class Meta:
        model = Article
        fields = ["title"]

    @property
    def changed_data(self):
        data = super().changed_data
        if data:
            # Add arbitrary name to changed_data to test
            # change message construction.
            return data + ["not_a_form_field"]

"admin")
site.register(Article)
site.register(ArticleProxy)
site.register(Site, SiteAdmin)

class CustomAdminSite(admin.AdminSite):
    def get_log_entries(self, request):
        from django.contrib.contenttypes.models import ContentType

        log_ent

     return data

class ArticleInline(admin.TabularInline):
    model = Article
    fields = ["title"]
    form = ArticleAdminForm

class SiteAdmin(admin.ModelAdmin):
    inlines = [ArticleInline]

site = admin.AdminSite(name=


hecks.model_checks.check_all_models])
class DuplicateDBTableTests(SimpleTestCase):
    def test_collision_in_same_app(self):
        class Model1(models.Model):
            class Meta:
                db_table = "test_table"

        class Model2(models.Model):
            class Meta:
                db_table = "test_table"

        self.assertEqual(
            checks.run_checks(app_configs=self.apps.get_app_configs()),
            [
                Error(
                    "db_table 'test_table' is used

ettings(
        DATABASE_ROUTERS=["check_framework.test_model_checks.EmptyRouter"]
    )
    def test_collision_in_same_app_database_routers_installed(self):
        class Model1(models.Model):
            class Meta:
                db_table = "test_tabl

 by multiple models: "
                    "check_framework.Model1, check_framework.Model2.",
                    obj="test_table",
                    id="models.E028",
                )
            ],
        )

    @override_s


t models
from django.test import SimpleTestCase
from django.test.utils import isolate_apps

@isolate_apps("check_framework")
class TestDeprecatedField(SimpleTestCase):
    def test_default_details(self):
        class MyField(models.Field):
            system_check_deprecated_details = {}

        class Model(models.Model):
            name = MyField()

        model = Model()
        self.assertEqual(
            model.check(),
            [
                checks.Warning(
                    msg="MyField

els.Field):
            system_check_deprecated_details = {
                "msg": "This field is deprecated and will be removed soon.",
                "hint": "Use something else.",
                "id": "fields.W999",
            }

        class Model(

 has been deprecated.",
                    obj=Model._meta.get_field("name"),
                    id="fields.WXXX",
                )
            ],
        )

    def test_user_specified_details(self):
        class MyField(mod


from django.db import connections, models
from django.test import SimpleTestCase
from django.test.utils import isolate_apps, override_settings

class TestRouter:
    """
    Routes to the 'other' database if the model name starts with 'Other'.
    """

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        return db == ("other" if model_name.startswith("other") else "default")

@override_settings(DATABASE_ROUTERS=[TestRouter()])
@isolate_apps("check_framework")
class TestMultiDBCh

l):
            field = models.CharField(max_length=100)

        model = Model()
        with self._patch_check_field_on("default") as mock_check_field_default:
            with self._patch_check_field_on("other") as mock_check_field_other:

ecks(SimpleTestCase):
    def _patch_check_field_on(self, db):
        return mock.patch.object(connections[db].validation, "check_field")

    def test_checks_called_on_the_default_database(self):
        class Model(models.Mode


 Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions" is
        in INSTALLED_APPS.
        """
        self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W010])

    @override_settings(
        SESSION_COOKIE_SECURE="1",
        INSTALLED_APPS=["django.contrib.sessions"],
        MIDDLEWARE=[],
    )
    def test_session_cookie_secure_with_installed_app_truthy(self):
        """SESSION_COOKIE_SECURE must be boolean."""
        self.assertEqual(sessions.check_session_cookie

ie_secure_with_middleware(self):
        """
        Warn if SESSION_COOKIE_SECURE is off and
        "django.contrib.sessions.middleware.SessionMiddleware" is in
        MIDDLEWARE.
        """
        self.assertEqual(sessions.check_session_cookie_secure

_secure(None), [sessions.W010])

    @override_settings(
        SESSION_COOKIE_SECURE=False,
        INSTALLED_APPS=[],
        MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"],
    )
    def test_session_cook


o.template.backends.base import BaseEngine
from django.test import SimpleTestCase
from django.test.utils import override_settings

class ErrorEngine(BaseEngine):
    def __init__(self, params):
        params.pop("OPTIONS")
        super().__init__(params)

    def check(self, **kwargs):
        return [Error("Example")]

class CheckTemplatesTests(SimpleTestCase):
    @override_settings(
        TEMPLATES=[
            {"BACKEND": f"{__name__}.{ErrorEngine.__qualname__}", "NAME": "backend_1"},

class CheckTemplateStringIfInvalidTest(SimpleTestCase):
    TEMPLATES_STRING_IF_INVALID = [
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            "NAME": "backend_1",
            "OPTIONS": {
                "strin

 {"BACKEND": f"{__name__}.{ErrorEngine.__qualname__}", "NAME": "backend_2"},
        ]
    )
    def test_errors_aggregated(self):
        errors = check_templates(None)
        self.assertEqual(errors, [Error("Example")] * 2)


ettings_consistent,
    check_setting_language_code,
    check_setting_languages,
    check_setting_languages_bidi,
)
from django.test import SimpleTestCase, override_settings

class TranslationCheckTests(SimpleTestCase):
    def setUp(self):
        self.valid_tags = (
            "en",  # language
            "mas",  # language
            "sgn-ase",  # language+extlang
            "fr-CA",  # language+region
            "es-419",  # language+region
            "zh-Hans",  # language+script
            "

     123,  # invalid type: int.
            b"en",  # invalid type: bytes.
            "eü",  # non-latin characters.
            "en_US",  # locale format.
            "en--us",  # empty subtag.
            "-en",  # leading separator.
            "en-",

ca-ES-valencia",  # language+region+variant
            # FIXME: The following should be invalid:
            "sr@latin",  # language+script
        )
        self.invalid_tags = (
            None,  # invalid type: None.


version import PY314

class CheckUrlConfigTests(SimpleTestCase):
    @override_settings(ROOT_URLCONF="check_framework.urls.no_warnings")
    def test_no_warnings(self):
        result = check_url_config(None)
        self.assertEqual(result, [])

    @override_settings(ROOT_URLCONF="check_framework.urls.no_warnings_i18n")
    def test_no_warnings_i18n(self):
        self.assertEqual(check_url_config(None), [])

    @override_settings(ROOT_URLCONF="check_framework.urls.warning_in_include")
    def test_chec

0]
        self.assertEqual(warning.id, "urls.W001")

    @override_settings(ROOT_URLCONF="check_framework.urls.include_with_dollar")
    def test_include_with_dollar(self):
        result = check_url_config(None)
        self.assertEqual(len(result), 1)

k_resolver_recursive(self):
        # The resolver is checked recursively (examining URL patterns in
        # include()).
        result = check_url_config(None)
        self.assertEqual(len(result), 1)
        warning = result[


ror
from django.db import models
from django.test import SimpleTestCase
from django.test.utils import isolate_apps, override_settings, override_system_checks

from .models import SimpleModel, my_check

class DummyObj:
    def __repr__(self):
        return "obj"

class SystemCheckFrameworkTests(SimpleTestCase):
    def test_register_and_run_checks(self):
        def f(**kwargs):
            calls[0] += 1
            return [1, 2, 3]

        def f2(**kwargs):
            return [4]

        def f3(**kwarg

", deploy=True)(f3)

        # test register as function
        registry2 = CheckRegistry()
        registry2.register(f)
        registry2.register(f2, "tag1", "tag2")
        registry2.register(f3, "tag2", deploy=True)

        # check results
        e

s):
            return [5]

        calls = [0]

        # test register as decorator
        registry = CheckRegistry()
        registry.register()(f)
        registry.register("tag1", "tag2")(f2)
        registry.register("tag2


ngo.urls import include, path

common_url_patterns = (
    [
        path("app-ns1/", include([])),
        path("app-url/", include([])),
    ],
    "common",
)

nested_url_patterns = (
    [
        path("common/", include(common_url_patterns, namespace="nested")),
    ],
    "nested",
)

urlpatterns = [
    path("app-ns1-0/", include(common_url_patterns, namespace="app-include-1")),
    path("app-ns1-1/", include(common_url_patterns, namespace="app-include-2")),
    # 'nested' is included twice but names

", include(nested_url_patterns, namespace="nested-1")),
    path("app-ns1-3/", include(nested_url_patterns, namespace="nested-2")),
    # namespaced URLs inside non-namespaced URLs.
    path("app-ns1-4/", include([path("abc/", include(common_url_patterns))

paced by nested-1 and nested-2.
    path("app-ns1-2/


 relationship between a model and itself, use
``ForeignKey('self', ...)``.

In this example, a ``Category`` is related to itself. That is, each
``Category`` has a parent ``Category``.

Set ``related_name`` to designate what the reverse relationship is called.
"""

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=20)
    parent = models.ForeignKey(
        "self", models.SET_NULL, blank=True, null=True, related_name="child_set"
    )

    def __str__(self):

):
    full_name = models.CharField(max_length=20)
    mother = models.ForeignKey(
        "self", models.SET_NULL, null=True, related_name="mothers_child_set"
    )
    father = models.ForeignKey(
        "self", models.SET_NULL, null=True, related_name="

        return self.name

class Person(models.Model


estCase

from .models import Category, Person

class ManyToOneRecursiveTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.r = Category.objects.create(id=None, name="Root category", parent=None)
        cls.c = Category.objects.create(id=None, name="Child category", parent=cls.r)

    def test_m2o_recursive(self):
        self.assertSequenceEqual(self.r.child_set.all(), [self.c])
        self.assertEqual(self.r.child_set.get(name__startswith="Child").id, self.c.id)
        self.assert

s):
        cls.dad = Person.objects.create(
            full_name="John Smith Senior", mother=None, father=None
        )
        cls.mom = Person.objects.create(
            full_name="Jane Smith", mother=None, father=None
        )
        cls.kid = Per

IsNone(self.r.parent)
        self.assertSequenceEqual(self.c.child_set.all(), [])
        self.assertEqual(self.c.parent.id, self.r.id)

class MultipleManyToOneRecursiveTests(TestCase):
    @classmethod
    def setUpTestData(cl


est_override(self):
        self.assertEqual(settings.ITEMS, ["b", "c", "d"])
        self.assertEqual(settings.ITEMS_OUTER, [1, 2, 3])
        self.assertEqual(settings.TEST, "override")
        self.assertEqual(settings.TEST_OUTER, "outer")

    @modify_settings(
        ITEMS={
            "append": ["e", "f"],
            "prepend": ["a"],
            "remove": ["d", "c"],
        }
    )
    def test_method_list_override(self):
        self.assertEqual(settings.ITEMS, ["a", "b", "e", "f"])
        self

ide_no_ops(self):
        self.assertEqual(settings.ITEMS, ["b", "d"])

    @modify_settings(
        ITEMS={
            "append": "e",
            "prepend": "a",
            "remove": "c",
        }
    )
    def test_method_list_override_strings(self):

.assertEqual(settings.ITEMS_OUTER, [1, 2, 3])

    @modify_settings(
        ITEMS={
            "append": ["b"],
            "prepend": ["d"],
            "remove": ["a", "c", "e"],
        }
    )
    def test_method_list_overr


)
    name = models.CharField(max_length=50)

class Country(models.Model):
    id = models.SmallAutoField(primary_key=True)
    name = models.CharField(max_length=50)

class District(models.Model):
    city = models.ForeignKey(City, models.CASCADE, primary_key=True)
    name = models.CharField(max_length=50)

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()
    facebook_user_id = models.BigIntege

e(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    body = models.TextField(default="")
    reporter = models.ForeignKey(Reporter, models.CASCADE)
    response_to = models.ForeignKey("self", models.SET_NUL

rField(null=True)
    raw_data = models.BinaryField(null=True)
    small_int = models.SmallIntegerField()
    interval = models.DurationField()

    class Meta:
        unique_together = ("first_name", "last_name")

class Articl


t()." % Reporter._meta.db_table,
        )
        self.assertIn(
            Article._meta.db_table,
            tl,
            "'%s' isn't in table_list()." % Article._meta.db_table,
        )

    def test_django_table_names(self):
        with connection.cursor() as cursor:
            cursor.execute("CREATE TABLE django_ixn_test_table (id INTEGER);")
            tl = connection.introspection.django_table_names()
            cursor.execute("DROP TABLE django_ixn_test_table;")
            self.assertNot

 #15216
        tl = connection.introspection.django_table_names(only_existing=True)
        self.assertIs(type(tl), list)
        tl = connection.introspection.django_table_names(only_existing=False)
        self.assertIs(type(tl), list)

    def test_tab

In(
                "django_ixn_test_table",
                tl,
                "django_table_names() returned a non-Django table",
            )

    def test_django_table_names_retval_type(self):
        # Table name is a list


ngo.db import connection, models
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature

from .models import (
    Anchor,
    AutoNowDateTimeData,
    BigIntegerData,
    BinaryData,
    BooleanData,
    BooleanPKData,
    CharData,
    CharPKData,
    DateData,
    DatePKData,
    DateTimeData,
    DateTimePKData,
    DecimalData,
    DecimalPKData,
    EmailData,
    EmailPKData,
    ExplicitInheritBaseModel,
    FileData,
    FilePathData,
    FilePathPKData,
    FKData,
    FKDataToFiel

ta,
    IntegerPKData,
    Intermediate,
    LengthModel,
    M2MData,
    M2MIntermediateData,
    M2MSelfData,
    ModifyingSaveData,
    O2OData,
    PositiveBigIntegerData,
    PositiveIntegerData,
    PositiveIntegerPKData,
    PositiveSmallIntegerDat

d,
    FKDataToO2O,
    FKSelfData,
    FKToUUID,
    FloatData,
    FloatPKData,
    GenericData,
    GenericIPAddressData,
    GenericIPAddressPKData,
    ImageData,
    InheritAbstractModel,
    InheritBaseModel,
    IntegerDa


lizers.json import Deserializer as JsonDeserializer
from django.core.serializers.jsonl import Deserializer as JsonlDeserializer
from django.core.serializers.python import Deserializer
from django.core.serializers.xml_serializer import Deserializer as XMLDeserializer
from django.test import SimpleTestCase

from .models import Author

try:
    import yaml  # NOQA

    HAS_YAML = True
except ImportError:
    HAS_YAML = False

class TestDeserializer(SimpleTestCase):
    def setUp(self):
        self.object_lis

ct_list)
        self.jane = Author(name="Jane", pk=1)
        self.joe = Author(name="Joe", pk=2)

    def test_deserialized_object_repr(self):
        deserial_obj = DeserializedObject(obj=self.jane)
        self.assertEqual(
            repr(deserial_ob

t = [
            {"pk": 1, "model": "serializers.author", "fields": {"name": "Jane"}},
            {"pk": 2, "model": "serializers.author", "fields": {"name": "Joe"}},
        ]
        self.deserializer = Deserializer(self.obje


ide

from .models import Score
from .tests import SerializersTestBase, SerializersTransactionTestBase

class JsonSerializerTestCase(SerializersTestBase, TestCase):
    serializer_name = "json"
    pkless_str = """[
    {
        "pk": null,
        "model": "serializers.category",
        "fields": {"name": "Reference"}
    }, {
        "model": "serializers.category",
        "fields": {"name": "Non-fiction"}
    }]"""
    mapping_ordering_str = """[
{
  "model": "serializers.article",
  "pk": %(article_p

ata": [],
    "topics": []
  }
}
]
"""

    @staticmethod
    def _validate_output(serial_str):
        try:
            json.loads(serial_str)
        except Exception:
            return False
        else:
            return True

    @staticmethod

k)s,
  "fields": {
    "author": %(author_pk)s,
    "headline": "Poker has no place on ESPN",
    "pub_date": "2006-06-16T11:00:00",
    "categories": [
      %(first_category_pk)s,
      %(second_category_pk)s
    ],
    "meta_d


se, TestCase):
    serializer_name = "jsonl"
    pkless_str = [
        '{"pk": null,"model": "serializers.category","fields": {"name": "Reference"}}',
        '{"model": "serializers.category","fields": {"name": "Non-fiction"}}',
    ]
    pkless_str = "\n".join([s.replace("\n", "") for s in pkless_str])

    mapping_ordering_str = (
        '{"model": "serializers.article","pk": %(article_pk)s,'
        '"fields": {'
        '"author": %(author_pk)s,'
        '"headline": "Poker has no place on ESPN",'

):
        try:
            for line in serial_str.split("\n"):
                if line:
                    json.loads(line)
        except Exception:
            return False
        else:
            return True

    @staticmethod
    def _get_pk_values

      '"pub_date": "2006-06-16T11:00:00",'
        '"categories": [%(first_category_pk)s,%(second_category_pk)s],'
        '"meta_data": [],'
        '"topics": []}}\n'
    )

    @staticmethod
    def _validate_output(serial_str


User,
)
from .tests import register_tests

class NaturalKeySerializerTests(TestCase):
    pass

def natural_key_serializer_test(self, format):
    # Create all the objects defined in the test data
    with connection.constraint_checks_disabled():
        objects = [
            NaturalKeyAnchor.objects.create(id=1100, data="Natural Key Anghor"),
            FKDataNaturalKey.objects.create(id=1101, data_id=1100),
            FKDataNaturalKey.objects.create(id=1102, data_id=None),
        ]
    # Serialize

ert that the deserialized data is the same
    # as the original source
    for obj in objects:
        instance = obj.__class__.objects.get(id=obj.pk)
        self.assertEqual(
            obj.data,
            instance.data,
            "Objects with PK=

the test database
    serialized_data = serializers.serialize(
        format, objects, indent=2, use_natural_foreign_keys=True
    )

    for obj in serializers.deserialize(format, serialized_data):
        obj.save()

    # Ass


ango.core.exceptions import ImproperlyConfigured
from django.test import override_settings

from .tests import AdminDocsTestCase, TestDataMixin

class XViewMiddlewareTest(TestDataMixin, AdminDocsTestCase):
    def test_xview_func(self):
        user = User.objects.get(username="super")
        response = self.client.head("/xview/func/")
        self.assertNotIn("X-View", response)
        self.client.force_login(self.superuser)
        response = self.client.head("/xview/func/")
        self.assertIn("X-Vi

, response)
        user.is_staff = True
        user.is_active = False
        user.save()
        response = self.client.head("/xview/func/")
        self.assertNotIn("X-View", response)

    def test_xview_class(self):
        user = User.objects.get(us

ew", response)
        self.assertEqual(response.headers["X-View"], "admin_docs.views.xview")
        user.is_staff = False
        user.save()
        response = self.client.head("/xview/func/")
        self.assertNotIn("X-View"


tils installed.")
class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
    def setUp(self):
        self.client.force_login(self.superuser)

    def test_index(self):
        response = self.client.get(reverse("django-admindocs-docroot"))
        self.assertContains(response, "
Documentation
", html=True)
        self.assertContains(
            response,
            '
Django administration
',
        )
        self.client.logout()
        response

       )

    def test_bookmarklets(self):
        response = self.client.get(reverse("django-admindocs-bookmarklets"))
        self.assertContains(response, "/admindocs/views/")

    def test_templatetag_index(self):
        response = self.client.get(rev

= self.client.get(reverse("django-admindocs-docroot"), follow=True)
        # Should display the login screen
        self.assertContains(
            response, '<input type="hidden" name="next" value="/admindocs/">', html=True


model, are m2m "
        "fields, primary keys, or are non-concrete fields: %s"
    )

    def test_update_fields_basic(self):
        s = Person.objects.create(name="Sara", gender="F")
        self.assertEqual(s.gender, "F")

        s.gender = "M"
        s.name = "Ian"
        s.save(update_fields=["name"])

        s = Person.objects.get(pk=s.pk)
        self.assertEqual(s.gender, "F")
        self.assertEqual(s.name, "Ian")

    def test_update_fields_deferred(self):
        s = Person.objects.create(n

          s1.save()

        s2 = Person.objects.get(pk=s1.pk)
        self.assertEqual(s2.name, "Emily")
        self.assertEqual(s2.gender, "M")

    def test_update_fields_only_1(self):
        s = Person.objects.create(name="Sara", gender="F")

ame="Sara", gender="F", pid=22)
        self.assertEqual(s.gender, "F")

        s1 = Person.objects.defer("gender", "pid").get(pk=s.pk)
        s1.name = "Emily"
        s1.gender = "M"

        with self.assertNumQueries(1):


    "followers_abstract",
            "followers_base",
            "followers_concrete",
            "following_abstract",
            "following_base",
            "following_inherited",
            "friends_abstract",
            "friends_base",
            "friends_inherited",
            "generic_relation_abstract",
            "generic_relation_base",
            "generic_relation_concrete",
            "id",
            "m2m_abstract",
            "m2m_base",
            "m2m_inherited",

        BasePerson: [
            "content_type_abstract",
            "content_type_abstract_id",
            "content_type_base",
            "content_type_base_id",
            "data_abstract",
            "data_base",
            "data_not_concrete_abs

"object_id_abstract",
            "object_id_base",
            "object_id_concrete",
            "relating_basepeople",
            "relating_baseperson",
            "relating_people",
            "relating_person",
        ],


tractPerson,
    BasePerson,
    Child,
    CommonAncestor,
    FirstParent,
    Person,
    ProxyPerson,
    Relating,
    Relation,
    SecondParent,
    Swappable,
)
from .results import TEST_RESULTS

class OptionsBaseTests(SimpleTestCase):
    def _map_related_query_names(self, res):
        return tuple((o.name, m) for o, m in res)

    def _map_names(self, res):
        return tuple((f.name, m) for f, m in res)

    def _model(self, current_model, field):
        model = field.model._meta.concrete_mo

        if model == current_model:
            model = None

        field = relation if direct else relation.field
        return (
            relation,
            model,
            direct,
            bool(field.many_to_many),
        )  # many_to_man

del
        return None if model == current_model else model

    def _details(self, current_model, relation):
        direct = isinstance(relation, (Field, GenericForeignKey))
        model = relation.model._meta.concrete_model


ort models
from django.utils.translation import gettext_lazy as _

class Site(models.Model):
    domain = models.CharField(max_length=100)

    def __str__(self):
        return self.domain

class Article(models.Model):
    """
    A simple Article model for testing
    """

    site = models.ForeignKey(Site, models.CASCADE, related_name="admin_articles")
    title = models.CharField(max_length=100)
    hist = models.CharField(
        max_length=100,
        verbose_name=_("History"),
        help_text=_

xpect")
    def test_from_model_with_override(self):
        return "nothing"

class ArticleProxy(Article):
    class Meta:
        proxy = True

class Cascade(models.Model):
    num = models.PositiveSmallIntegerField()
    parent = models.ForeignKey("se

("History help text"),
    )
    created = models.DateTimeField(null=True)

    def __str__(self):
        return self.title

    def test_from_model(self):
        return "nothing"

    @admin.display(description="not What you E


mats import localize
from django.utils.safestring import mark_safe

from .models import (
    Article,
    Car,
    Cascade,
    DBCascade,
    Event,
    EventGuide,
    Location,
    Site,
    Vehicle,
)

class NestedObjectsTests(TestCase):
    """
    Tests for ``NestedObject`` utility collection.
    """

    cascade_model = Cascade

    @classmethod
    def setUpTestData(cls):
        cls.n = NestedObjects(using=DEFAULT_DB_ALIAS)
        cls.objs = [cls.cascade_model.objects.create(num=i) for i in ran

lf, *indices):
        self.n.collect([self.objs[i] for i in indices])

    def test_unrelated_roots(self):
        self._connect(2, 1)
        self._collect(0)
        self._collect(1)
        self._check([0, 1, [2]])

    def test_siblings(self):

ge(5)]

    def _check(self, target):
        self.assertEqual(self.n.nested(lambda obj: obj.num), target)

    def _connect(self, i, j):
        self.objs[i].parent = self.objs[j]
        self.objs[i].save()

    def _collect(se


s as the ``default`` parameter to a field. When
the object is created without an explicit value passed in, Django will call
the method to determine the default value.

This example uses ``datetime.datetime.now`` as the default for the ``pub_date``
field.
"""

from datetime import datetime
from decimal import Decimal

from django.db import models
from django.db.models.functions import Coalesce, ExtractYear, Now, Pi
from django.db.models.lookups import GreaterThan

class Article(models.Model):
    headline =

xpressions can be passed as the db_default parameter to a field.
    When the object is created without an explicit value passed in, the
    database will insert the default value automatically.
    """

    headline = models.CharField(max_length=100, db_d

 models.CharField(max_length=100, default="Default headline")
    pub_date = models.DateTimeField(default=datetime.now)

    def __str__(self):
        return self.headline

class DBArticle(models.Model):
    """
    Values or e


rator(view):
    view.is_decorated = True
    return view

class DecoratedDispatchView(SimpleView):
    @decorator
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

class AboutTemplateView(TemplateView):
    def get(self, request):
        return self.render_to_response({})

    def get_template_names(self):
        return ["generic_views/about.html"]

class AboutTemplateAttributeView(TemplateView):
    template_name = "generic_views/about.html"

Factory()

    def _assert_simple(self, response):
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, b"This is a simple view")

    def test_no_init_kwargs(self):
        """
        A view can't be accidentally

    def get(self, request):
        return self.render_to_response(context={})

class InstanceView(View):
    def get(self, request):
        return self

class ViewTest(LoggingAssertionMixin, SimpleTestCase):
    rf = Request


@override_settings(ROOT_URLCONF="generic_views.urls")
class DetailViewTest(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.artist1 = Artist.objects.create(name="Rene Magritte")
        cls.author1 = Author.objects.create(
            name="Roberto Bolaño", slug="roberto-bolano"
        )
        cls.author2 = Author.objects.create(
            name="Scott Rosenberg", slug="scott-rosenberg"
        )
        cls.book1 = Book.objects.create(
            name="2066", slug="2066", pages=80

            pubdate=datetime.date(2006, 5, 1),
        )
        cls.page1 = Page.objects.create(
            content="I was once bitten by a moose.",
            template="generic_views/page_template.html",
        )

    def test_simple_object(self):

0, pubdate=datetime.date(2008, 10, 1)
        )
        cls.book1.authors.add(cls.author1)
        cls.book2 = Book.objects.create(
            name="Dreaming in Code",
            slug="dreaming-in-code",
            pages=300,


te")
        cls.author1 = Author.objects.create(
            name="Roberto Bolaño", slug="roberto-bolano"
        )
        cls.author2 = Author.objects.create(
            name="Scott Rosenberg", slug="scott-rosenberg"
        )
        cls.book1 = Book.objects.create(
            name="2066", slug="2066", pages=800, pubdate=datetime.date(2008, 10, 1)
        )
        cls.book1.authors.add(cls.author1)
        cls.book2 = Book.objects.create(
            name="Dreaming in Code",
            slug="dreamin

mplate.html",
        )

    def test_items(self):
        res = self.client.get("/list/dict/")
        self.assertEqual(res.status_code, 200)
        self.assertTemplateUsed(res, "generic_views/list.html")
        self.assertEqual(res.context["object_list

g-in-code",
            pages=300,
            pubdate=datetime.date(2006, 5, 1),
        )
        cls.page1 = Page.objects.create(
            content="I was once bitten by a moose.",
            template="generic_views/page_te


m django.views import generic

from .forms import AuthorForm, ConfirmDeleteForm, ContactForm
from .models import Artist, Author, Book, BookSigning, Page

class CustomTemplateView(generic.TemplateView):
    template_name = "generic_views/about.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({"key": "value"})
        return context

class ObjectDetail(generic.DetailView):
    template_name = "generic_views/detail.html"

    def get

eneric.DetailView):
    template_name = "generic_views/author_detail.html"
    queryset = Author.objects.all()

    def get(self, request, *args, **kwargs):
        # Ensures get_context_object_name() doesn't reference self.object.
        author = self.ge

_object(self):
        return {"foo": "bar"}

class ArtistDetail(generic.DetailView):
    queryset = Artist.objects.all()

class AuthorDetail(generic.DetailView):
    queryset = Author.objects.all()

class AuthorCustomDetail(g


tes.requests import RequestSite
from django.contrib.sites.shortcuts import get_current_site
from django.core import checks
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db.models.signals import post_migrate
from django.http import HttpRequest, HttpResponse
from django.test import SimpleTestCase, TestCase, modify_settings, override_settings
from django.test.utils import captured_stdout

@modify_settings(INSTALLED_APPS={"append": "django.contrib.sites"})
class SitesFramew

self):
        Site.objects.clear_cache()
        self.addCleanup(Site.objects.clear_cache)

    def test_site_manager(self):
        # Make sure that get_current() does not return a deleted Site object.
        s = Site.objects.get_current()
        self.

orkTests(TestCase):
    databases = {"default", "other"}

    @classmethod
    def setUpTestData(cls):
        cls.site = Site(id=settings.SITE_ID, domain="example.com", name="example.com")
        cls.site.save()

    def setUp(


from django.core import checks
from django.core.checks import Error
from django.test import SimpleTestCase
from django.test.utils import isolate_apps, override_settings, override_system_checks

@isolate_apps("check_framework.custom_commands_app", attr_name="apps")
@override_settings(INSTALLED_APPS=["check_framework.custom_commands_app"])
@override_system_checks([checks.commands.migrate_and_makemigrations_autodetector])
class CommandCheckTests(SimpleTestCase):
    def test_migrate_and_makemigrations_autodet

 is int, but "
                "migrate.Command.autodetector is MigrationAutodetector."
            ),
            id="commands.E001",
        )

        self.assertEqual(
            checks.run_checks(app_configs=self.apps.get_app_configs()),

ector_different(self):
        expected_error = Error(
            "The migrate and makemigrations commands must have the same "
            "autodetector.",
            hint=(
                "makemigrations.Command.autodetector


ngo.core.checks.database import check_database_backends
from django.db import connection, connections
from django.test import TestCase

class DatabaseCheckTests(TestCase):
    databases = {"default", "other"}

    @mock.patch("django.db.backends.base.validation.BaseDatabaseValidation.check")
    def test_database_checks_called(self, mocked_check):
        check_database_backends()
        self.assertFalse(mocked_check.called)
        check_database_backends(databases=self.databases)
        self.assertTrue

 hasattr(connections[alias], "sql_mode"):
                    del connections[alias].sql_mode

        _clean_sql_mode()
        good_sql_modes = [
            "STRICT_TRANS_TABLES,STRICT_ALL_TABLES",
            "STRICT_TRANS_TABLES",
            "STRICT_

(mocked_check.called)

    @unittest.skipUnless(connection.vendor == "mysql", "Test only for MySQL")
    def test_mysql_strict_mode(self):
        def _clean_sql_mode():
            for alias in self.databases:
                if


ort 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
        )

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:

   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


mpleTestCase

@unittest.skipUnless(docutils_is_available, "no docutils installed.")
class TestUtils(AdminDocsSimpleTestCase):
    """
    This __doc__ output is required for testing. I copied this example from
    `admindocs` documentation. (TITLE)

    Display an individual :model:`myapp.MyModel`.

    **Context**

    ``RequestContext``

    ``mymodel``
        An instance of :model:`myapp.MyModel`.

    **Template:**

    :template:`myapp/my_template.html` (DESCRIPTION)

    some_metadata: some data

tput is required for testing. I copied this example from\n"
            "`admindocs` documentation. (TITLE)"
        )
        docstring_description = (
            "Display an individual :model:`myapp.MyModel`.\n\n"
            "**Context**\n\n``RequestCo

 """

    def setUp(self):
        self.docstring = self.__doc__

    def test_parse_docstring(self):
        title, description, metadata = parse_docstring(self.docstring)
        docstring_title = (
            "This __doc__ ou


rt gettext_lazy as _

class Relation(models.Model):
    pass

class InstanceOnlyDescriptor:
    def __get__(self, instance, cls=None):
        if instance is None:
            raise AttributeError("Instance only")
        return 1

class AbstractPerson(models.Model):
    # DATA fields
    data_abstract = models.CharField(max_length=10)
    fk_abstract = models.ForeignKey(
        Relation, models.CASCADE, related_name="fk_abstract_rel"
    )

    # M2M fields
    m2m_abstract = models.ManyToManyField(Rel

    )

    # VIRTUAL fields
    data_not_concrete_abstract = models.ForeignObject(
        Relation,
        on_delete=models.CASCADE,
        from_fields=["abstract_non_concrete_id"],
        to_fields=["id"],
        related_name="fo_abstract_rel",

ation, related_name="m2m_abstract_rel")
    friends_abstract = models.ManyToManyField("self", symmetrical=True)
    following_abstract = models.ManyToManyField(
        "self", related_name="followers_abstract", symmetrical=False


= Site.objects.create(domain="example.org")
        cls.a1 = Article.objects.create(
            site=cls.site,
            title="Title",
            created=datetime(2008, 3, 12, 11, 54),
        )
        cls.a2 = Article.objects.create(
            site=cls.site,
            title="Title 2",
            created=datetime(2009, 3, 12, 11, 54),
        )
        cls.a3 = Article.objects.create(
            site=cls.site,
            title="Title 3",
            created=datetime(2010, 3, 12, 11, 54),

r)
        self.signals = []

        pre_save.connect(self.pre_save_listener, sender=LogEntry)
        self.addCleanup(pre_save.disconnect, self.pre_save_listener, sender=LogEntry)

        post_save.connect(self.post_save_listener, sender=LogEntry)

  )
        LogEntry.objects.log_actions(
            cls.user.pk,
            [cls.a1],
            CHANGE,
            change_message="Changed something",
        )

    def setUp(self):
        self.client.force_login(self.use


, FloatField, Value, When
from django.db.models.expressions import (
    Expression,
    ExpressionList,
    ExpressionWrapper,
    Func,
    OrderByList,
    RawSQL,
)
from django.db.models.functions import Collate
from django.db.models.lookups import GreaterThan
from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature

from .models import (
    Article,
    DBArticle,
    DBDefaults,
    DBDefaultsFK,
    DBDefaultsFunction,
    DBDefaultsPK,
)

class DefaultTests(TestCase):
    def test_fie

seconds, 5)

    @skipUnlessDBFeature("supports_expression_defaults")
    def test_field_db_defaults_returning(self):
        a = DBArticle()
        a.save()
        self.assertIsInstance(a.id, int)
        expected_num_queries = (
            0 if connec

ld_defaults(self):
        a = Article()
        now = datetime.now()
        a.save()

        self.assertIsInstance(a.id, int)
        self.assertEqual(a.headline, "Default headline")
        self.assertLess((now - a.pub_date).


(self):
        """Test prefix can be set (see #18872)"""
        test_string = "test"

        get_request = self.request_factory.get("/")

        class TestFormMixin(FormMixin):
            request = get_request

        default_kwargs = TestFormMixin().get_form_kwargs()
        self.assertIsNone(default_kwargs.get("prefix"))

        set_mixin = TestFormMixin()
        set_mixin.prefix = test_string
        set_kwargs = set_mixin.get_form_kwargs()
        self.assertEqual(test_string, set_kwargs.get("pr

.Form,
            "get_form() should use provided form class.",
        )

        class FormClassTestFormMixin(TestFormMixin):
            form_class = forms.Form

        self.assertIsInstance(
            FormClassTestFormMixin().get_form(),

efix"))

    def test_get_form(self):
        class TestFormMixin(FormMixin):
            request = self.request_factory.get("/")

        self.assertIsInstance(
            TestFormMixin().get_form(forms.Form),
            forms


from django.core.checks import Error
from django.core.checks.compatibility.django_4_0 import check_csrf_trusted_origins
from django.test import SimpleTestCase
from django.test.utils import override_settings

class CheckCSRFTrustedOrigins(SimpleTestCase):
    @override_settings(CSRF_TRUSTED_ORIGINS=["example.com"])
    def test_invalid_url(self):
        self.assertEqual(
            check_csrf_trusted_origins(None),
            [
                Error(
                    "As of Django 4.0, the values in t

       id="4_0.E001",
                )
            ],
        )

    @override_settings(
        CSRF_TRUSTED_ORIGINS=["http://example.com", "https://example.com"],
    )
    def test_valid_urls(self):
        self.assertEqual(check_csrf_trusted_origins(N

he CSRF_TRUSTED_ORIGINS "
                    "setting must start with a scheme (usually http:// or "
                    "https://) but found example.com. See the release notes for "
                    "details.",


athlib import Path

from django.core.checks import Error
from django.core.checks.files import check_setting_file_upload_temp_dir
from django.test import SimpleTestCase

class FilesCheckTests(SimpleTestCase):
    def test_file_upload_temp_dir(self):
        tests = [
            None,
            "",
            Path.cwd(),
            str(Path.cwd()),
        ]
        for setting in tests:
            with self.subTest(setting), self.settings(FILE_UPLOAD_TEMP_DIR=setting):
                self.assertEqual

EMP_DIR=setting):
                self.assertEqual(
                    check_setting_file_upload_temp_dir(None),
                    [
                        Error(
                            "The FILE_UPLOAD_TEMP_DIR setting refers to the "

(check_setting_file_upload_temp_dir(None), [])

    def test_file_upload_temp_dir_nonexistent(self):
        for setting in ["nonexistent", Path("nonexistent")]:
            with self.subTest(setting), self.settings(FILE_UPLOAD_T


nctions 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"),

tate(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("nam

            ]
        )

    def test_empty(self):
        obj = Author.objects.annotate(json_object=JSONObject()).first()
        self.assertEqual(obj.json_object, {})

    def test_basic(self):
        obj = Author.objects.anno


rt Article, Bar, Base, Child, Foo, Whiz

class StringLookupTests(TestCase):
    def test_string_form_referencing(self):
        """
        Regression test for #1661 and #1662

        String form referencing of models works, both as pre and post
        reference, on all RelatedField types.
        """

        f1 = Foo(name="Foo1")
        f1.save()
        f2 = Foo(name="Foo2")
        f2.save()

        w1 = Whiz(name="Whiz1")
        w1.save()

        b1 = Bar(name="Bar1", normal=f1, fwd=w1, back=f2)

1", parent=base1)
        child1.save()

        self.assertEqual(child1.parent, base1)

    def test_unicode_chars_in_queries(self):
        """
        Regression tests for #3937

        make sure we can use unicode characters in queries.
        If the

        b1.save()

        self.assertEqual(b1.normal, f1)

        self.assertEqual(b1.fwd, w1)

        self.assertEqual(b1.back, f2)

        base1 = Base(name="Base1")
        base1.save()

        child1 = Child(name="Child


db import models
from django.db.models import QuerySet
from django.db.models.manager import BaseManager
from django.urls import reverse

class Artist(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        ordering = ["name"]
        verbose_name = "professional artist"
        verbose_name_plural = "professional artists"

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("artist_detail", kwargs={"pk": self.id})

class Autho

def get(self, *args, **kwargs):
        raise Author.DoesNotExist

DoesNotExistBookManager = BaseManager.from_queryset(DoesNotExistQuerySet)

class Book(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField()
    pages =

r(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField()

    class Meta:
        ordering = ["name"]

    def __str__(self):
        return self.name

class DoesNotExistQuerySet(QuerySet):


late/login_required/", login_required(TemplateView.as_view())),
    path(
        "template/simple/<foo>/",
        TemplateView.as_view(template_name="generic_views/about.html"),
    ),
    path(
        "template/custom/<foo>/",
        views.CustomTemplateView.as_view(template_name="generic_views/about.html"),
    ),
    path(
        "template/content_type/",
        TemplateView.as_view(
            template_name="generic_views/robots.txt", content_type="text/plain"
        ),
    ),
    path(

_views/about.html", extra_context={"title": "Title"}
        ),
    ),
    # DetailView
    path("detail/obj/", views.ObjectDetail.as_view()),
    path("detail/artist/<int:pk>/", views.ArtistDetail.as_view(), name="artist_detail"),
    path("detail/author/

"template/cached/<foo>/",
        cache_page(2)(TemplateView.as_view(template_name="generic_views/about.html")),
    ),
    path(
        "template/extra_context/",
        TemplateView.as_view(
            template_name="generic


m django.db import models

class Account(models.Model):
    num = models.IntegerField()

class Person(models.Model):
    GENDER_CHOICES = (
        ("M", "Male"),
        ("F", "Female"),
    )
    name = models.CharField(max_length=20)
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    pid = models.IntegerField(null=True, default=None)

class Employee(Person):
    employee_num = models.IntegerField(default=0)
    profile = models.ForeignKey(
        "Profile", models.SET_NULL, relat

 def get_attname_column(self):
        attname, _ = super().get_attname_column()
        return attname, None

class Profile(models.Model):
    name = models.CharField(max_length=200)
    salary = models.FloatField(default=1000.0)
    non_concrete = NonCo

ed_name="profiles", null=True
    )
    accounts = models.ManyToManyField("Account", related_name="employees", blank=True)

class NonConcreteField(models.IntegerField):
    def db_type(self, connection):
        return None


es.status_code, 200)
        self.assertEqual(
            list(res.context["date_list"]),
            list(Book.objects.dates("pubdate", "year", "DESC")),
        )
        self.assertEqual(list(res.context["latest"]), list(Book.objects.all()))
        self.assertTemplateUsed(res, "generic_views/book_archive.html")

    def test_archive_view_context_object_name(self):
        res = self.client.get("/dates/books/context_object_name/")
        self.assertEqual(res.status_code, 200)
        self.assertEqual(

test", res.context)
        self.assertTemplateUsed(res, "generic_views/book_archive.html")

    def test_empty_archive_view(self):
        Book.objects.all().delete()
        res = self.client.get("/dates/books/")
        self.assertEqual(res.status_code,

            list(res.context["date_list"]),
            list(Book.objects.dates("pubdate", "year", "DESC")),
        )
        self.assertEqual(list(res.context["thingies"]), list(Book.objects.all()))
        self.assertNotIn("la


ache_is_absolute,
)
from django.test import SimpleTestCase
from django.test.utils import override_settings

class CheckCacheSettingsAppDirsTest(SimpleTestCase):
    VALID_CACHES_CONFIGURATION = {
        "default": {
            "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
        },
    }
    INVALID_CACHES_CONFIGURATION = {
        "other": {
            "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
        },
    }

    @override_settings(CACHES=VALID_CACHES_CONFIGURATION)

=INVALID_CACHES_CONFIGURATION)
    def test_default_cache_not_included(self):
        """
        Error if 'default' not present in CACHES setting.
        """
        self.assertEqual(check_default_cache_is_configured(None), [E001])

class CheckCacheLoca

   def test_default_cache_included(self):
        """
        Don't error if 'default' is present in CACHES setting.
        """
        self.assertEqual(check_default_cache_is_configured(None), [])

    @override_settings(CACHES