 uuid

from django.core.exceptions import ValidationError
from django.forms import UUIDField
from django.test import SimpleTestCase

class UUIDFieldTest(SimpleTestCase):
    def test_uuidfield_1(self):
        field = UUIDField()
        value = field.clean("550e8400e29b41d4a716446655440000")
        self.assertEqual(value, uuid.UUID("550e8400e29b41d4a716446655440000"))

    def test_clean_value_with_dashes(self):
        field = UUIDField()
        value = field.clean("550e8400-e29b-41d4-a716-446655440000

ld.clean(None))

    def test_uuidfield_3(self):
        field = UUIDField()
        with self.assertRaisesMessage(ValidationError, "Enter a valid UUID."):
            field.clean("550e8400")

    def test_uuidfield_4(self):
        field = UUIDField()

")
        self.assertEqual(value, uuid.UUID("550e8400e29b41d4a716446655440000"))

    def test_uuidfield_2(self):
        field = UUIDField(required=False)
        self.assertIsNone(field.clean(""))
        self.assertIsNone(fie


irst_name" aria-describedby="id_first_name_error">
'
            '
Last name:'
            '

This field is required.'
            '

<input type="text" name="last_name" aria-invalid="true" '
            'required id="id_last_name" aria-describedby="id_last_name_error">
'
            '
Birthday:'
            '

This field

p.as_table(),
            """
First name:

This field is required.

<input type="text" name="first_name" id="id_first_name" aria-invalid="true"

is required.'
            '

<input type="text" name="birthday" aria-invalid="true" required '
            'id="id_birthday" aria-describedby="id_birthday_error">
',
        )
        self.assertHTMLEqual(


,
)
from django.test import SimpleTestCase
from django.utils import translation
from django.utils.translation import gettext_lazy

from . import jinja2_tests

class FormsI18nTests(SimpleTestCase):
    def test_lazy_labels(self):
        class SomeForm(Form):
            username = CharField(max_length=10, label=gettext_lazy("username"))

        f = SomeForm()
        self.assertHTMLEqual(
            f.as_p(),
            '
username:'
            '<input id="id_username"

self.assertHTMLEqual(
                f.as_p(),
                '
Benutzername:'
                '<input id="id_username" type="text" name="username" maxlength="10" '
                "required>
",

 type="text" name="username" maxlength="10" '
            "required></p>",
        )

        # Translations are done at rendering time, so multi-lingual apps can
        # define forms.
        with translation.override("de"):


port unittest

from django.forms.renderers import (
    BaseRenderer,
    DjangoTemplates,
    Jinja2,
    TemplatesSetting,
)
from django.test import SimpleTestCase

try:
    import jinja2
except ImportError:
    jinja2 = None

class SharedTests:
    expected_widget_dir = "templates"

    def test_installed_apps_template_found(self):
        """Can find a custom template in INSTALLED_APPS."""
        renderer = self.renderer()
        # Found because forms_tests is .
        tpl = renderer.get_template("f

idget.html",
            )
        )
        self.assertEqual(tpl.origin.name, expected_path)

class BaseTemplateRendererTests(SimpleTestCase):
    def test_get_renderer(self):
        with self.assertRaisesMessage(
            NotImplementedError, "subcl

orms_tests/custom_widget.html")
        expected_path = os.path.abspath(
            os.path.join(
                os.path.dirname(__file__),
                "..",
                self.expected_widget_dir + "/forms_tests/custom_w


settings
from django.urls import reverse

from ..models import Article

@override_settings(ROOT_URLCONF="forms_tests.urls")
class LiveWidgetTests(AdminSeleniumTestCase):
    available_apps = ["forms_tests"] + AdminSeleniumTestCase.available_apps

    def test_textarea_trailing_newlines(self):
        """
        A roundtrip on a ModelForm doesn't alter the TextField value
        """
        from selenium.webdriver.common.by import By

        article = Article.objects.create(content="\nTst\n")
        sel

everse("article_form", args=[article.pk])
        )
        with self.wait_page_loaded():
            self.selenium.find_element(By.ID, "submit").click()
        article = Article.objects.get(pk=article.pk)
        self.assertEqual(article.content, "\r\nTs

f.selenium.get(
            self.live_server_url + r


contrib.gis.db.models import GeometryField
from django.contrib.gis.db.models.sql import AreaField, DistanceField
from django.test import SimpleTestCase

class FieldsTests(SimpleTestCase):
    def test_area_field_deepcopy(self):
        field = AreaField(None)
        self.assertEqual(copy.deepcopy(field), field)

    def test_distance_field_deepcopy(self):
        field = DistanceField(None)
        self.assertEqual(copy.deepcopy(field), field)

class GeometryFieldTests(SimpleTestCase):
    def test_decon

struct_empty(self):
        field = GeometryField()
        *_, kwargs = field.deconstruct()
        self.assertEqual(kwargs, {"srid": 4326})

    def test_deconstruct_values(self):
        field = GeometryField(
            srid


django.test import SimpleTestCase

class DistanceTest(SimpleTestCase):
    "Testing the Distance object"

    def test_init(self):
        "Testing initialization from valid units"
        d = Distance(m=100)
        self.assertEqual(d.m, 100)

        d1, d2, d3 = D(m=100), D(meter=100), D(metre=100)
        for d in (d1, d2, d3):
            self.assertEqual(d.m, 100)

        d = D(nm=100)
        self.assertEqual(d.m, 185200)

        y1, y2, y3 = D(yd=100), D(yard=100), D(Yard=100)
        for d in (y

f test_init_invalid(self):
        "Testing initialization from invalid units"
        with self.assertRaises(AttributeError):
            D(banana=100)

    def test_init_invalid_area_only_units(self):
        with self.assertRaises(AttributeError):

1, y2, y3):
            self.assertEqual(d.yd, 100)

        mm1, mm2 = D(millimeter=1000), D(MiLLiMeTeR=1000)
        for d in (mm1, mm2):
            self.assertEqual(d.m, 1.0)
            self.assertEqual(d.mm, 1000.0)

    de


ort cached_property

test_srs = (
    {
        "srid": 4326,
        "auth_name": ("EPSG", True),
        "auth_srid": 4326,
        # Only the beginning, because there are differences depending on
        # installed libs
        "srtext": 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84"',
        "proj_re": (
            r"\+proj=longlat (\+datum=WGS84 |\+towgs84=0,0,0,0,0,0,0 )\+no_defs ?"
        ),
        "spheroid": "WGS 84",
        "name": "WGS 84",
        "geographic": True,
        "projecte

d": False,
        "spatialite": True,
        # From proj's "cs2cs -le" and Wikipedia (semi-minor only)
        "ellipsoid": (6378137.0, 6356752.3, 298.257223563),
        "eprec": (1, 1, 9),
        "wkt": re.sub(
            r


 ValidationError
from django.forms import TimeField
from django.test import SimpleTestCase

from . import FormFieldAssertionsMixin

class TimeFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
    def test_timefield_1(self):
        f = TimeField()
        self.assertEqual(datetime.time(14, 25), f.clean(datetime.time(14, 25)))
        self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59)))
        self.assertEqual(datetime.time(14, 25), f.clean("14:25"))
        self.assertEqual(d

ime.'"):
            f.clean("1:24 p.m.")

    def test_timefield_2(self):
        f = TimeField(input_formats=["%I:%M %p"])
        self.assertEqual(datetime.time(14, 25), f.clean(datetime.time(14, 25)))
        self.assertEqual(datetime.time(14, 25, 59),

atetime.time(14, 25, 59), f.clean("14:25:59"))
        with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"):
            f.clean("hello")
        with self.assertRaisesMessage(ValidationError, "'Enter a valid t


" required>')

    def test_urlfield_widget_max_min_length(self):
        f = URLField(min_length=15, max_length=20)
        self.assertEqual("http://example.com", f.clean("http://example.com"))
        self.assertWidgetRendersTo(
            f,
            '<input id="id_f" type="url" name="f" maxlength="20" '
            'minlength="15" required>',
        )
        msg = "'Ensure this value has at least 15 characters (it has 12).'"
        with self.assertRaisesMessage(ValidationError, msg):

 test_urlfield_clean(self):
        f = URLField(required=False)
        tests = [
            ("http://localhost", "http://localhost"),
            ("http://example.com", "http://example.com"),
            ("http://example.com/test", "http://example.com/t

f.clean("http://f.com")
        msg = "'Ensure this value has at most 20 characters (it has 37).'"
        with self.assertRaisesMessage(ValidationError, msg):
            f.clean("http://abcdefghijklmnopqrstuvwxyz.com")

    def


hoiceField,
    RegexField,
    SplitDateTimeField,
    TimeField,
    URLField,
    utils,
)
from django.template import Context, Template
from django.test import SimpleTestCase, TestCase
from django.utils.safestring import mark_safe

from ..models import ChoiceModel

class AssertFormErrorsMixin:
    def assertFormErrors(self, expected, the_callable, *args, **kwargs):
        with self.assertRaises(ValidationError) as cm:
            the_callable(*args, **kwargs)
        self.assertEqual(cm.exception.mess

TH %(limit_value)s",
            "max_length": "LENGTH %(show_value)s, MAX LENGTH %(limit_value)s",
        }
        f = CharField(min_length=5, max_length=10, error_messages=e)
        self.assertFormErrors(["REQUIRED"], f.clean, "")
        self.assertF

ages, expected)

class FormsErrorMessagesTestCase(SimpleTestCase, AssertFormErrorsMixin):
    def test_charfield(self):
        e = {
            "required": "REQUIRED",
            "min_length": "LENGTH %(show_value)s, MIN LENG


ss FormsUtilsTestCase(SimpleTestCase):
    # Tests for forms/utils.py module.

    def test_flatatt(self):
        ###########
        # flatatt #
        ###########

        self.assertEqual(flatatt({"id": "header"}), ' id="header"')
        self.assertEqual(
            flatatt({"class": "news", "title": "Read this"}),
            ' class="news" title="Read this"',
        )
        self.assertEqual(
            flatatt({"class": "news", "title": "Read this", "required": "required"}),
            ' class

        self.assertEqual(
            flatatt({"class": "news", "title": "Read this", "required": False}),
            ' class="news" title="Read this"',
        )
        self.assertEqual(flatatt({"class": None}), "")
        self.assertEqual(flatatt({})

="news" required="required" title="Read this"',
        )
        self.assertEqual(
            flatatt({"class": "news", "title": "Read this", "required": True}),
            ' class="news" title="Read this" required',
        )


t GEOSGeometry
from django.test import SimpleTestCase, override_settings

if HAS_GEOIP2:
    import geoip2

    from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception

def build_geoip_path(*parts):
    return pathlib.Path(__file__).parent.joinpath("data/geoip2", *parts).resolve()

@skipUnless(HAS_GEOIP2, "GeoIP2 is required.")
@override_settings(
    GEOIP_CITY="GeoLite2-City-Test.mmdb",
    GEOIP_COUNTRY="GeoLite2-Country-Test.mmdb",
)
class GeoLite2Test(SimpleTestCase):
    fqdn = "sky.uk"
    ip

ected_city = {
        "accuracy_radius": 100,
        "city": "Boxford",
        "continent_code": "EU",
        "continent_name": "Europe",
        "country_code": "GB",
        "country_name": "United Kingdom",
        "is_in_european_union": False,

v4_str = "2.125.160.216"
    ipv6_str = "::ffff:027d:a0d8"
    ipv4_addr = ipaddress.ip_address(ipv4_str)
    ipv6_addr = ipaddress.ip_address(ipv6_str)
    query_values = (fqdn, ipv4_str, ipv6_str, ipv4_addr, ipv6_addr)

    exp


jango.test import SimpleTestCase

class MultipleChoiceFieldTest(SimpleTestCase):
    def test_multiplechoicefield_1(self):
        f = MultipleChoiceField(choices=[("1", "One"), ("2", "Two")])
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean("")
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean(None)
        self.assertEqual(["1"], f.clean([1]))
        self.assertEqual(["1"], f.clean(["1"]))

a list of values.'"):
            f.clean("hello")
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean([])
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):

    self.assertEqual(["1", "2"], f.clean(["1", "2"]))
        self.assertEqual(["1", "2"], f.clean([1, "2"]))
        self.assertEqual(["1", "2"], f.clean((1, "2")))
        with self.assertRaisesMessage(ValidationError, "'Enter


get_blank_choice_label
from django.forms import TypedChoiceField
from django.test import SimpleTestCase

class TypedChoiceFieldTest(SimpleTestCase):
    def test_typedchoicefield_1(self):
        f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
        self.assertEqual(1, f.clean("1"))
        msg = "'Select a valid choice. 2 is not one of the available choices.'"
        with self.assertRaisesMessage(ValidationError, msg):
            f.clean("2")

    def test_typedchoicefield_2(self):

 cause weirdness: be careful (bool(-1) == True,
        # remember)
        f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool)
        self.assertTrue(f.clean("-1"))

    def test_typedchoicefield_4(self):
        # Even more weirdness: if

       # Different coercion, same validation.
        f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float)
        self.assertEqual(1.0, f.clean("1"))

    def test_typedchoicefield_3(self):
        # This can also


d to hold reference geometry
for the GEOS and GDAL tests.
"""

import json
import os

from django.utils.functional import cached_property

# Path where reference test data is located.
TEST_DATA = os.path.join(os.path.dirname(__file__), "data")

def tuplize(seq):
    "Turn all nested sequences to tuples in given sequence."
    if isinstance(seq, (list, tuple)):
        return tuple(tuplize(i) for i in seq)
    return seq

def strconvert(d):
    "Converts all keys in dictionary to str type."
    return {str

t__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

class TestDS(TestObj):
    """
    Object for testing GDAL data sources.
    """

    def __init__(self, name, *, ext="shp", **kwargs):
        # Shapefi

(k): v for k, v in d.items()}

def get_ds_file(name, ext):
    return os.path.join(TEST_DATA, name, name + ".%s" % ext)

class TestObj:
    """
    Base testing object, turns keyword args into attributes.
    """

    def __ini


l(
            str(formset),
            """<input type="hidden" name="choices-TOTAL_FORMS" value="1">
<input type="hidden" name="choices-INITIAL_FORMS" value="0">
<input type="hidden" name="choices-MIN_NUM_FORMS" value="0">
<input type="hidden" name="choices-MAX_NUM_FORMS" value="1000">

Choice:<input type="text" name="choices-0-choice">

Votes:<input type="number" name="choices-0-votes">
""",
        )
        # FormSet are treated similarly to Forms. FormSet has an is_valid()
        #

formset = self.make_choiceformset([("Calexico", "100")])
        self.assertTrue(formset.is_valid())
        self.assertEqual(
            [form.cleaned_data for form in formset.forms],
            [{"votes": 100, "choice": "Calexico"}],
        )

 method, and a cleaned_data or errors attribute depending on whether
        # all the forms passed validation. However, unlike a Form, cleaned_data
        # and errors will be a list of dicts rather than a single dict.


 django.test import SimpleTestCase

class RegexFieldTest(SimpleTestCase):
    def test_regexfield_1(self):
        f = RegexField("^[0-9][A-F][0-9]$")
        self.assertEqual("2A2", f.clean("2A2"))
        self.assertEqual("3F3", f.clean("3F3"))
        with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"):
            f.clean("3G3")
        with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"):
            f.clean(" 2A2")
        with self.assertRaisesMessage(Validat

d("^[0-9][A-F][0-9]$", required=False)
        self.assertEqual("2A2", f.clean("2A2"))
        self.assertEqual("3F3", f.clean("3F3"))
        with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"):
            f.clean("3G3")
        self

ionError, "'Enter a valid value.'"):
            f.clean("2A2 ")
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean("")

    def test_regexfield_2(self):
        f = RegexFiel


trib.gis.geos.coordseq import GEOSCoordSeq
from django.contrib.gis.geos.libgeos import geos_version_tuple
from django.test import SimpleTestCase

class GEOSCoordSeqTest(SimpleTestCase):
    def test_getitem(self):
        coord_seq = LineString([(x, x) for x in range(2)]).coord_seq
        for i in (0, 1):
            with self.subTest(i):
                self.assertEqual(coord_seq[i], (i, i))
        for i in (-3, 10):
            msg = f"Invalid GEOS Geometry index: {i}"
            with self.subTest(i):

("POINT ZM (1 2 3 4)")
        coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)
        self.assertIs(coord_seq.hasm, True)

        geom = GEOSGeometry("POINT Z (1 2 3)")
        coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)
        self.

                with self.assertRaisesMessage(IndexError, msg):
                    coord_seq[i]

    @skipIf(geos_version_tuple() < (3, 14), "GEOS M support requires 3.14+")
    def test_has_m(self):
        geom = GEOSGeometry


from . import PostgreSQLTestCase
from .models import (
    HStoreModel,
    IntegerArrayModel,
    NestedIntegerArrayModel,
    NullableIntegerArrayModel,
    OffByOneModel,
    OtherTypesArrayModel,
    RangesModel,
)

try:
    from django.db.backends.postgresql.psycopg_any import DateRange, NumericRange
except ImportError:
    pass  # psycopg isn't installed.

class BulkSaveTests(PostgreSQLTestCase):
    def test_bulk_update(self):
        test_data = [
            (IntegerArrayModel, "field", [], [1,

umericRange(lower=1, upper=10)),
            (
                RangesModel,
                "dates",
                None,
                DateRange(lower=date.today(), upper=date.today()),
            ),
            (OtherTypesArrayModel, "ips", [], ["1.2

2, 3]),
            (NullableIntegerArrayModel, "field", [1, 2, 3], None),
            (NestedIntegerArrayModel, "field", [], [[1, 2, 3]]),
            (HStoreModel, "field", {}, {1: 2}),
            (RangesModel, "ints", None, N


.introspection.get_constraints(cursor, table)

    def test_check_constraint_range_value(self):
        constraint_name = "ints_between"
        self.assertNotIn(
            constraint_name, self.get_constraints(RangesModel._meta.db_table)
        )
        constraint = CheckConstraint(
            condition=Q(ints__contained_by=NumericRange(10, 30)),
            name=constraint_name,
        )
        with connection.schema_editor() as editor:
            editor.add_constraint(RangesModel, constraint)

.objects.create(ints=(10, 30))

    def test_check_constraint_array_contains(self):
        constraint = CheckConstraint(
            condition=Q(field__contains=[1]),
            name="array_contains",
        )
        msg = f"Constraint “{constraint.nam

     self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table))
        with self.assertRaises(IntegrityError), transaction.atomic():
            RangesModel.objects.create(ints=(20, 50))
        RangesModel


 uuid
from datetime import datetime
from time import sleep

from django.contrib.postgres.functions import RandomUUID, TransactionNow

from . import PostgreSQLTestCase
from .models import NowTestModel, UUIDTestModel

class TestTransactionNow(PostgreSQLTestCase):
    def test_transaction_now(self):
        """
        The test case puts everything under a transaction, so two models
        updated with a short gap should have the same time.
        """
        m1 = NowTestModel.objects.create()
        m2 =

()
        m2.refresh_from_db()

        self.assertIsInstance(m1.when, datetime)
        self.assertEqual(m1.when, m2.when)

class TestRandomUUID(PostgreSQLTestCase):
    def test_random_uuid(self):
        m1 = UUIDTestModel.objects.create()
        m2

NowTestModel.objects.create()

        NowTestModel.objects.filter(id=m1.id).update(when=TransactionNow())
        sleep(0.1)
        NowTestModel.objects.filter(id=m2.id).update(when=TransactionNow())

        m1.refresh_from_db


d=value)
        instance.save()
        reloaded = HStoreModel.objects.get()
        self.assertEqual(reloaded.field, value)

    def test_null(self):
        instance = HStoreModel(field=None)
        instance.save()
        reloaded = HStoreModel.objects.get()
        self.assertIsNone(reloaded.field)

    def test_value_null(self):
        value = {"a": None}
        instance = HStoreModel(field=value)
        instance.save()
        reloaded = HStoreModel.objects.get()
        self.assertEqual(reloaded

d=value)
        instance = HStoreModel.objects.get()
        self.assertEqual(instance.field, expected_value)

        instance = HStoreModel.objects.get(field__a=1)
        self.assertEqual(instance.field, expected_value)

        instance = HStoreModel.

.field, value)

    def test_key_val_cast_to_string(self):
        value = {"a": 1, "b": "B", 2: "c", "ï": "ê"}
        expected_value = {"a": "1", "b": "B", "2": "c", "ï": "ê"}

        instance = HStoreModel.objects.create(fiel


]{6}_%s" % self.index_class.suffix
        )

    def test_deconstruction_no_customization(self):
        index = self.index_class(
            fields=["title"], name="test_title_%s" % self.index_class.suffix
        )
        path, args, kwargs = index.deconstruct()
        self.assertEqual(
            path, "django.contrib.postgres.indexes.%s" % self.index_class.__name__
        )
        self.assertEqual(args, ())
        self.assertEqual(
            kwargs,
            {"fields": ["title"], "name": "t

e=name)
        path, args, kwargs = index.deconstruct()
        self.assertEqual(
            path,
            f"django.contrib.postgres.indexes.{self.index_class.__name__}",
        )
        self.assertEqual(args, (Lower("title"),))
        self.assert

est_title_%s" % self.index_class.suffix},
        )

    def test_deconstruction_with_expressions_no_customization(self):
        name = f"test_title_{self.index_class.suffix}"
        index = self.index_class(Lower("title"), nam


sys

from . import PostgreSQLSimpleTestCase

class PostgresIntegrationTests(PostgreSQLSimpleTestCase):
    def test_check(self):
        test_environ = os.environ.copy()
        if "DJANGO_SETTINGS_MODULE" in test_environ:
            del test_environ["DJANGO_SETTINGS_MODULE"]
        test_environ["PYTHONPATH"] = os.path.join(os.path.dirname(__file__), "../../")
        result = subprocess.run(
            [
                sys.executable,
                "-m",
                "django",
                "ch

"integration_settings",
            ],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.PIPE,
            cwd=os.path.dirname(__file__),
            env=test_environ,
            encoding="utf-8",
        )
        self.assertEqual(resu


from django.core.management import call_command

from . import PostgreSQLTestCase

class InspectDBTests(PostgreSQLTestCase):
    def assertFieldsInModel(self, model, field_outputs):
        out = StringIO()
        call_command(
            "inspectdb",
            table_name_filter=lambda tn: tn.startswith(model),
            stdout=out,
        )
        output = out.getvalue()
        for field_output in field_outputs:
            self.assertIn(field_output, output)

    def test_range_fields(self):

= django.contrib.postgres.fields.BigIntegerRangeField("
                "blank=True, null=True)",
                "decimals = django.contrib.postgres.fields.DecimalRangeField("
                "blank=True, null=True)",
                "timestamps = django.

     self.assertFieldsInModel(
            "postgres_tests_rangesmodel",
            [
                "ints = django.contrib.postgres.fields.IntegerRangeField(blank=True, "
                "null=True)",
                "bigints


on,
        CreateCollation,
        CreateExtension,
        RemoveCollation,
        RemoveIndexConcurrently,
        ValidateConstraint,
    )
except ImportError:
    pass

@unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests.")
@modify_settings(INSTALLED_APPS={"append": "migrations"})
class AddIndexConcurrentlyTests(OptimizerTestBase, OperationTestBase):
    app_label = "test_add_concurrently"

    def test_requires_atomic_false(self):
        project_state = self.set_up_t

e AddIndexConcurrently operation cannot be executed inside "
            "a transaction (set atomic = False on the migration)."
        )
        with self.assertRaisesMessage(NotSupportedError, msg):
            with connection.schema_editor(atomic=True)

est_model(self.app_label)
        new_state = project_state.clone()
        operation = AddIndexConcurrently(
            "Pony",
            Index(fields=["pink"], name="pony_pink_idx"),
        )
        msg = (
            "Th


stance = Model(field=value)
                self.assertEqual(instance.get_field_display(), display)

    def test_discrete_range_fields_unsupported_default_bounds(self):
        discrete_range_types = [
            pg_fields.BigIntegerRangeField,
            pg_fields.IntegerRangeField,
            pg_fields.DateRangeField,
        ]
        for field_type in discrete_range_types:
            msg = f"Cannot use 'default_bounds' with {field_type.__name__}."
            with self.assertRaisesMessage(TypeError

        pg_fields.DateTimeRangeField,
        ]
        for field_type in continuous_range_types:
            field = field_type(choices=[((51, 100), "51-100")], default_bounds="[]")
            self.assertEqual(field.default_bounds, "[]")

    def test_in

, msg):
                field_type(choices=[((51, 100), "51-100")], default_bounds="[]")

    def test_continuous_range_fields_default_bounds(self):
        continuous_range_types = [
            pg_fields.DecimalRangeField,


d and his bowels unplugged, "
                "And his nostrils ripped and his bottom burned off,"
                "And his --"
            ),
        ]
        cls.verses = [
            Line.objects.create(
                scene=cls.robin,
                character=cls.minstrel,
                dialogue=verse,
            )
            for verse in verses
        ]
        cls.verse0, cls.verse1, cls.verse2 = cls.verses

        cls.witch_scene = Scene.objects.create(
            scene="Scene 5", setting=

jects.create(name="Duck")

        cls.bedemir0 = Line.objects.create(
            scene=cls.witch_scene,
            character=bedemir,
            dialogue="We shall use my larger scales!",
            dialogue_config="english",
        )
        cls.bed

"Sir Bedemir's Castle"
        )
        bedemir = Character.objects.create(name="Bedemir")
        crowd = Character.objects.create(name="Crowd")
        witch = Character.objects.create(name="Witch")
        duck = Character.ob


db import connection

from . import PostgreSQLTestCase

try:
    from django.contrib.postgres.signals import (
        get_citext_oids,
        get_hstore_oids,
        register_type_handlers,
    )
except ImportError:
    pass  # psycopg isn't installed.

class OIDTests(PostgreSQLTestCase):
    def assertOIDs(self, oids):
        self.assertIsInstance(oids, tuple)
        self.assertGreater(len(oids), 0)
        self.assertTrue(all(isinstance(oid, int) for oid in oids))

    def test_hstore_cache(self):

Queries(0):
            get_citext_oids(connection.alias)

    def test_hstore_values(self):
        oids, array_oids = get_hstore_oids(connection.alias)
        self.assertOIDs(oids)
        self.assertOIDs(array_oids)

    def test_citext_values(self):

       get_hstore_oids(connection.alias)
        with self.assertNumQueries(0):
            get_hstore_oids(connection.alias)

    def test_citext_cache(self):
        get_citext_oids(connection.alias)
        with self.assertNum


res.search import (
        TrigramDistance,
        TrigramSimilarity,
        TrigramStrictWordDistance,
        TrigramStrictWordSimilarity,
        TrigramWordDistance,
        TrigramWordSimilarity,
    )
except ImportError:
    pass

class TrigramTest(PostgreSQLTestCase):
    Model = CharFieldModel

    @classmethod
    def setUpTestData(cls):
        cls.Model.objects.bulk_create(
            [
                cls.Model(field="Matthew"),
                cls.Model(field="Cat sat on mat."),

"],
            transform=lambda instance: instance.field,
        )

    def test_trigram_word_search(self):
        obj = self.Model.objects.create(
            field="Gumby rides on the path of Middlesbrough",
        )
        self.assertSequenceEqual(

      cls.Model(field="Dog sat on rug."),
            ]
        )

    def test_trigram_search(self):
        self.assertQuerySetEqual(
            self.Model.objects.filter(field__trigram_similar="Mathew"),
            ["Matthew


tgreSQLTestCase
from .models import CharFieldModel, TextFieldModel

class UnaccentTest(PostgreSQLTestCase):
    Model = CharFieldModel

    @classmethod
    def setUpTestData(cls):
        cls.Model.objects.bulk_create(
            [
                cls.Model(field="àéÖ"),
                cls.Model(field="aeO"),
                cls.Model(field="aeo"),
            ]
        )

    def test_unaccent(self):
        self.assertQuerySetEqual(
            self.Model.objects.filter(field__unaccent="aeO"),

e the case
        since unaccent implements the Transform API)
        """
        self.assertQuerySetEqual(
            self.Model.objects.filter(field__unaccent__iexact="aeO"),
            ["àéÖ", "aeO", "aeo"],
            transform=lambda instance: in

     ["àéÖ", "aeO"],
            transform=lambda instance: instance.field,
            ordered=False,
        )

    def test_unaccent_chained(self):
        """
        Unaccent can be used chained with a lookup (which should b


t django.contrib.postgres.fields
from django.db import migrations, models

class Migration(migrations.Migration):
    dependencies = []

    operations = [
        migrations.CreateModel(
            name="IntegerArrayDefaultModel",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        verbose_name="ID",
                        serialize=False,
                        auto_created=True,
                        primary_key=True,

   ),
                ),
                (
                    "field",
                    django.contrib.postgres.fields.ArrayField(models.IntegerField()),
                ),
            ],
            options={},
            bases=(models.Model,),


rom unittest import mock

from django.db import migrations

try:
    from django.contrib.postgres.operations import (
        BloomExtension,
        BtreeGinExtension,
        BtreeGistExtension,
        CITextExtension,
        CreateExtension,
        HStoreExtension,
        TrigramExtension,
        UnaccentExtension,
    )
except ImportError:
    BloomExtension = mock.Mock()
    BtreeGinExtension = mock.Mock()
    BtreeGistExtension = mock.Mock()
    CITextExtension = mock.Mock()
    CreateExtension =

(),
        BtreeGistExtension(),
        CITextExtension(),
        # Ensure CreateExtension quotes extension names by creating one with a
        # dash in its name.
        CreateExtension("uuid-ossp"),
        HStoreExtension(),
        TrigramExtensio

 mock.Mock()
    HStoreExtension = mock.Mock()
    TrigramExtension = mock.Mock()
    UnaccentExtension = mock.Mock()

class Migration(migrations.Migration):
    operations = [
        BloomExtension(),
        BtreeGinExtension


      ),
                ("field", ArrayField(models.CharField(max_length=10))),
            ],
            options={
                "required_db_vendor": "postgresql",
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name="DateTimeArrayModel",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        verbose_name="ID",
                        serialize=False,

)),
                ("times", ArrayField(models.TimeField())),
            ],
            options={
                "required_db_vendor": "postgresql",
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(

    auto_created=True,
                        primary_key=True,
                    ),
                ),
                ("datetimes", ArrayField(models.DateTimeField())),
                ("dates", ArrayField(models.DateField()


 django.contrib.postgres.fields
from django.db import migrations, models

class Migration(migrations.Migration):
    dependencies = []

    operations = [
        migrations.CreateModel(
            name="CharTextArrayIndexModel",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        verbose_name="ID",
                        serialize=False,
                        auto_created=True,
                        primary_key=True,

                  ),
                ),
                ("char2", models.CharField(max_length=11, db_index=True)),
                (
                    "text",
                    django.contrib.postgres.fields.ArrayField(
                        models.T

               ),
                ),
                (
                    "char",
                    django.contrib.postgres.fields.ArrayField(
                        models.CharField(max_length=10), db_index=True, size=100


sys
import unittest

from django.apps import apps
from django.core.management import ManagementUtility
from django.test.utils import captured_stdout

class BashCompletionTests(unittest.TestCase):
    """
    Testing the Python level bash completion code.
    This requires setting up the environment as if we got passed data
    from bash.
    """

    def setUp(self):
        self.old_DJANGO_AUTO_COMPLETE = os.environ.get("DJANGO_AUTO_COMPLETE")
        os.environ["DJANGO_AUTO_COMPLETE"] = "1"

    def tear

t_str):
        """
        Set the environment and the list of command line arguments.

        This sets the bash variables $COMP_WORDS and $COMP_CWORD. The former is
        an array consisting of the individual words in the current command
        line

Down(self):
        if self.old_DJANGO_AUTO_COMPLETE:
            os.environ["DJANGO_AUTO_COMPLETE"] = self.old_DJANGO_AUTO_COMPLETE
        else:
            del os.environ["DJANGO_AUTO_COMPLETE"]

    def _user_input(self, inpu


db import models

class User(models.Model):
    username = models.CharField(max_length=12, unique=True)
    serial = models.IntegerField()

class UserSite(models.Model):
    user = models.ForeignKey(User, models.CASCADE, to_field="username")
    data = models.IntegerField()

class UserProfile(models.Model):
    user = models.ForeignKey(User, models.CASCADE, unique=True, to_field="username")
    about = models.TextField()

class UserPreferences(models.Model):
    user = models.OneToOneField(
        User

 to_field="user")
    network = models.IntegerField()
    identifier = models.IntegerField()

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

class Restaurant(Place):
    pass

class Manager(models.Model):
    restaurant = models.

,
        models.CASCADE,
        to_field="username",
        primary_key=True,
    )
    favorite_number = models.IntegerField()

class ProfileNetwork(models.Model):
    profile = models.ForeignKey(UserProfile, models.CASCADE,


rove
        # you can create a form with no data
        form = Form()
        form_set = FormSet(instance=User())

        # Now create a new User and UserSite instance
        data = {
            "serial": "1",
            "username": "apollo13",
            "usersite_set-TOTAL_FORMS": "1",
            "usersite_set-INITIAL_FORMS": "0",
            "usersite_set-MAX_NUM_FORMS": "0",
            "usersite_set-0-data": "10",
            "usersite_set-0-user": "apollo13",
        }
        user = User()

valid():
            form_set.save()
            usersite = UserSite.objects.values()
            self.assertEqual(usersite[0]["data"], 10)
            self.assertEqual(usersite[0]["user_id"], "apollo13")
        else:
            self.fail("Errors found o

      form = Form(data)
        if form.is_valid():
            user = form.save()
        else:
            self.fail("Errors found on form:%s" % form_set)

        form_set = FormSet(data, instance=user)
        if form_set.is_


Factory()

    def setUp(self):
        request_started.disconnect(close_old_connections)
        self.addCleanup(request_started.connect, close_old_connections)

    async def test_get_asgi_application(self):
        """
        get_asgi_application() returns a functioning ASGI callable.
        """
        application = get_asgi_application()
        # Construct HTTP request.
        scope = self.async_request_factory._base_scope(path="/")
        communicator = ApplicationCommunicator(application, scope)

      self.assertEqual(response_start["status"], 200)
        self.assertEqual(
            set(response_start["headers"]),
            {
                (b"Content-Length", b"12"),
                (b"Content-Type", b"text/html; charset=utf-8"),

        await communicator.send_input({"type": "http.request"})
        # Read the response.
        response_start = await communicator.receive_output()
        self.assertEqual(response_start["type"], "http.response.start")


eading
import time

from django.http import FileResponse, HttpResponse, StreamingHttpResponse
from django.urls import path
from django.views.decorators.csrf import csrf_exempt

def hello(request):
    name = request.GET.get("name") or "World"
    return HttpResponse("Hello %s!" % name)

def hello_with_delay(request):
    name = request.GET.get("name") or "World"
    time.sleep(1)
    return HttpResponse(f"Hello {name}!")

def hello_meta(request):
    return HttpResponse(
        "From %s" % request.META.

nc_waiter(request):
    with sync_waiter.lock:
        sync_waiter.active_threads.add(threading.current_thread())
    sync_waiter.barrier.wait(timeout=0.5)
    return hello(request)

@csrf_exempt
def post_echo(request):
    if request.GET.get("echo"):

get("HTTP_REFERER") or "",
        content_type=request.META.get("CONTENT_TYPE"),
    )

def hello_cookie(request):
    response = HttpResponse("Hello World!")
    response.set_cookie("key", "value")
    return response

def sy


th(__file__).parent.absolute()
EXTRA_TEMPLATES_DIR = ROOT / "templates_extra"

@override_settings(
    INSTALLED_APPS=["template_tests"],
    TEMPLATES=[
        {
            "BACKEND": "django.template.backends.dummy.TemplateStrings",
            "APP_DIRS": True,
        },
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            "DIRS": [EXTRA_TEMPLATES_DIR],
            "OPTIONS": {
                "context_processors": [
                    "django.template.cont

          },
        },
    ],
)
class TemplateReloadTests(SimpleTestCase):
    @mock.patch("django.template.autoreload.reset_loaders")
    def test_template_changed(self, mock_reset):
        template_path = Path(__file__).parent / "templates" / "index.ht

ext_processors.request",
                ],
                "loaders": [
                    "django.template.loaders.filesystem.Loader",
                    "django.template.loaders.app_directories.Loader",
                ],


able, VariableDoesNotExist
from django.template.base import DebugLexer, Lexer, TokenType
from django.test import SimpleTestCase
from django.utils.translation import gettext_lazy

class LexerTestMixin:
    template_string = (
        "text\n"
        "{% if test %}{{ varvalue }}{% endif %}"
        "{#comment {{not a var}} {%not a block%} #}"
        "end text"
    )
    expected_token_tuples = [
        # (token_type, contents, lineno, position)
        (TokenType.TEXT, "text\n", 1, (0, 5)),
        (Token

kenType.TEXT, "end text", 2, (85, 93)),
    ]

    def test_tokenize(self):
        tokens = self.lexer_class(self.template_string).tokenize()
        token_tuples = [
            (t.token_type, t.contents, t.lineno, t.position) for t in tokens
        ]

Type.BLOCK, "if test", 2, (5, 18)),
        (TokenType.VAR, "varvalue", 2, (18, 32)),
        (TokenType.BLOCK, "endif", 2, (32, 43)),
        (TokenType.COMMENT, "comment {{not a var}} {%not a block%}", 2, (43, 85)),
        (To


        cls.engine = Engine()
        super().setUpClass()

    def test_callable(self):
        class Doodad:
            def __init__(self, value):
                self.num_calls = 0
                self.value = value

            def __call__(self):
                self.num_calls += 1
                return {"the_value": self.value}

        my_doodad = Doodad(42)
        c = Context({"my_doodad": my_doodad})

        # We can't access ``my_doodad.value`` in the template, because
        # ``my_doodad._

oodad has been called
        self.assertEqual(my_doodad.num_calls, 1)

        # But we can access keys on the dict that's returned
        # by ``__call__``, instead.
        t = self.engine.from_string("{{ my_doodad.the_value }}")
        self.assertEqu

_call__`` will be invoked first, yielding a dictionary
        # without a key ``value``.
        t = self.engine.from_string("{{ my_doodad.value }}")
        self.assertEqual(t.render(c), "")

        # We can confirm that the d


     c = Context({"a": 1, "b": "xyzzy"})
        self.assertEqual(c["a"], 1)
        self.assertEqual(c.push(), {})
        c["a"] = 2
        self.assertEqual(c["a"], 2)
        self.assertEqual(c.get("a"), 2)
        self.assertEqual(c.pop(), {"a": 2})
        self.assertEqual(c["a"], 1)
        self.assertEqual(c.get("foo", 42), 42)
        self.assertEqual(c, mock.ANY)

    def test_push_context_manager(self):
        c = Context({"a": 1})
        with c.push():
            c["a"] = 2
            self.a

: 1})
        with c.update({}):
            c["a"] = 2
            self.assertEqual(c["a"], 2)
        self.assertEqual(c["a"], 1)

        with c.update({"a": 3}):
            self.assertEqual(c["a"], 3)
        self.assertEqual(c["a"], 1)

    def test_

ssertEqual(c["a"], 2)
        self.assertEqual(c["a"], 1)

        with c.push(a=3):
            self.assertEqual(c["a"], 3)
        self.assertEqual(c["a"], 1)

    def test_update_context_manager(self):
        c = Context({"a"


ed result"),
            ("{% load custom %}{% one_param 37 %}", "one_param - Expected result: 37"),
            (
                "{% load custom %}{% explicit_no_context 37 %}",
                "explicit_no_context - Expected result: 37",
            ),
            (
                "{% load custom %}{% no_params_with_context %}",
                "no_params_with_context - Expected result (context value: 42)",
            ),
            (
                "{% load custom %}{% params_and_context 37 %}",

42",
            ),
            (
                "{% load custom %}{% simple_keyword_only_param kwarg=37 %}",
                "simple_keyword_only_param - Expected result: 37",
            ),
            (
                "{% load custom %}{% simple_keywo

            "params_and_context - Expected result (context value: 42): 37",
            ),
            (
                "{% load custom %}{% simple_two_params 37 42 %}",
                "simple_two_params - Expected result: 37,


from django.template.engine import Engine
from django.test import SimpleTestCase, override_settings

from .utils import ROOT, TEMPLATE_DIR

OTHER_DIR = os.path.join(ROOT, "other_templates")

class EngineTest(SimpleTestCase):
    def test_repr_empty(self):
        engine = Engine()
        self.assertEqual(
            repr(engine),
            "<Engine: app_dirs=False debug=False loaders=[("
            "'django.template.loaders.cached.Loader', "
            "['django.template.loaders.filesystem.Loader'])

def test_repr(self):
        engine = Engine(
            dirs=[TEMPLATE_DIR],
            context_processors=["django.template.context_processors.debug"],
            debug=True,
            loaders=["django.template.loaders.filesystem.Loader"],

] "
            "string_if_invalid='' file_charset='utf-8' builtins=["
            "'django.template.defaulttags', 'django.template.defaultfilters', "
            "'django.template.loader_tags'] autoescape=True>",
        )


cursive_templates")

class ExtendsBehaviorTests(SimpleTestCase):
    def test_normal_extend(self):
        engine = Engine(dirs=[os.path.join(RECURSIVE, "fs")])
        template = engine.get_template("one.html")
        output = template.render(Context({}))
        self.assertEqual(output.strip(), "three two one")

    def test_extend_recursive(self):
        engine = Engine(
            dirs=[
                os.path.join(RECURSIVE, "fs"),
                os.path.join(RECURSIVE, "fs2"),
                os

/recursive")

    def test_extend_missing(self):
        engine = Engine(dirs=[os.path.join(RECURSIVE, "fs")])
        template = engine.get_template("extend-missing.html")
        with self.assertRaises(TemplateDoesNotExist) as e:
            template.ren

.path.join(RECURSIVE, "fs3"),
            ]
        )
        template = engine.get_template("recursive.html")
        output = template.render(Context({}))
        self.assertEqual(output.strip(), "fs3/recursive fs2/recursive fs


mpleTestCase

from .utils import ROOT

RELATIVE = os.path.join(ROOT, "relative_templates")

class ExtendsRelativeBehaviorTests(SimpleTestCase):
    def test_normal_extend(self):
        engine = Engine(dirs=[RELATIVE])
        template = engine.get_template("one.html")
        output = template.render(Context({}))
        self.assertEqual(output.strip(), "three two one")

    def test_normal_extend_variable(self):
        engine = Engine(dirs=[RELATIVE])
        template = engine.get_template("one_var.html

t_template("dir1/one.html")
        output = template.render(Context({}))
        self.assertEqual(output.strip(), "three two one dir1 one")

    def test_dir1_extend1(self):
        engine = Engine(dirs=[RELATIVE])
        template = engine.get_template("

")
        output = template.render(Context({"tmpl": "./two.html"}))
        self.assertEqual(output.strip(), "three two one")

    def test_dir1_extend(self):
        engine = Engine(dirs=[RELATIVE])
        template = engine.ge


strationTests(SimpleTestCase):
    def setUp(self):
        self.library = Library()

    def test_filter(self):
        @self.library.filter
        def func():
            return ""

        self.assertEqual(self.library.filters["func"], func)

    def test_filter_parens(self):
        @self.library.filter()
        def func():
            return ""

        self.assertEqual(self.library.filters["func"], func)

    def test_filter_name_arg(self):
        @self.library.filter("name")
        def func():

l(self.library.filters["name"], func)

    def test_filter_call(self):
        def func():
            return ""

        self.library.filter("name", func)
        self.assertEqual(self.library.filters["name"], func)

    def test_filter_invalid(self):

          return ""

        self.assertEqual(self.library.filters["name"], func)

    def test_filter_name_kwarg(self):
        @self.library.filter(name="name")
        def func():
            return ""

        self.assertEqua


Engine(
            dirs=[TEMPLATE_DIR],
            loaders=[
                (
                    "django.template.loaders.cached.Loader",
                    [
                        "django.template.loaders.filesystem.Loader",
                    ],
                ),
            ],
        )

    def test_get_template(self):
        template = self.engine.get_template("index.html")
        self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, "index.html"))
        self.assertEqual(templa

 self.assertEqual(cache["index.html"], template)

        # Run a second time from cache
        template = self.engine.get_template("index.html")
        self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, "index.html"))
        self.assertE

te.origin.template_name, "index.html")
        self.assertEqual(
            template.origin.loader, self.engine.template_loaders[0].loaders[0]
        )

        cache = self.engine.template_loaders[0].get_template_cache


import (
    LinearRing,
    LineString,
    MultiPoint,
    Point,
    Polygon,
    fromstr,
)
from django.test import SimpleTestCase

def api_get_distance(x):
    return x.distance(Point(-200, -200))

def api_get_buffer(x):
    return x.buffer(10)

def api_get_geom_typeid(x):
    return x.geom_typeid

def api_get_num_coords(x):
    return x.num_coords

def api_get_centroid(x):
    return x.centroid

def api_get_empty(x):
    return x.empty

def api_get_valid(x):
    return x.valid

def api_get_sim

et_area(x):
    return x.area

def api_get_length(x):
    return x.length

geos_function_tests = [
    val
    for name, val in vars().items()
    if hasattr(val, "__call__") and name.startswith("api_get_")
]

class GEOSMutationTest(SimpleTestCase):

ple(x):
    return x.simple

def api_get_ring(x):
    return x.ring

def api_get_boundary(x):
    return x.boundary

def api_get_convex_hull(x):
    return x.convex_hull

def api_get_extent(x):
    return x.extent

def api_g


 self._list = self._mytype(i_list)
        super().__init__(*args, **kwargs)

    def __len__(self):
        return len(self._list)

    def __str__(self):
        return str(self._list)

    def __repr__(self):
        return repr(self._list)

    def _set_list(self, length, items):
        # this would work:
        # self._list = self._mytype(items)
        # but then we wouldn't be testing length parameter
        itemList = ["x"] * length
        for i, v in enumerate(items):
            itemList[i] =

list[index] = value

def nextRange(length):
    nextRange.start += 100
    return range(nextRange.start, nextRange.start + length)

nextRange.start = 0

class ListMixinTest(SimpleTestCase):
    """
    Tests base class ListMixin by comparing a list clon

v

        self._list = self._mytype(itemList)

    def _get_single_external(self, index):
        return self._list[index]

class UserListB(UserListA):
    _mytype = list

    def _set_single(self, index, value):
        self._


o.db import migrations
from django.db.models import deletion

class Migration(migrations.Migration):
    dependencies = [
        ("rasterapp", "0001_setup_extensions"),
    ]

    operations = [
        migrations.CreateModel(
            name="RasterModel",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,

                        srid=4326,
                        verbose_name="A Verbose Raster Name",
                    ),
                ),
                (
                    "rastprojected",
                    models.fields.RasterField(

     verbose_name="ID",
                    ),
                ),
                (
                    "rast",
                    models.fields.RasterField(
                        blank=True,
                        null=True,


ture, skipUnlessDBFeature

try:
    GeometryColumns = connection.ops.geometry_columns()
    HAS_GEOMETRY_COLUMNS = True
except NotImplementedError:
    HAS_GEOMETRY_COLUMNS = False

class OperationTestCase(TransactionTestCase):
    available_apps = ["gis_tests.gis_migrations"]
    get_opclass_query = """
        SELECT opcname, c.relname FROM pg_opclass AS oc
        JOIN pg_index as i on oc.oid = ANY(i.indclass)
        JOIN pg_class as c on c.oid = i.indexrelid
        WHERE c.relname = %s
    """

    d

 )
        super().tearDown()

    @property
    def has_spatial_indexes(self):
        if connection.ops.mysql:
            with connection.cursor() as cursor:
                return connection.introspection.supports_spatial_index(
                    cur

ef tearDown(self):
        # Delete table after testing
        if hasattr(self, "current_state"):
            self.apply_operations(
                "gis", self.current_state, [migrations.DeleteModel("Neighborhood")]


 in any serializable format (including JSON and XML). Fixtures
are identified by name, and are stored in either a directory named 'fixtures'
in the application directory, or in one of the directories named in the
``FIXTURE_DIRS`` setting.
"""

import uuid

from django.contrib.auth.models import Permission
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models

class Category(models.Model):
    title = models.C

gth=100, default="Default headline")
    pub_date = models.DateTimeField()

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

    def __str__(self):
        return self.headline

class Blog(models.Model):
    name = models.CharField(max_length

harField(max_length=100)
    description = models.TextField()

    class Meta:
        ordering = ("title",)

    def __str__(self):
        return self.title

class Article(models.Model):
    headline = models.CharField(max_len


 = []

    def test_class_fixtures(self):
        "There were no fixture objects installed"
        self.assertEqual(Article.objects.count(), 0)

class DumpDataAssertMixin:
    def _dumpdata_assert(
        self,
        args,
        output,
        format="json",
        filename=None,
        natural_foreign_keys=False,
        natural_primary_keys=False,
        use_base_manager=False,
        exclude_list=[],
        primary_keys="",
    ):
        new_io = StringIO()
        filename = filename and o

,
            use_natural_foreign_keys=natural_foreign_keys,
            use_natural_primary_keys=natural_primary_keys,
            use_base_manager=use_base_manager,
            exclude=exclude_list,
            primary_keys=primary_keys,
        )

s.path.join(tempfile.gettempdir(), filename)
        management.call_command(
            "dumpdata",
            *args,
            format=format,
            stdout=new_io,
            stderr=new_io,
            output=filename


ACHES={
        "default": {
            "BACKEND": "django.core.cache.backends.dummy.DummyCache",
        }
    }
)
class AsyncDummyCacheTests(SimpleTestCase):
    async def test_simple(self):
        """Dummy cache backend ignores cache set calls."""
        await cache.aset("key", "value")
        self.assertIsNone(await cache.aget("key"))

    async def test_aadd(self):
        """Add doesn't do anything in dummy cache backend."""
        self.assertIs(await cache.aadd("key", "value"), True)
        sel

f.assertIsNone(await cache.aget("does_not_exist"))
        self.assertEqual(await cache.aget("does_not_exist", "default"), "default")

    async def test_aget_many(self):
        """aget_many() returns nothing for the dummy cache backend."""
        await

f.assertIs(await cache.aadd("key", "new_value"), True)
        self.assertIsNone(await cache.aget("key"))

    async def test_non_existent(self):
        """Nonexistent keys aren't found in the dummy cache backend."""
        sel


ettings
from django.utils import translation

from .models import Album, Band, ReleaseEvent, VideoStream

class AlbumForm(forms.ModelForm):
    class Meta:
        model = Album
        fields = ["band", "featuring"]
        widgets = {
            "band": AutocompleteSelect(
                Album._meta.get_field("band"),
                admin.site,
                attrs={"class": "my-class"},
            ),
            "featuring": AutocompleteSelect(
                Album._meta.get_field("featuring"),

band").remote_field, admin.site
        ),
        required=False,
    )

class RequiredBandForm(forms.Form):
    band = ModelChoiceField(
        queryset=Album.objects.all(),
        widget=AutocompleteSelect(
            Album._meta.get_field("band").r

              admin.site,
            ),
        }

class NotRequiredBandForm(forms.Form):
    band = ModelChoiceField(
        queryset=Album.objects.all(),
        widget=AutocompleteSelect(
            Album._meta.get_field("


ield(Event, "link", widgets.AdminURLFieldWidget)

    def test_IntegerField(self):
        self.assertFormfield(Event, "min_age", widgets.AdminIntegerFieldWidget)

    def test_CharField(self):
        self.assertFormfield(Member, "name", widgets.AdminTextInputWidget)

    def test_EmailField(self):
        self.assertFormfield(Member, "email", widgets.AdminEmailInputWidget)

    def test_FileField(self):
        self.assertFormfield(Album, "cover_art", widgets.AdminFileWidget)

    def test_ForeignKey(self

     raw_id_fields=["main_band"],
        )

    def test_radio_fields_ForeignKey(self):
        ff = self.assertFormfield(
            Event,
            "main_band",
            widgets.AdminRadioSelect,
            radio_fields={"main_band": admin.VERTI

):
        self.assertFormfield(Event, "main_band", forms.Select)

    def test_raw_id_ForeignKey(self):
        self.assertFormfield(
            Event,
            "main_band",
            widgets.ForeignKeyRawIdWidget,


.receivers),
        )

    def tearDown(self):
        # All our signals got disconnected properly.
        post_signals = (
            len(signals.pre_save.receivers),
            len(signals.post_save.receivers),
            len(signals.pre_delete.receivers),
            len(signals.post_delete.receivers),
        )
        self.assertEqual(self.pre_signals, post_signals)

class SignalTests(BaseSignalSetup, TestCase):
    def test_model_pre_init_and_post_init(self):
        data = []

        def pre_i

        signals.post_init.connect(post_init_callback)

        p1 = Person(first_name="John", last_name="Doe")
        self.assertEqual(data, [{}, p1])

    def test_save_signals(self):
        data = []

        def pre_save_handler(signal, sender, instan

nit_callback(sender, args, **kwargs):
            data.append(kwargs["kwargs"])

        signals.pre_init.connect(pre_init_callback)

        def post_init_callback(sender, instance, **kwargs):
            data.append(instance)


h are a way of specifying common
      information inherited by the subclasses. They don't exist as a separate
      model.
    - non-abstract base classes (the default), which are models in their own
      right with their own database tables and everything. Their subclasses
      have references back to them, created automatically.

Both styles are demonstrated here.
"""

from django.db import models

#
# Abstract base classes
#

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

b = models.CharField(max_length=50)

class Student(CommonInfo):
    school_class = models.CharField(max_length=10)

    class Meta:
        pass

#
# Abstract base classes with related models
#

class Post(models.Model):
    title = models.CharField(max

    age = models.PositiveIntegerField()

    class Meta:
        abstract = True
        ordering = ["name"]

    def __str__(self):
        return "%s %s" % (self.__class__.__name__, self.name)

class Worker(CommonInfo):
    jo


he __str__() method, just as with normal Python
        # subclassing. This is useful if you want to factor out common
        # information for programming purposes, but still completely
        # independent separate models at the database level.
        w1 = Worker.objects.create(name="Fred", age=35, job="Quarry worker")
        Worker.objects.create(name="Barney", age=34, job="Quarry worker")

        s = Student.objects.create(name="Pebbles", age=5, school_class="1B")

        self.assertEqual(str(w1),

.objects.values("name"),
            [
                {"name": "Barney"},
                {"name": "Fred"},
            ],
        )

        # Since Student does not subclass CommonInfo's Meta, it has the effect
        # of completely overriding it. So

 "Worker Fred")
        self.assertEqual(str(s), "Student Pebbles")

        # The children inherit the Meta class of their parents (if they don't
        # specify their own).
        self.assertSequenceEqual(
            Worker


s, so the tests don't fail when
run with a backend other than PostgreSQL.
"""

import enum

from django.db import models

try:
    from django.contrib.postgres.fields import (
        ArrayField,
        BigIntegerRangeField,
        DateRangeField,
        DateTimeRangeField,
        DecimalRangeField,
        HStoreField,
        IntegerRangeField,
    )
    from django.contrib.postgres.search import SearchVector, SearchVectorField
except ImportError:

    class DummyArrayField(models.Field):
        def

                 "base_field": "",
                    "size": 1,
                }
            )
            return name, path, args, kwargs

    class DummyContinuousRangeField(models.Field):
        def __init__(self, *args, default_bounds="[)", **kwarg

__init__(self, base_field, size=None, **kwargs):
            super().__init__(**kwargs)

        def deconstruct(self):
            name, path, args, kwargs = super().deconstruct()
            kwargs.update(
                {


RangeField,
    OffByOneField,
    SearchVectorField,
)

class Tag:
    def __init__(self, tag_id):
        self.tag_id = tag_id

    def __eq__(self, other):
        return isinstance(other, Tag) and self.tag_id == other.tag_id

class TagField(models.SmallIntegerField):
    def from_db_value(self, value, expression, connection):
        if value is None:
            return value
        return Tag(int(value))

    def to_python(self, value):
        if isinstance(value, Tag):
            return value

   required_db_vendor = "postgresql"

class IntegerArrayModel(PostgreSQLModel):
    field = ArrayField(models.BigIntegerField(), default=list, blank=True)

class NullableIntegerArrayModel(PostgreSQLModel):
    field = ArrayField(models.BigIntegerField(),

     if value is None:
            return value
        return Tag(int(value))

    def get_prep_value(self, value):
        return value.tag_id

class PostgreSQLModel(models.Model):
    class Meta:
        abstract = True


signals import connection_created
from django.db.migrations.writer import MigrationWriter
from django.test import TestCase
from django.test.utils import CaptureQueriesContext, modify_settings, override_settings

try:
    from django.contrib.postgres.fields import (
        DateRangeField,
        DateTimeRangeField,
        DecimalRangeField,
        IntegerRangeField,
    )
    from django.contrib.postgres.signals import get_hstore_oids
    from django.db.backends.postgresql.psycopg_any import (
        Da

ostgresConfigTests(TestCase):
    def test_install_app_no_warning(self):
        # Clear cache to force queries when (re)initializing the
        # "django.contrib.postgres" app.
        get_hstore_oids.cache_clear()
        with CaptureQueriesContext(conn

teRange,
        DateTimeRange,
        DateTimeTZRange,
        NumericRange,
        is_psycopg3,
    )
except ImportError:
    pass

@unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests")
class P


solate_apps("postgres_tests")
class BasicTests(PostgreSQLSimpleTestCase):
    def test_get_field_display(self):
        class MyModel(PostgreSQLModel):
            field = ArrayField(
                models.CharField(max_length=16),
                choices=[
                    ["Media", [(["vinyl", "cd"], "Audio")]],
                    (("mp3", "mp4"), "Digital"),
                ],
            )

        tests = (
            (["vinyl", "cd"], "Audio"),
            (("mp3", "mp4"), "Digital"),

             self.assertEqual(instance.get_field_display(), display)

    def test_get_field_display_nested_array(self):
        class MyModel(PostgreSQLModel):
            field = ArrayField(
                ArrayField(models.CharField(max_length=16)),

  (("a", "b"), "('a', 'b')"),
            (["c", "d"], "['c', 'd']"),
        )
        for value, display in tests:
            with self.subTest(value=value, display=display):
                instance = MyModel(field=value)


s GEOSIOTest(SimpleTestCase):
    def test01_wktreader(self):
        # Creating a WKTReader instance
        wkt_r = WKTReader()
        wkt = "POINT (5 23)"

        # read() should return a GEOSGeometry
        ref = GEOSGeometry(wkt)
        g1 = wkt_r.read(wkt.encode())
        g2 = wkt_r.read(wkt)

        for geom in (g1, g2):
            with self.subTest(geom=geom):
                self.assertEqual(ref, geom)

        # Should only accept string objects.
        bad_input = (1, 5.23, None, False, m

r, msg.format(bad_wkt)),
            ):
                wkt_r.read(bad_wkt)

    def test02_wktwriter(self):
        # Creating a WKTWriter instance, testing its ptr property.
        wkt_w = WKTWriter()
        msg = "Incompatible pointer type: "

emoryview(b"foo"))
        msg = "'wkt' must be bytes or str (got {} instead)."
        for bad_wkt in bad_input:
            with (
                self.subTest(bad_wkt=bad_wkt),
                self.assertRaisesMessage(TypeErro


    available_apps = ["gis_tests.rasterapp"]

    def setUp(self):
        rast = GDALRaster(
            {
                "srid": 4326,
                "origin": [0, 0],
                "scale": [-1, 1],
                "skew": [0, 0],
                "width": 5,
                "height": 5,
                "nr_of_bands": 2,
                "bands": [{"data": range(25)}, {"data": range(25, 50)}],
            }
        )
        model_instance = RasterModel.objects.create(
            rast=rast,

where the RasterField has a null value.
        """
        r = RasterModel.objects.create(rast=None)
        r.refresh_from_db()
        self.assertIsNone(r.rast)

    def test_access_band_data_directly_from_queryset(self):
        RasterModel.objects.cre

  rastprojected=rast,
            geom="POINT (-95.37040 29.70486)",
        )
        RasterRelatedModel.objects.create(rastermodel=model_instance)

    def test_field_null_value(self):
        """
        Test creating a model


rations.CreateModel(
        name="Neighborhood",
        fields=[
            (
                "id",
                models.AutoField(
                    verbose_name="ID",
                    serialize=False,
                    auto_created=True,
                    primary_key=True,
                ),
            ),
            ("name", models.CharField(max_length=100, unique=True)),
            ("geom", models.MultiPolygonField(srid=4326)),
        ],
        options={},
        bases=(models.Model,)

                 auto_created=True,
                    primary_key=True,
                ),
            ),
            (
                "neighborhood",
                models.ForeignKey(
                    "gis_migrations.Neighborhood",

,
    ),
    migrations.CreateModel(
        name="Household",
        fields=[
            (
                "id",
                models.AutoField(
                    verbose_name="ID",
                    serialize=False,


rror:
    Image = None
else:
    temp_storage_dir = tempfile.mkdtemp()
    temp_storage = FileSystemStorage(temp_storage_dir)

class MyFileField(models.FileField):
    pass

class Member(models.Model):
    name = models.CharField(max_length=100)
    birthdate = models.DateTimeField(blank=True, null=True)
    gender = models.CharField(
        max_length=1, blank=True, choices=[("M", "Male"), ("F", "Female")]
    )
    email = models.EmailField(blank=True)

    def __str__(self):
        return self.name

.ManyToManyField(Member)

    def __str__(self):
        return self.name

class UnsafeLimitChoicesTo(models.Model):
    band = models.ForeignKey(
        Band,
        models.CASCADE,
        limit_choices_to={"name": '"&><escapeme'},
    )

class Album

class Artist(models.Model):
    pass

class Band(Artist):
    uuid = models.UUIDField(unique=True, default=uuid.uuid4)
    name = models.CharField(max_length=100)
    style = models.CharField(max_length=20)
    members = models


g signals before/after saving and deleting.
"""

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

class Car(models.Model):
    make = models.CharField(max_length=20)
    model = models.CharField(max_length=20)

class Author(models.Model):
    name = models.CharField(max_length=20)

    def __str__(self):
        retur

class Book(models.Model):
    name = models.CharField(max_length=20)
    authors = models.ManyToManyField(Author)

    def __str__(self):
        return self.name

class Page(models.Model):
    book = models.ForeignKey(Book, on_delete=models.CASCADE)


"Club")

class YearInSchool(models.TextChoices):
    FRESHMAN = "FR", _("Freshman")
    SOPHOMORE = "SO", _("Sophomore")
    JUNIOR = "JR", _("Junior")
    SENIOR = "SR", _("Senior")
    GRADUATE = "GR", _("Graduate")

class Vehicle(models.IntegerChoices):
    CAR = 1, "Carriage"
    TRUCK = 2
    JET_SKI = 3

    __empty__ = _("(Unknown)")

class Gender(models.TextChoices):
    MALE = "M"
    FEMALE = "F"
    NOT_SPECIFIED = "X"

    __empty__ = "(Undeclared)"

class ChoicesTests(SimpleTestCase):
    d

      self.assertEqual(Suit.values, [1, 2, 3, 4])
        self.assertEqual(Suit.names, ["DIAMOND", "SPADE", "HEART", "CLUB"])

        self.assertEqual(repr(Suit.DIAMOND), "Suit.DIAMOND")
        self.assertEqual(Suit.DIAMOND.label, "Diamond")
        self

ef test_integerchoices(self):
        self.assertEqual(
            Suit.choices, [(1, "Diamond"), (2, "Spade"), (3, "Heart"), (4, "Club")]
        )
        self.assertEqual(Suit.labels, ["Diamond", "Spade", "Heart", "Club"])


ing
    from django.contrib.postgres.aggregates import (
        StringAgg,  # RemovedInDjango70Warning.
    )
    from django.contrib.postgres.aggregates import (
        ArrayAgg,
        BoolAnd,
        BoolOr,
        Corr,
        CovarPop,
        JSONBAgg,
        RegrAvgX,
        RegrAvgY,
        RegrCount,
        RegrIntercept,
        RegrR2,
        RegrSlope,
        RegrSXX,
        RegrSXY,
        RegrSYY,
        StatAggregate,
    )
    from django.contrib.postgres.fields import ArrayFi

                AggregateTestModel(
                    boolean_field=True,
                    char_field="Foo1",
                    text_field="Text1",
                    integer_field=0,
                ),
                AggregateTestModel(

eld
except ImportError:
    pass  # psycopg2 is not installed

class TestGeneralAggregate(PostgreSQLTestCase):
    @classmethod
    def setUpTestData(cls):
        cls.aggs = AggregateTestModel.objects.bulk_create(
            [


om django.test.utils import isolate_apps

from . import PostgreSQLTestCase
from .fields import (
    BigIntegerRangeField,
    DateRangeField,
    DateTimeRangeField,
    DecimalRangeField,
    HStoreField,
    IntegerRangeField,
    SearchVectorField,
)
from .models import IntegerArrayModel, NestedIntegerArrayModel, PostgreSQLModel

try:
    from django.contrib.postgres.constraints import ExclusionConstraint
    from django.contrib.postgres.fields.ranges import RangeOperators
    from django.contrib.postgr

  def _make_error(self, obj, klass_name):
        """Helper to create postgres.E005 error for specific objects."""
        return checks.Error(
            "'django.contrib.postgres' must be in INSTALLED_APPS in order to "
            f"use {klass_name}.",

es.indexes import GinIndex, PostgresIndex
    from django.contrib.postgres.search import SearchQueryField
except ImportError:
    pass

@isolate_apps("postgres_tests")
class TestPostgresAppInstalledCheck(PostgreSQLTestCase):


m django.db import connection
from django.test import TransactionTestCase

class MigrateTests(TransactionTestCase):
    """
    Tests running the migrate command in GeoDjango.
    """

    available_apps = ["gis_tests.gis_migrations"]

    def get_table_description(self, table):
        with connection.cursor() as cursor:
            return connection.introspection.get_table_description(cursor, table)

    def assertTableExists(self, table):
        with connection.cursor() as cursor:
            self.asse

    def test_migrate_gis(self):
        """
        Tests basic usage of the migrate command when a model uses GeoDjango
        fields (#22001).

        It's also used to showcase an error in migrations where spatialite is
        enabled and geo tables

rtIn(table, connection.introspection.table_names(cursor))

    def assertTableNotExists(self, table):
        with connection.cursor() as cursor:
            self.assertNotIn(table, connection.introspection.table_names(cursor))


ue"), True)
        self.assertIs(cache.add("addkey1", "newvalue"), True)
        self.assertIsNone(cache.get("addkey1"))

    def test_non_existent(self):
        "Nonexistent keys aren't found in the dummy cache backend"
        self.assertIsNone(cache.get("does_not_exist"))
        self.assertEqual(cache.get("does_not_exist", "bang!"), "bang!")

    def test_get_many(self):
        "get_many returns nothing for the dummy cache backend"
        cache.set_many({"a": "a", "b": "b", "c": "c", "d": "d"})

        with self.assertWarnsMessage(CacheKeyWarning, msg):
            cache.get_many(["key with spaces"])

    def test_delete(self):
        "Cache deletion is transparently ignored on the dummy cache backend"
        cache.set_many({"key1": "spam", "ke

    self.assertEqual(cache.get_many(["a", "c", "d"]), {})
        self.assertEqual(cache.get_many(["a", "b", "e"]), {})

    def test_get_many_invalid_key(self):
        msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces"


ritanceTests(SimpleTestCase):
    def test_single_parent(self):
        class AbstractBase(models.Model):
            name = models.CharField(max_length=30)

            class Meta:
                abstract = True

        class AbstractDescendant(AbstractBase):
            name = models.CharField(max_length=50)

            class Meta:
                abstract = True

        class DerivedChild(AbstractBase):
            name = models.CharField(max_length=50)

        class DerivedGrandChild(AbstractDescen

._meta.get_field("name").max_length, 50)

    def test_multiple_inheritance_allows_inherited_field(self):
        """
        Single layer multiple inheritance is as expected, deriving the
        inherited field from the first base.
        """

        c

dant):
            pass

        self.assertEqual(AbstractDescendant._meta.get_field("name").max_length, 50)
        self.assertEqual(DerivedChild._meta.get_field("name").max_length, 50)
        self.assertEqual(DerivedGrandChild


self.assertEqual(memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb)
        self.assertEqual(memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb)

        # Redundant sanity check.
        self.assertEqual(4326, GEOSGeometry(hexewkb_2d).srid)

    def test_kml(self):
        "Testing KML output."
        for tg in self.geometries.wkt_out:
            geom = fromstr(tg.wkt)
            kml = getattr(tg, "kml", False)
            if kml:
                with self.subTest(tg=tg):
                    self.assertEqual(kml,

rtRaisesMessage((GEOSException, ValueError), err.msg),
            ):
                fromstr(err.wkt)

        # Bad WKB
        with self.assertRaisesMessage(
            GEOSException, self.error_checking_geom.format("GEOSWKBReader_read_r")
        ):

geom.kml)

    def test_errors(self):
        "Testing the Error handlers."
        # string-based
        for err in self.geometries.errors:
            with (
                self.subTest(err=err.wkt),
                self.asse


aaaaaaaaaaaaaa",
    "http://200.8.9.10/",
    "http://200.8.9.10:8000/test",
    "http://su--b.valid-----hyphens.com/",
    "http://example.com?something=value",
    "http://example.com/index.php?something=value&another=value2",
    "https://example.com/",
    "ftp://example.com/",
    "ftps://example.com/",
    "http://foo.com/blah_blah",
    "http://foo.com/blah_blah/",
    "http://foo.com/blah_blah_(wikipedia)",
    "http://foo.com/blah_blah_(wikipedia)_(again)",
    "http://www.example.com/wpstyle/?p=3

,
    "http://userid@example.com:65535",
    "http://userid@example.com:65535/",
    "http://userid:@example.com",
    "http://userid:@example.com/",
    "http://userid:@example.com:8080",
    "http://userid:@example.com:8080/",
    "http://userid:password

64",
    "https://www.example.com/foo/?bar=baz&inga=42&quux",
    "http://✪df.ws/123",
    "http://userid@example.com",
    "http://userid@example.com/",
    "http://userid@example.com:8080",
    "http://userid@example.com:8080/"


est

from forms_tests.widget_tests.base import WidgetTest

from django.db import connection
from django.test import SimpleTestCase, TestCase, modify_settings
from django.utils.functional import cached_property

@unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests")
# To register type handlers and locate the widget's template.
@modify_settings(INSTALLED_APPS={"append": "django.contrib.postgres"})
class PostgreSQLSimpleTestCase(SimpleTestCase):
    pass

@unittest.skipUnless(co

:
    @cached_property
    def default_text_search_config(self):
        with connection.cursor() as cursor:
            cursor.execute("SHOW default_text_search_config")
            row = cursor.fetchone()
            return row[0] if row else None

    d

nnection.vendor == "postgresql", "PostgreSQL specific tests")
# To register type handlers and locate the widget's template.
@modify_settings(INSTALLED_APPS={"append": "django.contrib.postgres"})
class PostgreSQLTestCase(TestCase)


t admin

from .models import (
    Advisor,
    Album,
    Band,
    Bee,
    Car,
    CarTire,
    Event,
    Inventory,
    Member,
    Profile,
    ReleaseEvent,
    School,
    Student,
    User,
    VideoStream,
)

class WidgetAdmin(admin.AdminSite):
    pass

class CarAdmin(admin.ModelAdmin):
    list_display = ["make", "model", "owner"]
    list_editable = ["owner"]

class CarTireAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name

in.ModelAdmin):
    raw_id_fields = ["main_band", "supporting_bands"]

class AlbumAdmin(admin.ModelAdmin):
    fields = (
        "name",
        "cover_art",
    )
    readonly_fields = ("cover_art",)

class SchoolAdmin(admin.ModelAdmin):
    filter_ver

== "car":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
            return db_field.formfield(**kwargs)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

class EventAdmin(adm


 Variable, VariableDoesNotExist
from django.test import SimpleTestCase

class VariableResolveLoggingTests(SimpleTestCase):
    loglevel = logging.DEBUG

    def test_log_on_variable_does_not_exist_silent(self):
        class TestObject:
            class SilentDoesNotExist(Exception):
                silent_variable_failure = True

            @property
            def template_name(self):
                return "template_name"

            @property
            def template(self):
                return E

 in dir(TestObject) if attr[:2] != "__")

            def __getitem__(self, item):
                return self.__dict__[item]

        with self.assertLogs("django.template", self.loglevel) as cm:
            Variable("article").resolve(TestObject())

ngine().from_string("")

            @property
            def article(self):
                raise TestObject.SilentDoesNotExist("Attribute does not exist.")

            def __iter__(self):
                return (attr for attr


ultfilters import length
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe

from ..utils import setup

class LengthTests(SimpleTestCase):
    @setup({"length01": "{{ list|length }}"})
    def test_length01(self):
        output = self.engine.render_to_string(
            "length01", {"list": ["4", None, True, {}]}
        )
        self.assertEqual(output, "4")

    @setup({"length02": "{{ list|length }}"})
    def test_length02(self):
        output = self.engine.render_

     self.assertEqual(output, "0")

    @setup({"length04": "{{ string|length }}"})
    def test_length04(self):
        output = self.engine.render_to_string("length04", {"string": "django"})
        self.assertEqual(output, "6")

    @setup({"length05":

to_string("length02", {"list": []})
        self.assertEqual(output, "0")

    @setup({"length03": "{{ string|length }}"})
    def test_length03(self):
        output = self.engine.render_to_string("length03", {"string": ""})


ks_filter
from django.test import SimpleTestCase
from django.utils.functional import lazy
from django.utils.safestring import mark_safe

from ..utils import setup

class LinebreaksTests(SimpleTestCase):
    """
    The contents in "linebreaks" are escaped according to the current
    autoescape setting.
    """

    @setup({"linebreaks01": "{{ a|linebreaks }} {{ b|linebreaks }}"})
    def test_linebreaks01(self):
        output = self.engine.render_to_string(
            "linebreaks01", {"a": "x&\ny", "b":

                "{% endautoescape %}"
            )
        }
    )
    def test_linebreaks02(self):
        output = self.engine.render_to_string(
            "linebreaks02", {"a": "x&\ny", "b": mark_safe("x&\ny")}
        )
        self.assertEqual(outp

mark_safe("x&\ny")}
        )
        self.assertEqual(output, "
x&
y

x&
y
")

    @setup(
        {
            "linebreaks02": (
                "{% autoescape off %}{{ a|linebreaks }} {{ b|linebreaks }}"


ultfilters import linebreaksbr
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe

from ..utils import setup

class LinebreaksbrTests(SimpleTestCase):
    """
    The contents in "linebreaksbr" are escaped according to the current
    autoescape setting.
    """

    @setup({"linebreaksbr01": "{{ a|linebreaksbr }} {{ b|linebreaksbr }}"})
    def test_linebreaksbr01(self):
        output = self.engine.render_to_string(
            "linebreaksbr01", {"a": "x&\ny", "b": mark_

   "{% endautoescape %}"
            )
        }
    )
    def test_linebreaksbr02(self):
        output = self.engine.render_to_string(
            "linebreaksbr02", {"a": "x&\ny", "b": mark_safe("x&\ny")}
        )
        self.assertEqual(output, "x&<br

safe("x&\ny")}
        )
        self.assertEqual(output, "x&
y x&
y")

    @setup(
        {
            "linebreaksbr02": (
                "{% autoescape off %}{{ a|linebreaksbr }} {{ b|linebreaksbr }}"


ers
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe

from ..utils import setup

class LinenumbersTests(SimpleTestCase):
    """
    The contents of "linenumbers" is escaped according to the current
    autoescape setting.
    """

    @setup({"linenumbers01": "{{ a|linenumbers }} {{ b|linenumbers }}"})
    def test_linenumbers01(self):
        output = self.engine.render_to_string(
            "linenumbers01",
            {"a": "one\n<two>\nthree", "b": mark_safe("one\n

% autoescape off %}{{ a|linenumbers }} {{ b|linenumbers }}"
                "{% endautoescape %}"
            )
        }
    )
    def test_linenumbers02(self):
        output = self.engine.render_to_string(
            "linenumbers02",
            {"a":

<two>\nthree")},
        )
        self.assertEqual(
            output, "1. one\n2. <two>\n3. three 1. one\n2. <two>\n3. three"
        )

    @setup(
        {
            "linenumbers02": (
                "{


jango.template.defaultfilters import ljust
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe

from ..utils import setup

class LjustTests(SimpleTestCase):
    @setup(
        {
            "ljust01": (
                '{% autoescape off %}.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.'
                "{% endautoescape %}"
            )
        }
    )
    def test_ljust01(self):
        output = self.engine.render_to_string(
            "ljust01", {"a": "a&b", "b": mark_safe("a

02", {"a": "a&b", "b": mark_safe("a&b")}
        )
        self.assertEqual(output, ".a&b  . .a&b  .")

class FunctionTests(SimpleTestCase):
    def test_ljust(self):
        self.assertEqual(ljust("test", 10), "test      ")
        self.assertEqual(l

&b")}
        )
        self.assertEqual(output, ".a&b  . .a&b  .")

    @setup({"ljust02": '.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.'})
    def test_ljust02(self):
        output = self.engine.render_to_string(
            "ljust


jango.template.defaultfilters import lower
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe

from ..utils import setup

class LowerTests(SimpleTestCase):
    @setup(
        {
            "lower01": (
                "{% autoescape off %}{{ a|lower }} {{ b|lower }}{% endautoescape %}"
            )
        }
    )
    def test_lower01(self):
        output = self.engine.render_to_string(
            "lower01", {"a": "Apple & banana", "b": mark_safe("Apple & banana")}

r02", {"a": "Apple & banana", "b": mark_safe("Apple & banana")}
        )
        self.assertEqual(output, "apple & banana apple & banana")

class FunctionTests(SimpleTestCase):
    def test_lower(self):
        self.assertEqual(lower("TEST"),

        )
        self.assertEqual(output, "apple & banana apple & banana")

    @setup({"lower02": "{{ a|lower }} {{ b|lower }}"})
    def test_lower02(self):
        output = self.engine.render_to_string(
            "lowe


ultfilters import make_list
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe

from ..utils import setup

class MakeListTests(SimpleTestCase):
    """
    The make_list filter can destroy existing escaping, so the results are
    escaped.
    """

    @setup({"make_list01": "{% autoescape off %}{{ a|make_list }}{% endautoescape %}"})
    def test_make_list01(self):
        output = self.engine.render_to_string("make_list01", {"a": mark_safe("&")})
        self.assertEqual

;']")

    @setup(
        {
            "make_list03": (
                '{% autoescape off %}{{ a|make_list|stringformat:"s"|safe }}'
                "{% endautoescape %}"
            )
        }
    )
    def test_make_list03(self):
        output

(output, "['&']")

    @setup({"make_list02": "{{ a|make_list }}"})
    def test_make_list02(self):
        output = self.engine.render_to_string("make_list02", {"a": mark_safe("&")})
        self.assertEqual(output, "['&amp


ultfilters import phone2numeric_filter
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe

from ..utils import setup

class Phone2numericTests(SimpleTestCase):
    @setup({"phone2numeric01": "{{ a|phone2numeric }} {{ b|phone2numeric }}"})
    def test_phone2numeric01(self):
        output = self.engine.render_to_string(
            "phone2numeric01",
            {"a": "<1-800-call-me>", "b": mark_safe("<1-800-call-me>")},
        )
        self.assertEqual(output, "<1-8

  }
    )
    def test_phone2numeric02(self):
        output = self.engine.render_to_string(
            "phone2numeric02",
            {"a": "<1-800-call-me>", "b": mark_safe("<1-800-call-me>")},
        )
        self.assertEqual(output, "<1-800-2255-63>

00-2255-63> <1-800-2255-63>")

    @setup(
        {
            "phone2numeric02": (
                "{% autoescape off %}{{ a|phone2numeric }} {{ b|phone2numeric }}"
                "{% endautoescape %}"
            )


efaultfilters import pluralize
from django.test import SimpleTestCase

from ..utils import setup

class PluralizeTests(SimpleTestCase):
    def check_values(self, *tests):
        for value, expected in tests:
            with self.subTest(value=value):
                output = self.engine.render_to_string("t", {"value": value})
                self.assertEqual(output, expected)

    @setup({"t": "vote{{ value|pluralize }}"})
    def test_no_arguments(self):
        self.check_values(("0", "votes"), ("1",

ies" }}'})
    def test_singular_and_plural_suffix(self):
        self.check_values(("0", "candies"), ("1", "candy"), ("2", "candies"))

class FunctionTests(SimpleTestCase):
    def test_integers(self):
        self.assertEqual(pluralize(1), "")
        s

"vote"), ("2", "votes"))

    @setup({"t": 'class{{ value|pluralize:"es" }}'})
    def test_suffix(self):
        self.check_values(("0", "classes"), ("1", "class"), ("2", "classes"))

    @setup({"t": 'cand{{ value|pluralize:"y,


from django.test import SimpleTestCase
from django.utils.safestring import mark_safe

from ..utils import setup

class RandomTests(SimpleTestCase):
    @setup({"random01": "{{ a|random }} {{ b|random }}"})
    def test_random01(self):
        output = self.engine.render_to_string(
            "random01", {"a": ["a&b", "a&b"], "b": [mark_safe("a&b"), mark_safe("a&b")]}
        )
        self.assertEqual(output, "a&b a&b")

    @setup(
        {
            "random02": (
                "{% autoescape of

 mark_safe("a&b")]}
        )
        self.assertEqual(output, "a&b a&b")

    @setup({"empty_list": "{{ list|random }}"})
    def test_empty_list(self):
        output = self.engine.render_to_string("empty_list", {"list": []})
        self.assertEqual(out

f %}{{ a|random }} {{ b|random }}{% endautoescape %}"
            )
        }
    )
    def test_random02(self):
        output = self.engine.render_to_string(
            "random02", {"a": ["a&b", "a&b"], "b": [mark_safe("a&b"),


jango.template.defaultfilters import rjust
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe

from ..utils import setup

class RjustTests(SimpleTestCase):
    @setup(
        {
            "rjust01": (
                '{% autoescape off %}.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.'
                "{% endautoescape %}"
            )
        }
    )
    def test_rjust01(self):
        output = self.engine.render_to_string(
            "rjust01", {"a": "a&b", "b": mark_safe("a

02", {"a": "a&b", "b": mark_safe("a&b")}
        )
        self.assertEqual(output, ".  a&b. .  a&b.")

class FunctionTests(SimpleTestCase):
    def test_rjust(self):
        self.assertEqual(rjust("test", 10), "      test")

    def test_less_than_st

&b")}
        )
        self.assertEqual(output, ".  a&b. .  a&b.")

    @setup({"rjust02": '.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.'})
    def test_rjust02(self):
        output = self.engine.render_to_string(
            "rjust


ultfilters import slice_filter
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe

from ..utils import setup

class SliceTests(SimpleTestCase):
    @setup({"slice01": '{{ a|slice:"1:3" }} {{ b|slice:"1:3" }}'})
    def test_slice01(self):
        output = self.engine.render_to_string(
            "slice01", {"a": "a&b", "b": mark_safe("a&b")}
        )
        self.assertEqual(output, "&b &b")

    @setup(
        {
            "slice02": (
                '{% autoesca

"b": mark_safe("a&b")}
        )
        self.assertEqual(output, "&b &b")

class FunctionTests(SimpleTestCase):
    def test_zero_length(self):
        self.assertEqual(slice_filter("abcdefg", "0"), "")

    def test_index(self):
        self.assertEqual

pe off %}{{ a|slice:"1:3" }} {{ b|slice:"1:3" }}'
                "{% endautoescape %}"
            )
        }
    )
    def test_slice02(self):
        output = self.engine.render_to_string(
            "slice02", {"a": "a&b",


ultfilters import slugify
from django.test import SimpleTestCase
from django.utils.functional import lazy
from django.utils.safestring import mark_safe

from ..utils import setup

class SlugifyTests(SimpleTestCase):
    """
    Running slugify on a pre-escaped string leads to odd behavior,
    but the result is still safe.
    """

    @setup(
        {
            "slugify01": (
                "{% autoescape off %}{{ a|slugify }} {{ b|slugify }}{% endautoescape %}"
            )
        }
    )
    def t

ugify }} {{ b|slugify }}"})
    def test_slugify02(self):
        output = self.engine.render_to_string(
            "slugify02", {"a": "a & b", "b": mark_safe("a & b")}
        )
        self.assertEqual(output, "a-b a-amp-b")

class FunctionTests(Si

est_slugify01(self):
        output = self.engine.render_to_string(
            "slugify01", {"a": "a & b", "b": mark_safe("a & b")}
        )
        self.assertEqual(output, "a-b a-amp-b")

    @setup({"slugify02": "{{ a|sl


ultfilters import stringformat
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe

from ..utils import setup

class StringformatTests(SimpleTestCase):
    """
    Notice that escaping is applied *after* any filters, so the string
    formatting here only needs to deal with pre-escaped characters.
    """

    @setup(
        {
            "stringformat01": (
                '{% autoescape off %}.{{ a|stringformat:"5s" }}. .'
                '{{ b|stringformat:"5s" }}.{% en

output, ".  a<b. .  a<b.")

    @setup(
        {"stringformat02": '.{{ a|stringformat:"5s" }}. .{{ b|stringformat:"5s" }}.'}
    )
    def test_stringformat02(self):
        output = self.engine.render_to_string(
            "stringformat02", {"a": "a<b",

dautoescape %}'
            )
        }
    )
    def test_stringformat01(self):
        output = self.engine.render_to_string(
            "stringformat01", {"a": "a<b", "b": mark_safe("a<b")}
        )
        self.assertEqual(


ultfilters import striptags
from django.test import SimpleTestCase
from django.utils.functional import lazystr
from django.utils.safestring import mark_safe

from ..utils import setup

class StriptagsTests(SimpleTestCase):
    @setup({"striptags01": "{{ a|striptags }} {{ b|striptags }}"})
    def test_striptags01(self):
        output = self.engine.render_to_string(
            "striptags01",
            {
                "a": "x
y
",
                "b": mark_safe("x
y

oescape %}"
            )
        }
    )
    def test_striptags02(self):
        output = self.engine.render_to_string(
            "striptags02",
            {
                "a": "x
y
",
                "b": mark_safe("x
<

</p>"),
            },
        )
        self.assertEqual(output, "x y x y")

    @setup(
        {
            "striptags02": (
                "{% autoescape off %}{{ a|striptags }} {{ b|striptags }}"
                "{% endaut


aultfilters import time as time_filter
from django.test import SimpleTestCase
from django.utils import timezone, translation

from ..utils import setup
from .timezone_utils import TimezoneTestCase

class TimeTests(TimezoneTestCase):
    """
    #20693: Timezone support for the time template filter
    """

    @setup({"time00": "{{ dt|time }}"})
    def test_time00(self):
        output = self.engine.render_to_string("time00", {"dt": time(16, 25)})
        self.assertEqual(output, "4:25 p.m.")

    @setup(

6:25")

    @setup({"time01": '{{ dt|time:"e:O:T:Z" }}'})
    def test_time01(self):
        output = self.engine.render_to_string("time01", {"dt": self.now_tz_i})
        self.assertEqual(output, "+0315:+0315:+0315:11700")

    @setup({"time02": '{{ dt|ti

{"time00_l10n": "{{ dt|time }}"})
    def test_time00_l10n(self):
        with translation.override("fr"):
            output = self.engine.render_to_string("time00_l10n", {"dt": time(16, 25)})
        self.assertEqual(output, "1


 import setup
from .timezone_utils import TimezoneTestCase

class TimesinceTests(TimezoneTestCase):
    """
    #20246 - \xa0 in output avoids line-breaks between value and unit
    """

    # Default compare with datetime.now()
    @setup({"timesince01": "{{ a|timesince }}"})
    def test_timesince01(self):
        output = self.engine.render_to_string(
            "timesince01", {"a": datetime.now() + timedelta(minutes=-1, seconds=-10)}
        )
        self.assertEqual(output, "1\xa0minute")

    @setu

qual(output, "1\xa0day")

    @setup({"timesince03": "{{ a|timesince }}"})
    def test_timesince03(self):
        output = self.engine.render_to_string(
            "timesince03",
            {"a": datetime.now() - timedelta(hours=1, minutes=25, seconds=1

p({"timesince02": "{{ a|timesince }}"})
    def test_timesince02(self):
        output = self.engine.render_to_string(
            "timesince02", {"a": datetime.now() - timedelta(days=1, minutes=1)}
        )
        self.assertE


 import setup
from .timezone_utils import TimezoneTestCase

class TimeuntilTests(TimezoneTestCase):
    # Default compare with datetime.now()
    @setup({"timeuntil01": "{{ a|timeuntil }}"})
    def test_timeuntil01(self):
        output = self.engine.render_to_string(
            "timeuntil01", {"a": datetime.now() + timedelta(minutes=2, seconds=10)}
        )
        self.assertEqual(output, "2\xa0minutes")

    @setup({"timeuntil02": "{{ a|timeuntil }}"})
    def test_timeuntil02(self):
        output =

st_timeuntil03(self):
        output = self.engine.render_to_string(
            "timeuntil03",
            {"a": (datetime.now() + timedelta(hours=8, minutes=10, seconds=10))},
        )
        self.assertEqual(output, "8\xa0hours, 10\xa0minutes")

    #

 self.engine.render_to_string(
            "timeuntil02", {"a": (datetime.now() + timedelta(days=1, seconds=10))}
        )
        self.assertEqual(output, "1\xa0day")

    @setup({"timeuntil03": "{{ a|timeuntil }}"})
    def te


 import title
from django.test import SimpleTestCase

from ..utils import setup

class TitleTests(SimpleTestCase):
    @setup({"title1": "{{ a|title }}"})
    def test_title1(self):
        output = self.engine.render_to_string("title1", {"a": "JOE'S CRAB SHACK"})
        self.assertEqual(output, "Joe's Crab Shack")

    @setup({"title2": "{{ a|title }}"})
    def test_title2(self):
        output = self.engine.render_to_string("title2", {"a": "555 WEST 53RD STREET"})
        self.assertEqual(output,

TestCase):
    def test_title(self):
        self.assertEqual(title("a nice title, isn't it?"), "A Nice Title, Isn't It?")

    def test_unicode(self):
        self.assertEqual(title("discoth\xe8que"), "Discoth\xe8que")

    def test_non_string_input(self)

"555 West 53rd Street")

class FunctionTests(Simple