"
        function(value) equals output. If output is None, function(value)
        equals value.
        """
        if output is None:
            output = value
        self.assertEqual(function(value), output)

    def test_escape(self):
        items = (
            ("&", "&"),
            ("<", "<"),
            (">", ">"),
            ('"', """),
            ("'", "'"),
        )
        # Substitution patterns for testing the above items.
        patterns = ("%s", "asdf%sfdsa", "

rn):
                        self.check_output(escape, pattern % value, pattern % output)
                        self.check_output(
                            escape, lazystr(pattern % value), pattern % output
                        )
                #

%s1", "1%sb")
        for value, output in items:
            with self.subTest(value=value, output=output):
                for pattern in patterns:
                    with self.subTest(value=value, output=output, pattern=patte


many relationships between the same two tables

In this example, a ``Person`` can have many friends, who are also ``Person``
objects. Friendship is a symmetrical relationship - if I am your friend, you
are my friend. Here, ``friends`` is an example of a symmetrical
``ManyToManyField``.

A ``Person`` can also have many idols - but while I may idolize you, you may
not think the same of me. Here, ``idols`` is an example of a non-symmetrical
``ManyToManyField``. Only recursive ``ManyToManyField`` fields may be

ango.db import models

class Person(models.Model):
    name = models.CharField(max_length=20)
    friends = models.ManyToManyField("self")
    colleagues = models.ManyToManyField("self", symmetrical=True, through="Colleague")
    idols = models.ManyToMany

non-symmetrical, and they are symmetrical by default.

This test validates that the many-to-many table is created using a mangled name
if there is a name clash, and tests that symmetry is preserved where
appropriate.
"""

from dj


ns import ImproperlyConfigured
from django.template import engines
from django.test import SimpleTestCase, override_settings

class TemplateUtilsTests(SimpleTestCase):
    @override_settings(TEMPLATES=[{"BACKEND": "raise.import.error"}])
    def test_backend_import_error(self):
        """
        Failing to import a backend keeps raising the original import error
        (#24265).
        """
        with self.assertRaisesMessage(ImportError, "No module named 'raise"):
            engines.all()
        wi

,
                # Incorrect: APP_DIRS and loaders are mutually incompatible.
                "APP_DIRS": True,
                "OPTIONS": {"loaders": []},
            }
        ]
    )
    def test_backend_improperly_configured(self):
        """

th self.assertRaisesMessage(ImportError, "No module named 'raise"):
            engines.all()

    @override_settings(
        TEMPLATES=[
            {
                "BACKEND": "django.template.backends.django.DjangoTemplates"


 to_path

class SafeMakeDirsTests(unittest.TestCase):
    def setUp(self):
        tmp = tempfile.TemporaryDirectory()
        self.base = tmp.name
        self.addCleanup(tmp.cleanup)

    def assertDirMode(self, path, expected):
        self.assertIs(os.path.isdir(path), True)
        if sys.platform == "win32":
            # Windows partially supports chmod: dirs always end up with 0o777.
            expected = 0o777

        # These tests assume a typical process umask (0o022 or similar): they

        self.assertEqual(stat.S_IMODE(os.stat(path).st_mode), expected)

    def test_creates_directory_hierarchy_with_permissions(self):
        path = os.path.join(self.base, "a", "b", "c")
        safe_makedirs(path, mode=0o755)

        self.assertDirM

# create directories with modes like 0o755 and 0o700, which don't have
        # group/world write bits, so a typical umask doesn't change the final
        # permissions. On unexpected failures, check whether umask has changed.


st.TestCase):
    def lazy_wrap(self, wrapped_object):
        """
        Wrap the given object into a LazyObject
        """

        class AdHocLazyObject(LazyObject):
            def _setup(self):
                self._wrapped = wrapped_object

        return AdHocLazyObject()

    def test_getattribute(self):
        """
        Proxy methods don't exist on wrapped objects unless they're set.
        """
        attrs = [
            "__getitem__",
            "__setitem__",
            "__delitem__",

tFalse(hasattr(obj, attr))
                setattr(foo, attr, attr)
                obj_with_attr = self.lazy_wrap(foo)
                self.assertTrue(hasattr(obj_with_attr, attr))
                self.assertEqual(getattr(obj_with_attr, attr), attr)

            "__iter__",
            "__len__",
            "__contains__",
        ]
        foo = Foo()
        obj = self.lazy_wrap(foo)
        for attr in attrs:
            with self.subTest(attr):
                self.asser


ibute and gives a nice error
        message upon test failure.
        """
        got = getattr(paginator, name)
        if coerce is not None:
            got = coerce(got)
        self.assertEqual(
            expected,
            got,
            "For '%s', expected %s but got %s. Paginator parameters were: %s"
            % (name, expected, got, params),
        )

    async def check_attribute_async(self, name, paginator, expected, params):
        """See check_attribute."""
        got = getattr(pa

 get_test_cases_for_test_paginator(self):
        nine = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        ten = nine + [10]
        eleven = ten + [11]
        return (
            # Each item is 2-tuple:
            #     First tuple is Paginator parameters - object_l

ginator, name)
        self.assertEqual(
            expected,
            await got(),
            "For '%s', expected %s but got %s. Paginator parameters were: %s"
            % (name, expected, got, params),
        )

    def


s(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.a, cls.b, cls.c, cls.d = [
            Person.objects.create(name=name)
            for name in ["Anne", "Bill", "Chuck", "David"]
        ]
        cls.a.friends.add(cls.b, cls.c)
        # Add m2m for Anne and Chuck in reverse direction.
        cls.d.friends.add(cls.a, cls.c)

    def test_recursive_m2m_all(self):
        for person, friends in (
            (self.a, [self.b, self.c, self.d]),
            (self.b, [self.a]),

verse_add(self):
        # Add m2m for Anne in reverse direction.
        self.b.friends.add(self.a)
        self.assertSequenceEqual(self.a.friends.all(), [self.b, self.c, self.d])
        self.assertSequenceEqual(self.b.friends.all(), [self.a])

    def

  (self.c, [self.a, self.d]),
            (self.d, [self.a, self.c]),
        ):
            with self.subTest(person=person):
                self.assertSequenceEqual(person.friends.all(), friends)

    def test_recursive_m2m_re


me_trunc,
    _sqlite_time_trunc,
)
from django.test import SimpleTestCase

class FunctionTests(SimpleTestCase):
    def test_sqlite_date_trunc(self):
        msg = "Unsupported lookup type: 'unknown-lookup'"
        with self.assertRaisesMessage(ValueError, msg):
            _sqlite_date_trunc("unknown-lookup", "2005-08-11", None, None)

    def test_sqlite_datetime_trunc(self):
        msg = "Unsupported lookup type: 'unknown-lookup'"
        with self.assertRaisesMessage(ValueError, msg):
            _s

:00:00", None, None)

    def test_sqlite_time_trunc(self):
        msg = "Unsupported lookup type: 'unknown-lookup'"
        with self.assertRaisesMessage(ValueError, msg):
            _sqlite_time_trunc("unknown-lookup", "2005-08-11 1:00:00", None, None)


t_intersection")
    def test_intersection_with_values(self):
        ReservedName.objects.create(name="a", order=2)
        qs1 = ReservedName.objects.all()
        reserved_name = qs1.intersection(qs1).values("name", "order", "id").get()
        self.assertEqual(reserved_name["name"], "a")
        self.assertEqual(reserved_name["order"], 2)
        reserved_name = qs1.intersection(qs1).values_list("name", "order", "id").get()
        self.assertEqual(reserved_name[:2], ("a", 2))

    @skipUnlessDBFeature(

=False)

    def test_union_distinct(self):
        qs1 = Number.objects.all()
        qs2 = Number.objects.all()
        self.assertEqual(len(list(qs1.union(qs2, all=True))), 20)
        self.assertEqual(len(list(qs1.union(qs2))), 10)

    def test_union_

"supports_select_difference")
    def test_simple_difference(self):
        qs1 = Number.objects.filter(num__lte=5)
        qs2 = Number.objects.filter(num__lte=4)
        self.assertNumbersEqual(qs1.difference(qs2), [5], ordered


dels.expressions import (
    Col,
    Exists,
    ExpressionWrapper,
    Func,
    RawSQL,
    Value,
)
from django.db.models.fields.related_lookups import RelatedIsNull
from django.db.models.functions import Lower
from django.db.models.lookups import Exact, GreaterThan, IsNull, LessThan
from django.db.models.sql.constants import SINGLE
from django.db.models.sql.query import JoinPromoter, Query, get_field_names_from_opts
from django.db.models.sql.where import AND, OR
from django.test import SimpleTestCase,

      where = query.build_where(Q(num__gt=2))
        lookup = where.children[0]
        self.assertIsInstance(lookup, GreaterThan)
        self.assertEqual(lookup.rhs, 2)
        self.assertEqual(lookup.lhs.target, Author._meta.get_field("num"))

    def

 TestCase, skipUnlessDBFeature
from django.test.utils import register_lookup

from .models import Author, Item, ObjectC, Ranking

class TestQuery(SimpleTestCase):
    def test_simple_query(self):
        query = Query(Author)


FAULT_DB_ALIAS, DatabaseError, connection
from django.db.models.sql import Query
from django.db.models.sql.compiler import SQLCompiler
from django.test import TestCase
from django.utils.deprecation import RemovedInDjango70Warning

from .models import Item

class SQLCompilerTest(TestCase):
    def test_repr(self):
        query = Query(Item)
        compiler = query.get_compiler(DEFAULT_DB_ALIAS, connection)
        self.assertEqual(
            repr(compiler),
            f"<SQLCompiler model=Item connecti

Item)
        compiler = SQLCompiler(query, connection, None)
        cursor = mock.MagicMock()

        # When execution fails, the cursor may have been closed.
        # Django's attempt to close it again will fail, and needs catching.
        execute_er

on="
            f"<DatabaseWrapper vendor={connection.vendor!r} alias='default'> "
            f"using='default'>",
        )

    def test_execute_sql_suppresses_cursor_closing_failure_on_exception(self):
        query = Query(


quenceEqual(
            Author.objects.filter(item=self.i2) & Author.objects.filter(item=self.i3),
            [self.a2],
        )

    def test_ticket2306(self):
        # Checking that no join types are "left outer" joins.
        query = Item.objects.filter(tags=self.t2).query
        self.assertNotIn(LOUTER, [x.join_type for x in query.alias_map.values()])

        self.assertSequenceEqual(
            Item.objects.filter(Q(tags=self.t1)).order_by("name"),
            [self.i1, self.i2],
        )

                Q(creator__name="fred") | Q(tags=self.t2)
            ),
            [self.i1],
        )

        # Each filter call is processed "at once" against a single table, so
        # this is different from the previous example as it tries to fin

     self.assertSequenceEqual(
            Item.objects.filter(Q(tags=self.t1)).filter(Q(tags=self.t2)),
            [self.i1],
        )
        self.assertSequenceEqual(
            Item.objects.filter(Q(tags=self.t1)).filter(


db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    friends = models.ManyToManyField("self", blank=True)
    rating = models.FloatField(null=True)

    def __str__(self):
        return self.name

class Publisher(models.Model):
    name = models.CharField(max_length=255)
    num_awards = models.IntegerField(null=True)
    duration = models.DurationField(blank=True, null=True)

    def __str__(self):
        return self.name

class

gits=6)
    authors = models.ManyToManyField(Author)
    contact = models.ForeignKey(Author, models.CASCADE, related_name="book_contact_set")
    publisher = models.ForeignKey(Publisher, models.CASCADE)
    pubdate = models.DateField()

    def __str__(sel

Book(models.Model):
    isbn = models.CharField(max_length=9)
    name = models.CharField(max_length=255)
    pages = models.IntegerField()
    rating = models.FloatField()
    price = models.DecimalField(decimal_places=2, max_di


    When,
)
from django.test import TestCase
from django.test.utils import Approximate

from .models import Author, Book, Publisher

class FilteredAggregateTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.a1 = Author.objects.create(name="test", age=40)
        cls.a2 = Author.objects.create(name="test2", age=60)
        cls.a3 = Author.objects.create(name="test3", age=100)
        cls.p1 = Publisher.objects.create(
            name="Apress", num_awards=3, duration=datetime.timedelt

ce=Decimal("30.00"),
            contact=cls.a1,
            publisher=cls.p1,
            pubdate=datetime.date(2007, 12, 6),
        )
        cls.b2 = Book.objects.create(
            isbn="067232959",
            name="Sams Teach Yourself Django in 24

a(days=1)
        )
        cls.b1 = Book.objects.create(
            isbn="159059725",
            name="The Definitive Guide to Django: Web Development Done Right",
            pages=447,
            rating=4.5,
            pri


4.5,
            price=Decimal("30.00"),
            contact=cls.a1,
            publisher=cls.p1,
            pubdate=datetime.date(2007, 12, 6),
        )
        cls.b2 = Book.objects.create(
            isbn="067232959",
            name="Sams Teach Yourself Django in 24 Hours",
            pages=528,
            rating=3.0,
            price=Decimal("23.09"),
            contact=cls.a3,
            publisher=cls.p2,
            pubdate=datetime.date(2008, 3, 3),
        )
        cls.b3 = Book.objects.

        pubdate=datetime.date(2008, 6, 23),
        )
        cls.b4 = Book.objects.create(
            isbn="013235613",
            name="Python Web Development with Django",
            pages=350,
            rating=4.0,
            price=Decimal("29.69

create(
            isbn="159059996",
            name="Practical Django Projects",
            pages=300,
            rating=4.0,
            price=Decimal("29.69"),
            contact=cls.a4,
            publisher=cls.p1,


aising_test(self):
        self._pre_setup.assert_called_once_with()
        raise Exception("debug() bubbles up exceptions before cleanup.")

    def simple_test(self):
        self._pre_setup.assert_called_once_with()

    @unittest.skip("Skip condition.")
    def skipped_test(self):
        pass

@mock.patch.dict(os.environ, {"PYTHON_COLORS": "0"})
@mock.patch.object(ErrorTestCase, "_post_teardown")
@mock.patch.object(ErrorTestCase, "_pre_setup")
class DebugInvocationTests(SimpleTestCase):
    def get_r

reviousClass(None, result)
        test_suite._handleModuleTearDown(result)

    def test_run_cleanup(self, _pre_setup, _post_teardown):
        """Simple test run: catches errors and runs cleanup."""
        test_suite = unittest.TestSuite()
        test_

unner(self):
        return unittest.TextTestRunner(stream=StringIO())

    def isolate_debug_test(self, test_suite, result):
        # Suite teardown needs to be manually called to isolate failures.
        test_suite._tearDownP


baseOperationForbidden,
    SimpleTestCase,
    TestData,
    is_pickable,
)

from .models import Car, Person, PossessedCar

class UnpicklableObject:
    def __getstate__(self):
        raise pickle.PickleError("cannot be pickled for testing reasons")

class TestSimpleTestCase(SimpleTestCase):
    def test_is_picklable_with_non_picklable_properties(self):
        """ParallelTestSuite requires that all TestCases are picklable."""
        self.non_picklable = lambda: 0
        self.assertEqual(self, pickle.

  @skipUnlessDBFeature("can_defer_constraint_checks")
    @skipUnlessDBFeature("supports_foreign_keys")
    def test_fixture_teardown_checks_constraints(self):
        rollback_atomics = self._rollback_atomics
        self._rollback_atomics = lambda connec

loads(pickle.dumps(self)))

    def test_is_picklable_with_non_picklable_object(self):
        unpicklable_obj = UnpicklableObject()
        self.assertEqual(is_pickable(unpicklable_obj), False)

class TestTestCase(TestCase):


nnections
from django.test import TestCase, TransactionTestCase, override_settings
from django.test.testcases import DatabaseOperationForbidden

from .models import Car, Person

class TestSerializedRollbackInhibitsPostMigrate(TransactionTestCase):
    """
    TransactionTestCase._fixture_teardown() inhibits the post_migrate signal
    for test classes with serialized_rollback=True.
    """

    available_apps = ["test_utils"]
    serialized_rollback = True

    def setUp(self):
        # self.available_app

   def test(self, call_command):
        # with a mocked call_command(), this doesn't have any effect.
        self._fixture_teardown()
        call_command.assert_called_with(
            "flush",
            interactive=False,
            allow_cascade=F

s must be None to test the serialized_rollback
        # condition.
        self.available_apps = None

    def tearDown(self):
        self.available_apps = ["test_utils"]

    @mock.patch("django.test.testcases.call_command")


ts."
            "SkippingTestCase.test_skip_unless_db_feature.<locals>.SkipTestCase."
            "test_foo) as SkippingTestCase.test_skip_unless_db_feature.<locals>."
            "SkipTestCase doesn't allow queries against the 'default' database.",
        )

    def test_skip_if_db_feature(self):
        """
        Testing the django.test.skipIfDBFeature decorator.
        """

        @skipIfDBFeature("__class__")
        def test_func():
            raise ValueError

        @skipIfDBFeature("notprovi

 def test_func4():
            raise ValueError

        @skipIfDBFeature("notprovided", "notprovided")
        def test_func5():
            raise ValueError

        self._assert_skipping(test_func, unittest.SkipTest)
        self._assert_skipping(test_f

ded")
        def test_func2():
            raise ValueError

        @skipIfDBFeature("__class__", "__class__")
        def test_func3():
            raise ValueError

        @skipIfDBFeature("__class__", "notprovided")


esponse
from django.template import engines
from django.template.response import TemplateResponse
from django.utils.decorators import (
    async_only_middleware,
    sync_and_async_middleware,
    sync_only_middleware,
)

log = []

class BaseMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        if iscoroutinefunction(self.get_response):
            markcoroutinefunction(self)

    def __call__(self, request):
        return self.get_response(request)

class Pr

ync def process_exception(self, request, exception):
        return HttpResponse("Exception caught")

class ProcessExceptionLogMiddleware(BaseMiddleware):
    def process_exception(self, request, exception):
        log.append("process-exception")

class

ocessExceptionMiddleware(BaseMiddleware):
    def process_exception(self, request, exception):
        return HttpResponse("Exception caught")

@async_only_middleware
class AsyncProcessExceptionMiddleware(BaseMiddleware):
    as


MIDDLEWARE=["middleware_exceptions.middleware.ProcessViewNoneMiddleware"]
    )
    def test_process_view_return_none(self):
        response = self.client.get("/middleware_exceptions/view/")
        self.assertEqual(mw.log, ["processed view normal_view"])
        self.assertEqual(response.content, b"OK")

    @override_settings(
        MIDDLEWARE=["middleware_exceptions.middleware.ProcessViewMiddleware"]
    )
    def test_process_view_return_response(self):
        response = self.client.get("/middleware

         "middleware_exceptions.middleware.LogMiddleware",
        ]
    )
    def test_templateresponse_from_process_view_rendered(self):
        """
        TemplateResponses returned from process_view() must be rendered before
        being passed to an

_exceptions/view/")
        self.assertEqual(response.content, b"Processed view normal_view")

    @override_settings(
        MIDDLEWARE=[
            "middleware_exceptions.middleware.ProcessViewTemplateResponseMiddleware",


rom django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.template import engines
from django.template.response import TemplateResponse

def normal_view(request):
    return HttpResponse("OK")

def template_response(request):
    template = engines["django"].from_string(
        "template_response OK{% for m in mw %}\n{{ m }}{% endfor %}"
    )
    return TemplateResponse(request, template, context={"mw": []})

def server_error(request):
    raise Exception("Erro

sponse.render()")

    return CustomHttpResponse("Error")

async def async_exception_in_render(request):
    class CustomHttpResponse(HttpResponse):
        async def render(self):
            raise Exception("Exception in HttpResponse.render()")

    ret

r in view")

def permission_denied(request):
    raise PermissionDenied()

def exception_in_render(request):
    class CustomHttpResponse(HttpResponse):
        def render(self):
            raise Exception("Exception in HttpRe


m django.db import models

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    expire_date = models.DateField()

    class Meta:
        get_latest_by = "pub_date"

class Person(models.Model):
    name = models.CharField(max_length=30)
    birthday = models.DateField()
    # Note that this model doesn't have "get_latest_by" set.

class Comment(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    likes_count =

 an intentionally broken QuerySet.__iter__ method.

class IndexErrorQuerySet(models.QuerySet):
    """
    Emulates the case when some internal code raises an unexpected
    IndexError.
    """

    def __iter__(self):
        raise IndexError

class Ind

models.PositiveIntegerField()

class OrderedArticle(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()

    class Meta:
        ordering = ["headline"]

# Ticket #23555 - model with


et_latest_by = Article._meta.get_latest_by

    def tearDown(self):
        Article._meta.get_latest_by = self._article_get_latest_by

    def test_earliest(self):
        # Because no Articles exist yet, earliest() raises ArticleDoesNotExist.
        with self.assertRaises(Article.DoesNotExist):
            Article.objects.earliest()

        a1 = Article.objects.create(
            headline="Article 1",
            pub_date=datetime(2005, 7, 26),
            expire_date=datetime(2005, 9, 1),
        )

rticle 3",
            pub_date=datetime(2005, 7, 28),
            expire_date=datetime(2005, 8, 27),
        )
        a4 = Article.objects.create(
            headline="Article 4",
            pub_date=datetime(2005, 7, 28),
            expire_date=datet

     a2 = Article.objects.create(
            headline="Article 2",
            pub_date=datetime(2005, 7, 27),
            expire_date=datetime(2005, 7, 28),
        )
        a3 = Article.objects.create(
            headline="A


rage(temp_storage_dir)

test_collation = SimpleLazyObject(
    lambda: connection.features.test_collations["virtual"]
)

class Foo(models.Model):
    a = models.CharField(max_length=10)
    d = models.DecimalField(max_digits=5, decimal_places=3)

def get_foo():
    return Foo.objects.get(id=1).pk

class Bar(models.Model):
    b = models.CharField(max_length=10)
    a = models.ForeignKey(Foo, models.CASCADE, default=get_foo, related_name="bars")

class Whiz(models.Model):
    CHOICES = {
        "Group 1

ld(choices=CHOICES, null=True)

class WhizDelayed(models.Model):
    c = models.IntegerField(choices=(), null=True)

# Contrived way of adding choices later.
WhizDelayed._meta.get_field("c").choices = Whiz.CHOICES

class WhizIter(models.Model):
    c =

": {
            1: "First",
            2: "Second",
        },
        "Group 2": (
            (3, "Third"),
            (4, "Fourth"),
        ),
        0: "Other",
        5: _("translated"),
    }
    c = models.IntegerFie


db import models
from django.test import SimpleTestCase

from .models import AutoModel, BigAutoModel, SmallAutoModel
from .test_integerfield import (
    BigIntegerFieldTests,
    IntegerFieldTests,
    SmallIntegerFieldTests,
)

class AutoFieldTests(IntegerFieldTests):
    model = AutoModel
    rel_db_type_class = models.IntegerField

class BigAutoFieldTests(BigIntegerFieldTests):
    model = BigAutoModel
    rel_db_type_class = models.BigIntegerField

class SmallAutoFieldTests(SmallIntegerFieldTests):

oField):
            with self.subTest(field.__name__):
                self.assertIsInstance(field(), models.AutoField)

    def test_issubclass_of_autofield(self):
        class MyBigAutoField(models.BigAutoField):
            pass

        class MySmall

    model = SmallAutoModel
    rel_db_type_class = models.SmallIntegerField

class AutoFieldInheritanceTests(SimpleTestCase):
    def test_isinstance_of_autofield(self):
        for field in (models.BigAutoField, models.SmallAut


from django.db import models
from django.test import TestCase

from .models import DataModel

class BinaryFieldTests(TestCase):
    binary_data = b"\x00\x46\xfe"

    def test_set_and_retrieve(self):
        data_set = (
            self.binary_data,
            bytearray(self.binary_data),
            memoryview(self.binary_data),
        )
        for bdata in data_set:
            with self.subTest(data=repr(bdata)):
                dm = DataModel(data=bdata)
                dm.save()
                dm

elf.assertEqual(bytes(dm.data), bytes(bdata))
                # Test default value
                self.assertEqual(bytes(dm.short_data), b"\x08")

    def test_max_length(self):
        dm = DataModel(short_data=self.binary_data * 4)
        with self.ass

 = DataModel.objects.get(pk=dm.pk)
                self.assertEqual(bytes(dm.data), bytes(bdata))
                # Resave (=update)
                dm.save()
                dm = DataModel.objects.get(pk=dm.pk)
                s


test import SimpleTestCase, TestCase
from django.test.utils import ignore_warnings
from django.utils.deprecation import RemovedInDjango70Warning

from .models import BooleanModel, FksToBooleans, NullBooleanModel

class BooleanFieldTests(TestCase):
    def _test_get_prep_value(self, f):
        self.assertIs(f.get_prep_value(True), True)
        self.assertIs(f.get_prep_value("1"), True)
        self.assertIs(f.get_prep_value(1), True)
        self.assertIs(f.get_prep_value(False), False)
        self.asser

ertIs(f.to_python(0), False)

    def test_booleanfield_get_prep_value(self):
        self._test_get_prep_value(models.BooleanField())

    def test_nullbooleanfield_get_prep_value(self):
        self._test_get_prep_value(models.BooleanField(null=True))

tIs(f.get_prep_value("0"), False)
        self.assertIs(f.get_prep_value(0), False)
        self.assertIsNone(f.get_prep_value(None))

    def _test_to_python(self, f):
        self.assertIs(f.to_python(1), True)
        self.ass


t SimpleTestCase, TestCase

from .models import Post

class TestCharField(TestCase):
    def test_max_length_passed_to_formfield(self):
        """
        CharField passes its max_length attribute to form fields created using
        the formfield() method.
        """
        cf1 = models.CharField()
        cf2 = models.CharField(max_length=1234)
        self.assertIsNone(cf1.formfield().max_length)
        self.assertEqual(1234, cf2.formfield().max_length)

    def test_lookup_integer_in_charfield(self

le 😀")

    def test_assignment_from_choice_enum(self):
        class Event(models.TextChoices):
            C = "Carnival!"
            F = "Festival!"

        p1 = Post.objects.create(title=Event.C, body=Event.F)
        p1.refresh_from_db()
        sel

):
        self.assertEqual(Post.objects.filter(title=9).count(), 0)

    def test_emoji(self):
        p = Post.objects.create(title="Smile 😀", body="Whatever.")
        p.refresh_from_db()
        self.assertEqual(p.title, "Smi


de_settings, skipUnlessDBFeature
from django.test.utils import requires_tz_support
from django.utils import timezone

from .models import DateTimeModel

class DateTimeFieldTests(TestCase):
    def test_datetimefield_to_python_microseconds(self):
        """DateTimeField.to_python() supports microseconds."""
        f = models.DateTimeField()
        self.assertEqual(
            f.to_python("2001-01-02 03:04:05.000006"),
            datetime.datetime(2001, 1, 2, 3, 4, 5, 6),
        )
        self.assertEq

roseconds."""
        f = models.TimeField()
        self.assertEqual(f.to_python("01:02:03.000004"), datetime.time(1, 2, 3, 4))
        self.assertEqual(f.to_python("01:02:03.999999"), datetime.time(1, 2, 3, 999999))

    def test_datetimes_save_completel

ual(
            f.to_python("2001-01-02 03:04:05.999999"),
            datetime.datetime(2001, 1, 2, 3, 4, 5, 999999),
        )

    def test_timefield_to_python_microseconds(self):
        """TimeField.to_python() supports mic


o.db.models import Max
from django.test import TestCase

from .models import BigD, Foo

class DecimalFieldTests(TestCase):
    def test_to_python(self):
        f = models.DecimalField(max_digits=4, decimal_places=2)
        self.assertEqual(f.to_python(3), Decimal("3"))
        self.assertEqual(f.to_python("3.14"), Decimal("3.14"))
        # to_python() converts floats and honors max_digits.
        self.assertEqual(f.to_python(3.1415926535897), Decimal("3.142"))
        self.assertEqual(f.to_python(2.4),

lf):
        field = models.DecimalField(max_digits=4, decimal_places=2)
        msg = "“%s” value must be a decimal number."
        tests = [
            (),
            [],
            {},
            set(),
            object(),
            complex(),

 Decimal("2.400"))
        # Uses default rounding of ROUND_HALF_EVEN.
        self.assertEqual(f.to_python(2.0625), Decimal("2.062"))
        self.assertEqual(f.to_python(2.1875), Decimal("2.188"))

    def test_invalid_value(se


ms
from django.core import exceptions, serializers
from django.db import models
from django.test import SimpleTestCase, TestCase

from .models import DurationModel, NullDurationModel

class TestSaveLoad(TestCase):
    def test_simple_roundtrip(self):
        duration = datetime.timedelta(microseconds=8999999999999999)
        DurationModel.objects.create(field=duration)
        loaded = DurationModel.objects.get()
        self.assertEqual(loaded.field, duration)

    def test_create_empty(self):
        Nu

onModel.objects.create(field=value)
        d.refresh_from_db()
        self.assertEqual(d.field, value)

class TestQuerying(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.objs = [
            DurationModel.objects.create(field=dateti

llDurationModel.objects.create()
        loaded = NullDurationModel.objects.get()
        self.assertIsNone(loaded.field)

    def test_fractional_seconds(self):
        value = datetime.timedelta(seconds=2.05)
        d = Durati


ls.ForeignObject,
    models.ManyToManyField,
    GenericForeignKey,
    GenericRelation,
)

NON_EDITABLE_FIELDS = (
    models.BinaryField,
    GenericForeignKey,
    GenericRelation,
)

RELATION_FIELDS = (
    models.ForeignKey,
    models.ForeignObject,
    models.ManyToManyField,
    models.OneToOneField,
    GenericForeignKey,
    GenericRelation,
)

MANY_TO_MANY_CLASSES = {
    models.ManyToManyField,
}

MANY_TO_ONE_CLASSES = {
    models.ForeignObject,
    models.ForeignKey,
    GenericForeignKey,
}

 "model",
    "hidden",
    "one_to_many",
    "many_to_one",
    "many_to_many",
    "one_to_one",
    "related_model",
)

FLAG_PROPERTIES_FOR_RELATIONS = (
    "one_to_many",
    "many_to_one",
    "many_to_many",
    "one_to_one",
)

class FieldFlagsTe

ONE_TO_MANY_CLASSES = {
    models.ForeignObjectRel,
    models.ManyToOneRel,
    GenericRelation,
}

ONE_TO_ONE_CLASSES = {
    models.OneToOneField,
}

FLAG_PROPERTIES = (
    "concrete",
    "editable",
    "is_relation",


from django.core.files.base import ContentFile
from django.core.files.uploadedfile import TemporaryUploadedFile
from django.db import IntegrityError, models
from django.test import TestCase, override_settings
from django.test.utils import isolate_apps

from .models import Document, DocumentWithTimestamp

class FileFieldTests(TestCase):
    def test_clearable(self):
        """
        FileField.save_form_data() will clear its instance attribute value if
        passed False.
        """
        d = Docume

):
        """
        FileField.save_form_data() considers None to mean "no change" rather
        than "clear".
        """
        d = Document(myfile="something.txt")
        self.assertEqual(d.myfile, "something.txt")
        field = d._meta.get_field

nt(myfile="something.txt")
        self.assertEqual(d.myfile, "something.txt")
        field = d._meta.get_field("myfile")
        field.save_form_data(d, False)
        self.assertEqual(d.myfile, "")

    def test_unchanged(self


nsaction
from django.test import TestCase

from .models import FloatModel

class TestFloatField(TestCase):
    def test_float_validates_object(self):
        instance = FloatModel(size=2.5)
        # Try setting float field to unsaved object
        instance.size = instance
        with transaction.atomic():
            with self.assertRaises(TypeError):
                instance.save()
        # Set value to valid and save
        instance.size = 2.5
        instance.save()
        self.assertTrue(instance

e with FloatField."
        ) % instance
        with transaction.atomic():
            with self.assertRaisesMessage(TypeError, msg):
                instance.save()
        # Try setting field to object on retrieved object
        obj = FloatModel.object

.id)
        # Set field to object on saved instance
        instance.size = instance
        msg = (
            "Tried to update field model_fields.FloatModel.size with a model "
            "instance, %r. Use a value compatibl


DBFeature
from django.test.utils import isolate_apps

from .models import Bar, FkToChar, Foo, PrimaryKeyCharModel

class ForeignKeyTests(TestCase):
    def test_callable_default(self):
        """A lazy callable may be used for ForeignKey.default."""
        a = Foo.objects.create(id=1, a="abc", d=Decimal("12.34"))
        b = Bar.objects.create(b="bcd")
        self.assertEqual(b.a, a)

    @skipIfDBFeature("interprets_empty_strings_as_nulls")
    def test_empty_string_fk(self):
        """
        Empty

fk_model_empty = FkToChar.objects.select_related("out").get(
            id=fk_model_empty.pk
        )
        self.assertEqual(fk_model_empty.out, char_model_empty)

    @isolate_apps("model_fields")
    def test_warning_when_unique_true_on_fk(self):

strings foreign key values don't get converted to None (#19299).
        """
        char_model_empty = PrimaryKeyCharModel.objects.create(string="")
        fk_model_empty = FkToChar.objects.create(out=char_model_empty)


 django.test.utils import isolate_apps

from .models import (
    Foo,
    GeneratedModel,
    GeneratedModelCheckConstraint,
    GeneratedModelCheckConstraintVirtual,
    GeneratedModelFieldWithConverters,
    GeneratedModelNonAutoPk,
    GeneratedModelNull,
    GeneratedModelNullVirtual,
    GeneratedModelOutputFieldDbCollation,
    GeneratedModelOutputFieldDbCollationVirtual,
    GeneratedModelParams,
    GeneratedModelParamsVirtual,
    GeneratedModelUniqueConstraint,
    GeneratedModelUniqueConstraintV

eneratedField(
                expression=Lower("name"),
                output_field=CharField(max_length=255),
                editable=True,
                db_persist=False,
            )

    @isolate_apps("model_fields")
    def test_contribute_to_cl

irtual,
    GeneratedModelVirtual,
)

class BaseGeneratedFieldTests(SimpleTestCase):
    def test_editable_unsupported(self):
        with self.assertRaisesMessage(ValueError, "GeneratedField cannot be editable."):
            G


core.exceptions import ValidationError
from django.db import models
from django.test import TestCase

from .models import GenericIPAddress

class GenericIPAddressFieldTests(TestCase):
    def test_genericipaddressfield_formfield_protocol(self):
        """
        GenericIPAddressField with a specified protocol does not generate a
        formfield without a protocol.
        """
        model_field = models.GenericIPAddressField(protocol="IPv4")
        form_field = model_field.formfield()
        with se

):
            form_field.clean("127.0.0.1")

    def test_null_value(self):
        """
        Null values should be resolved to None.
        """
        GenericIPAddress.objects.create()
        o = GenericIPAddress.objects.get()
        self.assertIsN

lf.assertRaises(ValidationError):
            form_field.clean("::1")
        model_field = models.GenericIPAddressField(protocol="IPv6")
        form_field = model_field.formfield()
        with self.assertRaises(ValidationError


sonDimensionsFirst = Person
    PersonTwoImages = PersonNoReadImage = Person

class ImageFieldTestMixin(SerializeMixin):
    """
    Mixin class to provide common functionality to ImageField test classes.
    """

    lockfile = __file__

    # Person model to use for tests.
    PersonModel = PersonWithHeightAndWidth
    # File class to use for file instances.
    File = ImageFile

    def setUp(self):
        """
        Creates a pristine temp directory (or deletes and recreates if it
        already exi

emp_storage_dir)
        self.addCleanup(shutil.rmtree, temp_storage_dir)
        file_path1 = os.path.join(os.path.dirname(__file__), "4x8.png")
        self.file1 = self.File(open(file_path1, "rb"), name="4x8.png")
        self.addCleanup(self.file1.clos

sts) that the model uses as its storage directory.

        Sets up two ImageFile instances for use in tests.
        """
        if os.path.exists(temp_storage_dir):
            shutil.rmtree(temp_storage_dir)
        os.mkdir(t


erFieldTests(TestCase):
    model = IntegerModel
    documented_range = (-2147483648, 2147483647)
    rel_db_type_class = models.IntegerField

    @property
    def backend_range(self):
        field = self.model._meta.get_field("value")
        internal_type = field.get_internal_type()
        return connection.ops.integer_field_range(internal_type)

    def test_documented_range(self):
        """
        Values within the documented safe range pass validation, and can be
        saved and retrieved witho

te=min_value)
        self.assertEqual(qs.count(), 1)
        self.assertEqual(qs[0].value, min_value)

        instance = self.model(value=max_value)
        instance.full_clean()
        instance.save()
        qs = self.model.objects.filter(value__gte=m

ut corruption.
        """
        min_value, max_value = self.documented_range

        instance = self.model(value=min_value)
        instance.full_clean()
        instance.save()
        qs = self.model.objects.filter(value__l


t connection
from django.test import TestCase

from ..models import Person, Tag

@unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests.")
class SQLiteOperationsTests(TestCase):
    def test_sql_flush(self):
        self.assertEqual(
            connection.ops.sql_flush(
                no_style(),
                [Person._meta.db_table, Tag._meta.db_table],
            ),
            [
                'DELETE FROM "backends_person";',
                'DELETE FROM "backends_tag";',
            ]

      self.assertEqual(
            # The tables are processed in an unordered set.
            sorted(statements),
            [
                'DELETE FROM "backends_person";',
                'DELETE FROM "backends_tag";',
                'DELETE FROM

,
        )

    def test_sql_flush_allow_cascade(self):
        statements = connection.ops.sql_flush(
            no_style(),
            [Person._meta.db_table, Tag._meta.db_table],
            allow_cascade=True,
        )


irectBase
from django.shortcuts import redirect
from django.test import SimpleTestCase, override_settings
from django.test.utils import require_jinja2
from django.utils.http import MAX_URL_REDIRECT_LENGTH

@override_settings(ROOT_URLCONF="shortcuts.urls")
class RenderTests(SimpleTestCase):
    def test_render(self):
        response = self.client.get("/render/")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, b"FOO.BAR../render/\n")
        self.assertEqual(re

r/multiple_templates/")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, b"FOO.BAR../render/multiple_templates/\n")

    def test_render_with_content_type(self):
        response = self.client.get("/render/cont

sponse.headers["Content-Type"], "text/html; charset=utf-8")
        self.assertFalse(hasattr(response.context.request, "current_app"))

    def test_render_with_multiple_templates(self):
        response = self.client.get("/rende


ango.db import models

# Forward declared intermediate model
class Membership(models.Model):
    person = models.ForeignKey("Person", models.CASCADE)
    group = models.ForeignKey("Group", models.CASCADE)
    price = models.IntegerField(default=100)

# using custom id column to test ticket #11107
class UserMembership(models.Model):
    id = models.AutoField(db_column="usermembership_id", primary_key=True)
    user = models.ForeignKey(User, models.CASCADE)
    group = models.ForeignKey("Group", models.CASC

(max_length=128)
    # Membership object defined as a class
    members = models.ManyToManyField(Person, through=Membership)
    user_members = models.ManyToManyField(User, through="UserMembership")

    def __str__(self):
        return self.name

# Usin

ADE)
    price = models.IntegerField(default=100)

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __str__(self):
        return self.name

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


)

        cls.rock = Group.objects.create(name="Rock")
        cls.roll = Group.objects.create(name="Roll")

        cls.frank = User.objects.create_user("frank", "frank@example.com", "password")
        cls.jane = User.objects.create_user("jane", "jane@example.com", "password")

        # normal intermediate model
        cls.bob_rock = Membership.objects.create(person=cls.bob, group=cls.rock)
        cls.bob_roll = Membership.objects.create(
            person=cls.bob, group=cls.roll, price=50
        )

frank, group=cls.rock)
        cls.frank_roll = UserMembership.objects.create(user=cls.frank, group=cls.roll)
        cls.jane_rock = UserMembership.objects.create(user=cls.jane, group=cls.rock)

    def test_retrieve_reverse_m2m_items(self):
        self.

        cls.jim_rock = Membership.objects.create(
            person=cls.jim, group=cls.rock, price=50
        )

        # intermediate model with custom id column
        cls.frank_rock = UserMembership.objects.create(user=cls.


ent-type/object-id field. A ``GenericForeignKey`` field can point to any
object, be it animal, vegetable, or mineral.

The canonical example is tags (although this example implementation is *far*
from complete).
"""

from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models

class TaggedItem(models.Model):
    """A tag on an item."""

    tag = models.SlugField()
    content_type = models.Foreign

lf.tag

class ValuableTaggedItem(TaggedItem):
    value = models.PositiveIntegerField()

class AbstractComparison(models.Model):
    comparative = models.CharField(max_length=50)

    content_type1 = models.ForeignKey(
        ContentType, models.CASCADE

Key(ContentType, models.CASCADE)
    object_id = models.PositiveIntegerField()

    content_object = GenericForeignKey()

    class Meta:
        ordering = ["tag", "content_type__model"]

    def __str__(self):
        return se


def wraps_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        value = f(*args, **kwargs)
        return f"{value} -- decorated by @wraps."

    return wrapper

def common_decorator(f):
    def wrapper(*args, **kwargs):
        value = f(*args, **kwargs)
        return f"{value} -- common decorated."

    return wrapper

class TestRss2Feed(views.Feed):
    title = "My blog"
    description = "A more thorough description of my blog."
    link = "/blog/"
    feed_guid = "/foo/bar/1234"

ms(self):
        return Entry.objects.all()

    def item_description(self, item):
        return "Overridden description: %s" % item

    def item_pubdate(self, item):
        return item.published

    def item_updateddate(self, item):
        return it

author_name = "Sally Smith"
    author_email = "test@example.com"
    author_link = "http://www.example.com/"
    categories = ("python", "django")
    feed_copyright = "Copyright (c) 2007, Sally Smith"
    ttl = 600

    def ite


urlpatterns = [
    path("syndication/rss2/", feeds.TestRss2Feed()),
    path(
        "syndication/rss2/with-callable-object/", feeds.TestRss2FeedWithCallableObject()
    ),
    path(
        "syndication/rss2/with-decorated-methods/",
        feeds.TestRss2FeedWithDecoratedMethod(),
    ),
    path(
        "syndication/rss2/with-wrong-decorated-methods/",
        feeds.TestRss2FeedWithWrongDecoratedMethod(),
    ),
    path("syndication/rss2/articles/<int:entry_id>/", feeds.TestGetObjectFeed()),
    path

    ),
    path("syndication/rss091/", feeds.TestRss091Feed()),
    path("syndication/no_pubdate/", feeds.TestNoPubdateFeed()),
    path("syndication/atom/", feeds.TestAtomFeed()),
    path("syndication/latest/", feeds.TestLatestFeed()),
    path("syndicat

(
        "syndication/rss2/guid_ispermalink_true/",
        feeds.TestRss2FeedWithGuidIsPermaLinkTrue(),
    ),
    path(
        "syndication/rss2/guid_ispermalink_false/",
        feeds.TestRss2FeedWithGuidIsPermaLinkFalse(),


override_settings

APP_CONFIG = apps.get_app_config("migrate_signals")
SIGNAL_ARGS = [
    "app_config",
    "verbosity",
    "interactive",
    "using",
    "stdout",
    "plan",
    "apps",
]
MIGRATE_DATABASE = "default"
MIGRATE_VERBOSITY = 0
MIGRATE_INTERACTIVE = False

class Receiver:
    def __init__(self, signal):
        self.call_counter = 0
        self.call_args = None
        signal.connect(self, sender=APP_CONFIG)

    def __call__(self, signal, sender, **kwargs):
        self.call_counter += 1

f, signal):
        self.signal = signal
        self.call_counter = 0
        self.call_args = None
        self.signal.connect(self, sender=APP_CONFIG)

    def __call__(self, signal, sender, **kwargs):
        # Although test runner calls migrate for se

        self.call_args = kwargs

class OneTimeReceiver:
    """
    Special receiver for handle the fact that test runner calls migrate for
    several databases and several times for some of them.
    """

    def __init__(sel


f.assertEqual(repr(media_type), "<MediaType: >")

    def test_str(self):
        self.assertEqual(str(MediaType("*/*; q=0.8")), "*/*; q=0.8")
        self.assertEqual(str(MediaType("application/xml")), "application/xml")
        self.assertEqual(
            str(MediaType("application/xml;type=madeup;q=42")),
            "application/xml; type=madeup; q=42",
        )

    def test_repr(self):
        self.assertEqual(repr(MediaType("*/*; q=0.8")), "<MediaType: */*; q=0.8>")
        self.assertEqual(

 (" */* ", "application/json"),
            ("application/*", "application/json"),
            ("application/*", "application/*"),
            ("application/xml", "application/xml"),
            (" application/xml ", "application/xml"),
            ("appli

       repr(MediaType("application/xml")),
            "<MediaType: application/xml>",
        )

    def test_match(self):
        tests = [
            ("*/*; q=0.8", "*/*"),
            ("*/*", "application/json"),


request.POST.urlencode(), "")

        # and FILES should be MultiValueDict
        self.assertEqual(request.FILES.getlist("foo"), [])

        self.assertIsNone(request.content_type)
        self.assertIsNone(request.content_params)

    def test_httprequest_full_path(self):
        request = HttpRequest()
        request.path_info = "/;some/?awful/=path/foo:bar/"
        request.path = "/prefix" + request.path_info
        request.META["QUERY_STRING"] = ";some=query&+query=string"
        expected = "/%3B

h_with_query_string_and_fragment(self):
        request = HttpRequest()
        request.path_info = "/foo#bar"
        request.path = "/prefix" + request.path_info
        request.META["QUERY_STRING"] = "baz#quux"
        self.assertEqual(request.get_full_

some/%3Fawful/%3Dpath/foo:bar/?;some=query&+query=string"
        self.assertEqual(request.get_full_path_info(), expected)
        self.assertEqual(request.get_full_path(), "/prefix" + expected)

    def test_httprequest_full_pat


an initialize a model instance using positional arguments,
        which should match the field order as defined in the model.
        """
        a = Article(None, "Second article", datetime(2005, 7, 29))
        a.save()

        self.assertEqual(a.headline, "Second article")
        self.assertEqual(a.pub_date, datetime(2005, 7, 29, 0, 0))

    def test_can_create_instance_using_kwargs(self):
        a = Article(
            id=None,
            headline="Third article",
            pub_date=datetime(200

lf):
        a1 = Article.objects.create(
            headline="First", pub_date=datetime(2005, 7, 30, 0, 0)
        )
        a2 = Article.objects.create(
            headline="First", pub_date=datetime(2005, 7, 30, 0, 0)
        )
        a3 = Article.ob

5, 7, 30),
        )
        a.save()
        self.assertEqual(a.headline, "Third article")
        self.assertEqual(a.pub_date, datetime(2005, 7, 30, 0, 0))

    def test_autofields_generate_different_values_for_each_instance(se


       self.assertEqual(models.Index.suffix, "idx")

    def test_repr(self):
        index = models.Index(fields=["title"])
        named_index = models.Index(fields=["title"], name="title_idx")
        multi_col_index = models.Index(fields=["title", "author"])
        partial_index = models.Index(
            fields=["title"], name="long_books_idx", condition=models.Q(pages__gt=400)
        )
        covering_index = models.Index(
            fields=["title"],
            name="include_idx",
            i

        func_index = models.Index(Lower("title"), "subtitle", name="book_func_idx")
        tablespace_index = models.Index(
            fields=["title"],
            db_tablespace="idx_tbls",
            name="book_tablespace_idx",
        )
        self

nclude=["author", "pages"],
        )
        opclasses_index = models.Index(
            fields=["headline", "body"],
            name="opclasses_idx",
            opclasses=["varchar_pattern_ops", "text_pattern_ops"],
        )


ustomPk,
    Detail,
    Food,
    Individual,
    JSONFieldNullable,
    Member,
    Note,
    Number,
    Order,
    Paragraph,
    RelatedObject,
    SingleObject,
    SpecialCategory,
    Tag,
    Valid,
)

class WriteToOtherRouter:
    def db_for_write(self, model, **hints):
        return "other"

class BulkUpdateNoteTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.notes = [Note.objects.create(note=str(i), misc=str(i)) for i in range(10)]

    def create_tags(self):

cts.bulk_update(self.notes, ["note"])
        self.assertCountEqual(
            Note.objects.values_list("note", flat=True),
            [cat.note for cat in self.notes],
        )

    def test_multiple_fields(self):
        for note in self.notes:

self.tags = [Tag.objects.create(name=str(i)) for i in range(10)]

    def test_simple(self):
        for note in self.notes:
            note.note = "test-%s" % note.id
        with self.assertNumQueries(1):
            Note.obje


rom django.test import TestCase, skipUnlessDBFeature
from django.test.utils import CaptureQueriesContext

from .models import DumbCategory, NonIntegerPKReturningModel, ReturningModel

@skipUnlessDBFeature("can_return_columns_from_insert")
class ReturningValuesTests(TestCase):
    def test_insert_returning(self):
        with CaptureQueriesContext(connection) as captured_queries:
            DumbCategory.objects.create()
        self.assertIn(
            "RETURNING %s.%s"
            % (
                co

turning_non_integer(self):
        obj = NonIntegerPKReturningModel.objects.create()
        self.assertTrue(obj.created)
        self.assertIsInstance(obj.created, datetime.datetime)

    def test_insert_returning_non_integer_from_literal_value(self):

nnection.ops.quote_name(DumbCategory._meta.db_table),
                connection.ops.quote_name(DumbCategory._meta.get_field("id").column),
            ),
            captured_queries[-1]["sql"],
        )

    def test_insert_re


ure, skipUnlessDBFeature
from django.test.utils import CaptureQueriesContext

from .models import Tag

@skipUnlessDBFeature("supports_explaining_query_execution")
class ExplainTests(TestCase):
    def test_basic(self):
        querysets = [
            Tag.objects.filter(name="test"),
            Tag.objects.filter(name="test").select_related("parent"),
            Tag.objects.filter(name="test").prefetch_related("children"),
            Tag.objects.filter(name="test").annotate(Count("children")),

e="test"))
            )
        if connection.features.has_select_for_update:
            querysets.append(Tag.objects.select_for_update().filter(name="test"))
        supported_formats = connection.features.supported_explain_formats
        all_formats =

    Tag.objects.filter(name="test").values_list("name"),
        ]
        if connection.features.supports_select_union:
            querysets.append(
                Tag.objects.order_by().union(Tag.objects.order_by().filter(nam


:
    def test_get_primary_key_column(self):
        """
        Get the primary key column regardless of whether or not it has
        quotation.
        """
        testable_column_strings = (
            ("id", "id"),
            ("[id]", "id"),
            ("`id`", "id"),
            ('"id"', "id"),
            ("[id col]", "id col"),
            ("`id col`", "id col"),
            ('"id col"', "id col"),
        )
        with connection.cursor() as cursor:
            for column, expected_string in te

)
                        field = connection.introspection.get_primary_key_column(
                            cursor, "test_primary"
                        )
                        self.assertEqual(field, expected_string)
                    finally:

stable_column_strings:
                sql = "CREATE TABLE test_primary (%s int PRIMARY KEY NOT NULL)" % column
                with self.subTest(column=column):
                    try:
                        cursor.execute(sql


m django.shortcuts import render

def render_view(request):
    return render(
        request,
        "shortcuts/render_test.html",
        {
            "foo": "FOO",
            "bar": "BAR",
        },
    )

def render_view_with_multiple_templates(request):
    return render(
        request,
        [
            "shortcuts/no_such_template.html",
            "shortcuts/render_test.html",
        ],
        {
            "foo": "FOO",
            "bar": "BAR",
        },
    )

def render_view_wit

def render_view_with_status(request):
    return render(
        request,
        "shortcuts/render_test.html",
        {
            "foo": "FOO",
            "bar": "BAR",
        },
        status=403,
    )

def render_view_with_using(request):
    us

h_content_type(request):
    return render(
        request,
        "shortcuts/render_test.html",
        {
            "foo": "FOO",
            "bar": "BAR",
        },
        content_type="application/x-rendertest",
    )


(forms.TextInput):
    pass

class TaggedItemForm(forms.ModelForm):
    class Meta:
        model = TaggedItem
        fields = "__all__"
        widgets = {"tag": CustomWidget}

class GenericInlineFormsetTests(TestCase):
    def test_output(self):
        GenericFormSet = generic_inlineformset_factory(TaggedItem, extra=1)
        formset = GenericFormSet()
        self.assertHTMLEqual(
            "".join(form.as_p() for form in formset.forms),
            """
            <p><label
                for="i

_relations-taggeditem-content_type-object_id-0-tag"
                maxlength="50">

            Delete:
            <input type="checkb

d_generic_relations-taggeditem-content_type-object_id-0-tag">
            Tag:</label>
            <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag"
                type="text"
                name="generic


etime.datetime(1980, 1, 1, 12, 30),
            published=datetime.datetime(1986, 9, 25, 20, 15, 00),
        )
        cls.e2 = Entry.objects.create(
            title="My second entry",
            updated=datetime.datetime(2008, 1, 2, 12, 30),
            published=datetime.datetime(2006, 3, 17, 18, 0),
        )
        cls.e3 = Entry.objects.create(
            title="My third entry",
            updated=datetime.datetime(2008, 1, 2, 13, 30),
            published=datetime.datetime(2005, 6, 14, 10, 45)

 cls.e5 = Entry.objects.create(
            title="My last entry",
            updated=datetime.datetime(2013, 1, 20, 0, 0),
            published=datetime.datetime(2013, 3, 25, 20, 0),
        )
        cls.a1 = Article.objects.create(
            title="

,
        )
        cls.e4 = Entry.objects.create(
            title="A & B < C > D",
            updated=datetime.datetime(2008, 1, 3, 13, 30),
            published=datetime.datetime(2005, 11, 25, 12, 11, 23),
        )


st.client import RequestFactory

@override_settings(
    TEMPLATES=[
        {
            "BACKEND": "django.template.backends.dummy.TemplateStrings",
            "APP_DIRS": True,
        },
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            "OPTIONS": {
                "context_processors": [
                    "django.template.context_processors.request",
                ],
                "loaders": [
                    "django.template.loaders.filesystem

 template = get_template("template_loader/hello.html")
        self.assertEqual(template.render(), "Hello! (template strings)\n")

    def test_get_template_second_engine(self):
        template = get_template("template_loader/goodbye.html")
        self.a

.Loader",
                    "django.template.loaders.app_directories.Loader",
                ],
            },
        },
    ]
)
class TemplateLoaderTests(SimpleTestCase):
    def test_get_template_first_engine(self):


db import models

class Article(models.Model):
    headline = models.CharField(max_length=100, default="Default headline")
    pub_date = models.DateTimeField()

    class Meta:
        ordering = ("pub_date", "headline")

    def __str__(self):
        return self.headline

class FeaturedArticle(models.Model):
    article = models.OneToOneField(Article, models.CASCADE, related_name="featured")

class ArticleSelectOnSave(Article):
    class Meta:
        proxy = True
        select_on_save = True

class

ll=True, blank=True)
    article_cited = models.ForeignKey(
        Article, models.SET_NULL, null=True, blank=True, related_name="cited"
    )

    def __str__(self):
        # This method intentionally doesn't work for all cases - part
        # of the t

 SelfRef(models.Model):
    selfref = models.ForeignKey(
        "self",
        models.SET_NULL,
        null=True,
        blank=True,
        related_name="+",
    )
    article = models.ForeignKey(Article, models.SET_NULL, nu


self.name

class Note(models.Model):
    note = models.CharField(max_length=100)
    misc = models.CharField(max_length=25)
    tag = models.ForeignKey(Tag, models.SET_NULL, blank=True, null=True)
    negate = models.BooleanField(default=True)

    class Meta:
        ordering = ["note"]

    def __str__(self):
        return self.note

class Annotation(models.Model):
    name = models.CharField(max_length=10)
    tag = models.ForeignKey(Tag, models.CASCADE)
    notes = models.ManyToManyField(Note)

    d

odel):
    info = models.CharField(max_length=100)
    note = models.ForeignKey(Note, models.CASCADE, null=True)
    value = models.IntegerField(null=True)
    date = models.ForeignKey(DateTimePK, models.SET_NULL, null=True)
    filterable = models.Boolean

ef __str__(self):
        return self.name

class DateTimePK(models.Model):
    date = models.DateTimeField(primary_key=True, default=datetime.datetime.now)

    class Meta:
        ordering = ["date"]

class ExtraInfo(models.M


ngo.db import connections
from django.db.models.sql.compiler import cursor_iter
from django.test import TestCase

from .models import Article

class QuerySetIteratorTests(TestCase):
    itersize_index_in_mock_args = 3

    @classmethod
    def setUpTestData(cls):
        Article.objects.create(name="Article 1", created=datetime.datetime.now())
        Article.objects.create(name="Article 2", created=datetime.datetime.now())

    def test_iterator_invalid_chunk_size(self):
        for size in (0, -1):

e=size)

    def test_default_iterator_chunk_size(self):
        qs = Article.objects.iterator()
        with mock.patch(
            "django.db.models.sql.compiler.cursor_iter", side_effect=cursor_iter
        ) as cursor_iter_mock:
            next(qs)

       with self.subTest(size=size):
                with self.assertRaisesMessage(
                    ValueError, "Chunk size must be strictly positive."
                ):
                    Article.objects.iterator(chunk_siz


Variance
from django.db.utils import ConnectionHandler
from django.test import SimpleTestCase, TestCase, TransactionTestCase, override_settings
from django.test.utils import CaptureQueriesContext, isolate_apps

from ..models import Item, Object, Square

@unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests")
class Tests(TestCase):
    longMessage = True

    def test_aggregation(self):
        """Raise NotSupportedError when aggregating on date/time fields."""
        for aggregate in (Sum, Avg

Message(NotSupportedError, msg):
                Item.objects.aggregate(aggregate("time"))
            with self.assertRaisesMessage(NotSupportedError, msg):
                Item.objects.aggregate(aggregate("date"))
            with self.assertRaisesMessag

, Variance, StdDev):
            msg = (
                f"SQLite does not support {aggregate.__name__} on date or "
                "time fields, because they are stored as text."
            )
            with self.assertRaises


       await self.bacon.tags.acreate(tag="orange")
        self.assertEqual(await self.bacon.tags.acount(), 3)

    def test_generic_update_or_create_when_created(self):
        """
        Should be able to use update_or_create from the generic related manager
        to create a tag. Refs #23611.
        """
        count = self.bacon.tags.count()
        tag, created = self.bacon.tags.update_or_create(tag="stinky")
        self.assertTrue(created)
        self.assertEqual(count + 1, self.bacon.tags.count

ist create
            # a "juicy" tag.
            create_defaults={"tag": "juicy"},
            defaults={"tag": "uncured"},
            tag="stinky",
        )
        self.assertEqual(tag.tag, "juicy")
        self.assertIs(created, True)
        self.

())

    def test_generic_update_or_create_when_created_with_create_defaults(self):
        count = self.bacon.tags.count()
        tag, created = self.bacon.tags.update_or_create(
            # Since, the "stinky" tag doesn't ex


 SimpleTestCase
from django.test.client import FakePayload

TOO_MANY_FIELDS_MSG = (
    "The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS."
)
TOO_MANY_FILES_MSG = (
    "The number of files exceeded settings.DATA_UPLOAD_MAX_NUMBER_FILES."
)
TOO_MUCH_DATA_MSG = "Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE."

class DataUploadMaxMemorySizeFormPostTests(SimpleTestCase):
    def setUp(self):
        payload = FakePayload("a=1&a=2&a=3\r\n")
        self.request = W

       }
        )

    def test_size_exceeded(self):
        with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=12):
            with self.assertRaisesMessage(RequestDataTooBig, TOO_MUCH_DATA_MSG):
                self.request._load_post_and_files()

    def

SGIRequest(
            {
                "REQUEST_METHOD": "POST",
                "CONTENT_TYPE": "application/x-www-form-urlencoded",
                "CONTENT_LENGTH": len(payload),
                "wsgi.input": payload,


m django.db import models

class Book(models.Model):
    title = models.CharField(max_length=50)
    author = models.CharField(max_length=50)
    pages = models.IntegerField(db_column="page_count")
    shortcut = models.CharField(max_length=50, db_tablespace="idx_tbls")
    isbn = models.CharField(max_length=50, db_tablespace="idx_tbls")
    barcode = models.CharField(max_length=31)

    class Meta:
        indexes = [
            models.Index(fields=["title"]),
            models.Index(fields=["isbn", "id

 models.CharField(max_length=3)

    class Meta:
        abstract = True
        indexes = [
            models.Index(fields=["name"]),
            models.Index(fields=["shortcut"], name="%(app_label)s_%(class)s_idx"),
        ]

class ChildModel1(Abstrac

"]),
            models.Index(
                fields=["barcode"], name="%(app_label)s_%(class)s_barcode_idx"
            ),
        ]

class AbstractModel(models.Model):
    name = models.CharField(max_length=50)
    shortcut =


rt (
    CompetingTeam,
    Event,
    Group,
    IndividualCompetitor,
    Membership,
    Person,
)

class MultiTableTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.alice = Person.objects.create(name="Alice")
        cls.bob = Person.objects.create(name="Bob")
        cls.chris = Person.objects.create(name="Chris")
        cls.dan = Person.objects.create(name="Dan")
        cls.team_alpha = Group.objects.create(name="Alpha")
        Membership.objects.create(person=cls.alice, gr

.chris)
        IndividualCompetitor.objects.create(event=cls.event, person=cls.dan)
        CompetingTeam.objects.create(event=cls.event, team=cls.team_alpha)

    def test_m2m_query(self):
        result = self.event.teams.all()
        self.assertCountE

oup=cls.team_alpha)
        Membership.objects.create(person=cls.bob, group=cls.team_alpha)
        cls.event = Event.objects.create(name="Exposition Match")
        IndividualCompetitor.objects.create(event=cls.event, person=cls


 TestCase

from .models import Person

class PropertyTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.a = Person.objects.create(first_name="John", last_name="Lennon")

    def test_getter(self):
        self.assertEqual(self.a.full_name, "John Lennon")

    def test_setter(self):
        # The "full_name" property hasn't provided a "set" method.
        with self.assertRaises(AttributeError):
            setattr(self.a, "full_name", "Paul McCartney")

        # And cannot be used t

es(AttributeError):
            Person(full_name="Paul McCartney")

        # But "full_name_2" has, and it can be used to initialize the class.
        a2 = Person(full_name_2="Paul McCartney")
        a2.save()
        self.assertEqual(a2.first_name, "Pa

o initialize the class.
        with self.assertRais


    Exact,
    IntegerFieldExact,
    IntegerLessThanOrEqual,
    IsNull,
)
from django.db.models.sql.where import NothingNode
from django.test import SimpleTestCase, TestCase

from .models import Tag

class QTests(SimpleTestCase):
    def test_combine_and_empty(self):
        q = Q(x=1)
        self.assertEqual(q & Q(), q)
        self.assertEqual(Q() & q, q)

        q = Q(x__in={}.keys())
        self.assertEqual(q & Q(), q)
        self.assertEqual(Q() & q, q)

    def test_combine_and_both_empty(self)

l(q | Q(), q)
        self.assertEqual(Q() | q, q)

    def test_combine_xor_empty(self):
        q = Q(x=1)
        self.assertEqual(q ^ Q(), q)
        self.assertEqual(Q() ^ q, q)

        q = Q(x__in={}.keys())
        self.assertEqual(q ^ Q(), q)

:
        self.assertEqual(Q() & Q(), Q())

    def test_combine_or_empty(self):
        q = Q(x=1)
        self.assertEqual(q | Q(), q)
        self.assertEqual(Q() | q, q)

        q = Q(x__in={}.keys())
        self.assertEqua


rt DumbCategory, NamedCategory, ProxyCategory

class ContainsTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.category = DumbCategory.objects.create()
        cls.proxy_category = ProxyCategory.objects.create()

    def test_unsaved_obj(self):
        msg = "QuerySet.contains() cannot be used on unsaved objects."
        with self.assertRaisesMessage(ValueError, msg):
            DumbCategory.objects.contains(DumbCategory())

    def test_obj_type(self):
        msg = "'obj' must b

_list()."
        with self.assertRaisesMessage(TypeError, msg):
            DumbCategory.objects.values_list("pk").contains(self.category)
        with self.assertRaisesMessage(TypeError, msg):
            DumbCategory.objects.values("pk").contains(self.c

e a model instance."
        with self.assertRaisesMessage(TypeError, msg):
            DumbCategory.objects.contains(object())

    def test_values(self):
        msg = "Cannot call QuerySet.contains() after .values() or .values


pUnlessDBFeature
from django.utils.deprecation import RemovedInDjango70Warning

from .models import Company, Employee, JSONFieldModel

class ValuesExpressionsTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        Company.objects.create(
            name="Example Inc.",
            num_employees=2300,
            num_chairs=5,
            ceo=Employee.objects.create(firstname="Joe", lastname="Smith", salary=10),
        )
        Company.objects.create(
            name="Foobar Ltd.",

oyees=32,
            num_chairs=1,
            ceo=Employee.objects.create(
                firstname="Max", lastname="Mustermann", salary=30
            ),
        )

    def test_values_expression(self):
        self.assertSequenceEqual(
            Com

     num_employees=3,
            num_chairs=4,
            ceo=Employee.objects.create(firstname="Frank", lastname="Meyer", salary=20),
        )
        Company.objects.create(
            name="Test GmbH",
            num_empl


ontrib.flatpages.models import FlatPage
from django.contrib.sites.models import Site
from django.test import TestCase, modify_settings, override_settings
from django.utils import translation

@modify_settings(INSTALLED_APPS={"append": ["django.contrib.flatpages"]})
class FlatpageAdminFormTests(TestCase):
    def setUp(self):
        # Site fields cache needs to be cleared after flatpages is added to
        # INSTALLED_APPS
        Site._meta._expire_cache()
        self.form_data = {
            "title":

 self.assertTrue(
            FlatpageForm(data=dict(url="/new_flatpage/", **self.form_data)).is_valid()
        )
        self.assertTrue(
            FlatpageForm(
                data=dict(url="/some.special~chars/", **self.form_data)
            ).is_v

"A test page",
            "content": "This is a test",
            "sites": [settings.SITE_ID],
        }

    def test_flatpage_admin_form_url_validation(self):
        "The flatpage admin form correctly validates urls"


ase, modify_settings, override_settings

from .settings import FLATPAGES_TEMPLATES

class TestDataMixin:
    @classmethod
    def setUpTestData(cls):
        cls.site1 = Site.objects.get()
        cls.fp1 = FlatPage.objects.create(
            url="/flatpage/",
            title="A Flatpage",
            content="Isn't it flat!",
            enable_comments=False,
            template_name="",
            registration_required=False,
        )
        cls.fp2 = FlatPage.objects.create(
            url="/lo

cls.fp3 = FlatPage.objects.create(
            url="/sekrit/",
            title="Sekrit Flatpage",
            content="Isn't it sekrit!",
            enable_comments=False,
            template_name="",
            registration_required=True,
        )

cation/flatpage/",
            title="A Nested Flatpage",
            content="Isn't it flat and deep!",
            enable_comments=False,
            template_name="",
            registration_required=False,
        )


contrib.flatpages.models import FlatPage
from django.test import SimpleTestCase, override_settings
from django.test.utils import override_script_prefix

class FlatpageModelTests(SimpleTestCase):
    def setUp(self):
        self.page = FlatPage(title="Café!", url="/café/")

    def test_get_absolute_url_urlencodes(self):
        self.assertEqual(self.page.get_absolute_url(), "/caf%C3%A9/")

    @override_script_prefix("/prefix/")
    def test_get_absolute_url_honors_script_prefix(self):
        self.assert

_url_include(self):
        self.assertEqual(self.page.get_absolute_url(), "/flatpage_root/caf%C3%A9/")

    @override_settings(ROOT_URLCONF="flatpages_tests.no_slash_urls")
    def test_get_absolute_url_include_no_slash(self):
        self.assertEqual(sel

Equal(self.page.get_absolute_url(), "/prefix/caf%C3%A9/")

    def test_str(self):
        self.assertEqual(str(self.page), "/café/ -- Café!")

    @override_settings(ROOT_URLCONF="flatpages_tests.urls")
    def test_get_absolute


apps import apps
from django.contrib.sites.models import Site
from django.test import TestCase
from django.test.utils import modify_settings, override_settings

@override_settings(ROOT_URLCONF="flatpages_tests.urls")
@modify_settings(
    INSTALLED_APPS={
        "append": ["django.contrib.sitemaps", "django.contrib.flatpages"],
    },
)
class FlatpagesSitemapTests(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        # This cleanup is necessary because contrib.sites cac

urrent()
        current_site.flatpage_set.create(url="/foo/", title="foo")
        current_site.flatpage_set.create(
            url="/private-foo/", title="private foo", registration_required=True
        )

    def test_flatpage_sitemap(self):
        r

he
        # makes tests interfere with each other, see #11505
        Site.objects.clear_cache()

    @classmethod
    def setUpTestData(cls):
        Site = apps.get_model("sites.Site")
        current_site = Site.objects.get_c


TemplateSyntaxError
from django.test import TestCase

class FlatpageTemplateTagTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.site1 = Site.objects.get()
        cls.fp1 = FlatPage.objects.create(
            url="/flatpage/",
            title="A Flatpage",
            content="Isn't it flat!",
            enable_comments=False,
            template_name="",
            registration_required=False,
        )
        cls.fp2 = FlatPage.objects.create(
            url="/location/fl

 FlatPage.objects.create(
            url="/sekrit/",
            title="Sekrit Flatpage",
            content="Isn't it sekrit!",
            enable_comments=False,
            template_name="",
            registration_required=True,
        )
        cl

atpage/",
            title="A Nested Flatpage",
            content="Isn't it flat and deep!",
            enable_comments=False,
            template_name="",
            registration_required=False,
        )
        cls.fp3 =


import call_command
from django.template import Context, Template
from django.test import SimpleTestCase, override_settings

from .settings import TEST_SETTINGS

class BaseStaticFilesMixin:
    """
    Test case with a couple utility assertions.
    """

    def assertFileContains(self, filepath, text):
        self.assertIn(
            text,
            self._get_file(filepath),
            "'%s' not in '%s'" % (text, filepath),
        )

    def assertFileNotFound(self, filepath):
        with self.ass

*kwargs)).strip()

    def static_template_snippet(self, path, asvar=False):
        if asvar:
            return (
                "{%% load static from static %%}{%% static '%s' as var %%}{{ var }}"
                % path
            )
        return "{%

ertRaises(OSError):
            self._get_file(filepath)

    def render_template(self, template, **kwargs):
        if isinstance(template, str):
            template = Template(template)
        return template.render(Context(*


ort os.path
from pathlib import Path

TEST_ROOT = os.path.dirname(__file__)

TEST_SETTINGS = {
    "MEDIA_URL": "media/",
    "STATIC_URL": "static/",
    "MEDIA_ROOT": os.path.join(TEST_ROOT, "project", "site_media", "media"),
    "STATIC_ROOT": os.path.join(TEST_ROOT, "project", "site_media", "static"),
    "STATICFILES_DIRS": [
        os.path.join(TEST_ROOT, "project", "documents"),
        ("prefix", os.path.join(TEST_ROOT, "project", "prefixed")),
        Path(TEST_ROOT) / "project" / "pathlib",
    ]

   ],
    "INSTALLED_APPS": [
        "django.contrib.staticfiles",
        "staticfiles_tests",
        "staticfiles_tests.apps.test",
        "staticfiles_tests.apps.no_label",
    ],
    # In particular, AuthenticationMiddleware can't be used because

,
    "STATICFILES_FINDERS": [
        "django.contrib.staticfiles.finders.FileSystemFinder",
        "django.contrib.staticfiles.finders.AppDirectoriesFinder",
        "django.contrib.staticfiles.finders.DefaultStorageFinder",


elta

from django.conf import settings
from django.contrib.staticfiles.storage import ManifestStaticFilesStorage
from django.core.files import storage

class DummyStorage(storage.Storage):
    """
    A storage class that implements get_modified_time() but raises
    NotImplementedError for path().
    """

    def _save(self, name, content):
        return "dummy"

    def delete(self, name):
        pass

    def exists(self, name):
        pass

    def get_modified_time(self, name):
        return date

def exists(self, name):
        return os.path.exists(self._path(name))

    def listdir(self, path):
        path = self._path(path)
        directories, files = [], []
        with os.scandir(path) as entries:
            for entry in entries:

time(1970, 1, 1, tzinfo=UTC)

class PathNotImplementedStorage(storage.Storage):
    def _save(self, name, content):
        return "dummy"

    def _path(self, name):
        return os.path.join(settings.STATIC_ROOT, name)


eck_storages
from django.contrib.staticfiles.finders import BaseFinder, get_finder
from django.core.checks import Error, Warning
from django.test import SimpleTestCase, override_settings

from .cases import CollectionTestCase
from .settings import TEST_ROOT

class FindersCheckTests(CollectionTestCase):
    run_collectstatic_in_setUp = False

    def test_base_finder_check_not_implemented(self):
        finder = BaseFinder()
        msg = (
            "subclasses may provide a check() method to verify the

errors."""
        error1 = Error("1")
        error2 = Error("2")
        error3 = Error("3")

        def get_finders():
            class Finder1(BaseFinder):
                def check(self, **kwargs):
                    return [error1]

            cl

finder is "
            "configured correctly."
        )
        with self.assertRaisesMessage(NotImplementedError, msg):
            finder.check()

    def test_check_finders(self):
        """check_finders() concatenates all


om django.core.exceptions import ImproperlyConfigured
from django.test import SimpleTestCase, override_settings

from .cases import StaticFilesTestCase
from .settings import TEST_ROOT

class TestFinders:
    """
    Base finder test mixin.

    On Windows, sometimes the case of the path we ask the finders for and the
    path(s) they find can differ. Compare them using os.path.normcase() to
    avoid false negatives.
    """

    def test_find_first(self):
        src, dst = self.find_first
        found =

os.path.normcase(f) for f in found]
        dst = [os.path.normcase(d) for d in dst]
        self.assertEqual(found, dst)

class TestFileSystemFinder(TestFinders, StaticFilesTestCase):
    """
    Test FileSystemFinder.
    """

    def setUp(self):

 self.finder.find(src)
        self.assertEqual(os.path.normcase(found), os.path.normcase(dst))

    def test_find_all(self):
        src, dst = self.find_all
        found = self.finder.find(src, find_all=True)
        found = [


urljoin

from django.conf import STATICFILES_STORAGE_ALIAS
from django.contrib.staticfiles import storage
from django.forms import Media
from django.templatetags.static import static
from django.test import SimpleTestCase, override_settings

class StaticTestStorage(storage.StaticFilesStorage):
    def url(self, name):
        return urljoin("https://example.com/assets/", name)

@override_settings(
    INSTALLED_APPS=("django.contrib.staticfiles",),
    STORAGES={
        STATICFILES_STORAGE_ALIAS: {

olute_url(self):
        m = Media(
            css={"all": ("path/to/css1", "/path/to/css2")},
            js=(
                "/path/to/js1",
                "http://media.other.com/path/to/js2",
                "https://secure.other.com/path/to/js3",

       "BACKEND": "staticfiles_tests.test_forms.StaticTestStorage",
            "OPTIONS": {"location": "http://media.example.com/static/"},
        }
    },
)
class StaticFilesFormsMediaTestCase(SimpleTestCase):
    def test_abs


cfiles.handlers import ASGIStaticFilesHandler
from django.core.handlers.asgi import ASGIHandler
from django.test import AsyncRequestFactory

from .cases import StaticFilesTestCase

class MockApplication:
    """ASGI application that returns a string indicating that it was called."""

    async def __call__(self, scope, receive, send):
        return "Application called"

class TestASGIStaticFilesHandler(StaticFilesTestCase):
    async_request_factory = AsyncRequestFactory()

    async def test_get_async_r

)
        self.assertEqual(response.status_code, 200)

    async def test_get_async_response_not_found(self):
        request = self.async_request_factory.get("/static/test/not-found.txt")
        handler = ASGIStaticFilesHandler(ASGIHandler())
        res

esponse(self):
        request = self.async_request_factory.get("/static/test/file.txt")
        handler = ASGIStaticFilesHandler(ASGIHandler())
        response = await handler.get_response_async(request)
        response.close(


ercising
django.contrib.staticfiles.testing.StaticLiveServerTestCase instead of
django.test.LiveServerTestCase.
"""

import os
from urllib.request import urlopen

from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.core.exceptions import ImproperlyConfigured
from django.test import modify_settings, override_settings

TEST_ROOT = os.path.dirname(__file__)
TEST_SETTINGS = {
    "MEDIA_URL": "media/",
    "STATIC_URL": "static/",
    "MEDIA_ROOT": os.path.join(TEST_ROOT, "projec

     cls.enterClassContext(override_settings(**TEST_SETTINGS))
        super().setUpClass()

class StaticLiveServerChecks(LiveServerBase):
    @classmethod
    def setUpClass(cls):
        # If contrib.staticfiles isn't configured properly, the exception

t", "site_media", "media"),
    "STATIC_ROOT": os.path.join(TEST_ROOT, "project", "site_media", "static"),
}

class LiveServerBase(StaticLiveServerTestCase):
    available_apps = []

    @classmethod
    def setUpClass(cls):


e, TestDefaults
from .settings import TEST_ROOT, TEST_SETTINGS
from .storage import DummyStorage

class TestNoFilesCreated:
    def test_no_files_created(self):
        """
        Make sure no files were create in the destination directory.
        """
        self.assertEqual(os.listdir(settings.STATIC_ROOT), [])

class TestRunserver(StaticFilesTestCase):
    @override_settings(MIDDLEWARE=["django.middleware.common.CommonMiddleware"])
    def test_middleware_loaded_only_once(self):
        command = run

    def test_404_response(self):
        command = runserver.Command()
        handler = command.get_handler(use_static_handler=True, insecure_serving=True)
        missing_static_file = os.path.join(settings.STATIC_URL, "unknown.css")
        req = Reques

server.Command()
        with mock.patch("django.middleware.common.CommonMiddleware") as mocked:
            command.get_handler(use_static_handler=True, insecure_serving=True)
            self.assertEqual(mocked.call_count, 1)


ticRenders("path/", "/static/path/")
        self.assertStaticRenders("path/?query", "/static/path/?query")
        self.assertPostCondition()

    def test_template_tag_simple_content(self):
        relpath = self.hashed_file_path("cached/styles.css")
        self.assertEqual(relpath, "cached/styles.5e0040571e1a.css")
        with storage.staticfiles_storage.open(relpath) as relfile:
            content = relfile.read()
            self.assertNotIn(b"cached/other.css", content)
            self.assertIn(b"

ored.0e15ac4a4fb4.css")
        with storage.staticfiles_storage.open(relpath) as relfile:
            content = relfile.read()
            self.assertIn(b"#foobar", content)
            self.assertIn(b"http:foobar", content)
            self.assertIn(b"ht

other.d41d8cd98f00.css", content)
        self.assertPostCondition()

    def test_path_ignored_completely(self):
        relpath = self.hashed_file_path("cached/css/ignored.css")
        self.assertEqual(relpath, "cached/css/ign


m django.conf import STATICFILES_STORAGE_ALIAS
from django.test import override_settings

from .cases import StaticFilesTestCase

class TestTemplateTag(StaticFilesTestCase):
    def test_template_tag(self):
        self.assertStaticRenders("does/not/exist.png", "/static/does/not/exist.png")
        self.assertStaticRenders("testfile.txt", "/static/testfile.txt")
        self.assertStaticRenders(
            "special?chars&quoted.html", "/static/special%3Fchars%26quoted.html"
        )

    @override_settin

 Storage.url() should return an encoded path and might be overridden
        to also include a querystring. {% static %} escapes the URL to avoid
        raw '&', for example.
        """
        self.assertStaticRenders("a.html", "a.html?a=b&c=d")

gs(
        STORAGES={
            STATICFILES_STORAGE_ALIAS: {
                "BACKEND": "staticfiles_tests.storage.QueryStringStorage"
            },
        }
    )
    def test_template_tag_escapes(self):
        """


django.contrib.sites.models import Site
from django.test import Client, TestCase, modify_settings, override_settings

from .settings import FLATPAGES_TEMPLATES

@modify_settings(INSTALLED_APPS={"append": "django.contrib.flatpages"})
@override_settings(
    LOGIN_URL="/accounts/login/",
    MIDDLEWARE=[
        "django.middleware.common.CommonMiddleware",
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
        "django.contrib.auth.middlewa

URE_VIEW="django.views.csrf.csrf_failure",
    TEMPLATES=FLATPAGES_TEMPLATES,
)
class FlatpageCSRFTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.site1 = Site.objects.get()
        cls.fp1 = FlatPage.objects.create(
            ur

re.AuthenticationMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
        "django.contrib.flatpages.middleware.FlatpageFallbackMiddleware",
    ],
    ROOT_URLCONF="flatpages_tests.urls",
    CSRF_FAIL


Case
from django.test.utils import isolate_apps

from .models import ManyToMany

class ManyToManyFieldTests(SimpleTestCase):
    def test_abstract_model_pending_operations(self):
        """
        Many-to-many fields declared on abstract models should not add lazy
        relations to resolve relationship declared as string (#24215).
        """
        pending_ops_before = list(apps._pending_operations.items())

        class AbstractManyToManyModel(models.Model):
            fk = models.ForeignKey("mis

pending_operations.items()),
            "Pending lookup added for a many-to-many field on an abstract model",
        )

    @isolate_apps("model_fields", "model_fields.tests")
    def test_abstract_model_app_relative_foreign_key(self):
        class Abst

sing.FK", models.CASCADE)

            class Meta:
                abstract = True

        self.assertIs(AbstractManyToManyModel._meta.apps, apps)
        self.assertEqual(
            pending_ops_before,
            list(apps._


from django.db import models
from django.test import SimpleTestCase, TestCase

from .models import Post

class TextFieldTests(TestCase):
    def test_max_length_passed_to_formfield(self):
        """
        TextField passes its max_length attribute to form fields created using
        their formfield() method.
        """
        tf1 = models.TextField()
        tf2 = models.TextField(max_length=2345)
        self.assertIsNone(tf1.formfield().max_length)
        self.assertEqual(2345, tf2.formfield().max_

widget, forms.Select)

    def test_to_python(self):
        """TextField.to_python() should return a string."""
        f = models.TextField()
        self.assertEqual(f.to_python(1), "1")

    def test_lookup_integer_in_textfield(self):
        self.asse

length)

    def test_choices_generates_select_widget(self):
        """A TextField with choices uses a Select widget."""
        f = models.TextField(choices=[("A", "A"), ("B", "B")])
        self.assertIsInstance(f.formfield().


field = models.Field(choices=choices)
        form_field = model_field.formfield(show_hidden_initial=True)
        self.assertTrue(form_field.show_hidden_initial)

        form_field = model_field.formfield(show_hidden_initial=False)
        self.assertFalse(form_field.show_hidden_initial)

    def test_field_repr(self):
        """
        __repr__() of a field displays its name.
        """
        f = Foo._meta.get_field("a")
        self.assertEqual(repr(f), "<django.db.models.fields.CharField: a>")

assertEqual(repr(Nested.Field()), "<model_fields.tests.Nested.Field>")

    def test_field_name(self):
        """
        A defined field name (name="fieldname") is used instead of the model
        model's attribute name (modelname).
        """

     f = models.fields.CharField()
        self.assertEqual(repr(f), "<django.db.models.fields.CharField>")

    def test_field_repr_nested(self):
        """__repr__() uses __qualname__ for nested class support."""
        self.


ngo.test import TestCase

from .models import PersonWithCustomMaxLengths, PersonWithDefaultMaxLengths

class MaxLengthArgumentsTests(unittest.TestCase):
    def verify_max_length(self, model, field, length):
        self.assertEqual(model._meta.get_field(field).max_length, length)

    def test_default_max_lengths(self):
        self.verify_max_length(PersonWithDefaultMaxLengths, "email", 254)
        self.verify_max_length(PersonWithDefaultMaxLengths, "vcard", 100)
        self.verify_max_length(PersonWit

    self.verify_max_length(PersonWithCustomMaxLengths, "vcard", 250)
        self.verify_max_length(PersonWithCustomMaxLengths, "homepage", 250)
        self.verify_max_length(PersonWithCustomMaxLengths, "avatar", 250)

class MaxLengthORMTests(TestCase):

hDefaultMaxLengths, "homepage", 200)
        self.verify_max_length(PersonWithDefaultMaxLengths, "avatar", 100)

    def test_custom_max_lengths(self):
        self.verify_max_length(PersonWithCustomMaxLengths, "email", 250)


models import Permission
from django.contrib.contenttypes.models import ContentType
from django.core import management
from django.test import TestCase, override_settings

from .models import Article

class SwappableModelTests(TestCase):
    # Limit memory usage when calling 'migrate'.
    available_apps = [
        "swappable_models",
        "django.contrib.auth",
        "django.contrib.contenttypes",
    ]

    @override_settings(TEST_ARTICLE_MODEL="swappable_models.AlternateArticle")
    def test_gene

e()
        ContentType.objects.filter(app_label="swappable_models").delete()

        # Re-run migrate. This will re-build the permissions and content types.
        management.call_command("migrate", interactive=False, verbosity=0)

        # Content typ

rated_data(self):
        "Permissions and content types are not created for a swapped model"

        # Delete all permissions and content_types
        Permission.objects.filter(content_type__app_label="swappable_models").delet


ger(models.Model):
    name = models.CharField(max_length=50)
    secretary = models.ForeignKey(
        "Employee", models.CASCADE, null=True, related_name="managers"
    )

class Employee(models.Model):
    firstname = models.CharField(max_length=50)
    lastname = models.CharField(max_length=50)
    salary = models.IntegerField(blank=True, null=True)
    manager = models.ForeignKey(Manager, models.CASCADE, null=True)
    based_in_eu = models.BooleanField(default=False)

    def __str__(self):
        re

sitiveIntegerField()
    num_chairs = models.PositiveIntegerField()
    ceo = models.ForeignKey(
        Employee,
        models.CASCADE,
        related_name="company_ceo_set",
    )
    point_of_contact = models.ForeignKey(
        Employee,
        mod

turn "%s %s" % (self.firstname, self.lastname)

class RemoteEmployee(Employee):
    adjusted_salary = models.IntegerField()

class Company(models.Model):
    name = models.CharField(max_length=100)
    num_employees = models.Po


from django.tasks import TaskContext, task

@task()
def noop_task(*args, **kwargs):
    return None

@task
def noop_task_from_bare_decorator(*args, **kwargs):
    return None

@task()
async def noop_task_async(*args, **kwargs):
    return None

@task()
def calculate_meaning_of_life():
    return 42

@task()
def failing_task_value_error():
    raise ValueError("This Task failed due to ValueError")

@task()
def failing_task_system_exit():
    raise SystemExit("This Task failed due to SystemExit")

@ta

turn_value():
    # Return something which isn't JSON serializable nor picklable.
    return lambda: True

@task()
def exit_task():
    exit(1)

@task()
def hang():
    """
    Do nothing for 5 minutes
    """
    time.sleep(300)

@task()
def sleep_for(

sk()
def failing_task_keyboard_interrupt():
    raise KeyboardInterrupt("This Task failed due to KeyboardInterrupt")

@task()
def complex_exception():
    raise ValueError(ValueError("This task failed"))

@task()
def complex_re


ask, default_task_backend, task, task_backends
from django.tasks.backends.base import BaseTaskBackend
from django.tasks.exceptions import InvalidTask
from django.test import SimpleTestCase, override_settings

from . import tasks as test_tasks

class CustomBackend(BaseTaskBackend):
    def __init__(self, alias, params):
        super().__init__(alias, params)
        self.prefix = self.options.get("prefix", "")

    def enqueue(self, *args, **kwargs):
        logger = logging.getLogger(__name__)
        log

Backend(BaseTaskBackend):
    task_class = CustomTask
    supports_priority = True

    def enqueue(self, task, args, kwargs):
        pass

@override_settings(
    TASKS={
        "default": {
            "BACKEND": f"{CustomBackend.__module__}.{CustomBa

ger.info(f"{self.prefix}Task enqueued.")

class CustomBackendNoEnqueue(BaseTaskBackend):
    pass

@dataclass(frozen=True, slots=True, kw_only=True)
class CustomTask(Task):
    foo: int = 3
    bar: int = 300

class CustomTask


   "default": {
            "BACKEND": "django.tasks.backends.immediate.ImmediateBackend",
            "QUEUES": [],
        }
    }
)
class ImmediateBackendTestCase(SimpleTestCase):
    def test_using_correct_backend(self):
        self.assertEqual(default_task_backend, task_backends["default"])
        self.assertIsInstance(task_backends["default"], ImmediateBackend)
        self.assertEqual(default_task_backend.alias, "default")
        self.assertEqual(default_task_backend.options, {})

    def test_enq

sultStatus.SUCCESSFUL)
                self.assertIs(result.is_finished, True)
                self.assertIsNotNone(result.started_at)
                self.assertIsNotNone(result.last_attempted_at)
                self.assertIsNotNone(result.finished_at)

ueue_task(self):
        for task in [test_tasks.noop_task, test_tasks.noop_task_async]:
            with self.subTest(task):
                result = task.enqueue(1, two=3)

                self.assertEqual(result.status, TaskRe


tions import (
    InvalidTask,
    InvalidTaskBackend,
    TaskResultDoesNotExist,
    TaskResultMismatch,
)
from django.test import SimpleTestCase, override_settings
from django.utils import timezone
from django.utils.module_loading import import_string

from . import tasks as test_tasks

@override_settings(
    TASKS={
        "default": {
            "BACKEND": "django.tasks.backends.dummy.DummyBackend",
            "QUEUES": ["default", "queue_1"],
        },
        "immediate": {
            "BACKEN

     default_task_backend.clear()

    def test_using_correct_backend(self):
        self.assertEqual(default_task_backend, task_backends["default"])
        self.assertIsInstance(task_backends["default"], DummyBackend)

    def test_task_decorator(self):

D": "django.tasks.backends.immediate.ImmediateBackend",
            "QUEUES": [],
        },
        "missing": {"BACKEND": "does.not.exist"},
    },
    USE_TZ=True,
)
class TaskTestCase(SimpleTestCase):
    def setUp(self):


AULT_DB_ALIAS

class TestRouter:
    """
    Vaguely behave like primary/replica, but the databases aren't assumed to
    propagate changes.
    """

    def db_for_read(self, model, instance=None, **hints):
        if instance:
            return instance._state.db or "other"
        return "other"

    def db_for_write(self, model, **hints):
        return DEFAULT_DB_ALIAS

    def allow_relation(self, obj1, obj2, **hints):
        return obj1._state.db in ("default", "other") and obj2._state.db in (

n.
    """

    def db_for_read(self, model, **hints):
        "Point all read operations on auth models to 'default'"
        if model._meta.app_label == "auth":
            # We use default here to ensure we can tell the difference
            # between

         "default",
            "other",
        )

    def allow_migrate(self, db, app_label, **hints):
        return True

class AuthRouter:
    """
    Control all database operations on models in the contrib.auth applicatio