n

from .base import WidgetTest

class NullBooleanSelectTest(WidgetTest):
    widget = NullBooleanSelect()

    def test_render_true(self):
        self.check_html(
            self.widget,
            "is_cool",
            True,
            html=("""<select name="is_cool">
            <option value="unknown">Unknown</option>
            <option value="true" selected>Yes</option>
            <option value="false">No</option>
            </select>"""),
        )

    def test_render_false(self):
        se

         <option value="false" selected>No</option>
            </select>"""),
        )

    def test_render_none(self):
        self.check_html(
            self.widget,
            "is_cool",
            None,
            html=("""<select name="is_cool"

lf.check_html(
            self.widget,
            "is_cool",
            False,
            html=("""<select name="is_cool">
            <option value="unknown">Unknown</option>
            <option value="true">Yes</option>


rom django.forms import CharField, Form, NumberInput
from django.test import override_settings

from .base import WidgetTest

class NumberInputTests(WidgetTest):
    widget = NumberInput(attrs={"max": 12345, "min": 1234, "step": 9999})

    @override_settings(USE_THOUSAND_SEPARATOR=True)
    def test_attrs_not_localized(self):
        self.check_html(
            self.widget,
            "name",
            "value",
            '<input type="number" name="name" value="value" max="12345" min="1234" '

self.assertIs(self.widget.use_fieldset, False)
        self.assertHTMLEqual(
            '
Field:'
            '<input id="id_field" max="12345" min="1234" '
            'name="field" required step="9999" type="num

      'step="9999">',
        )

    def test_fieldset(self):
        class TestForm(Form):
            template_name = "forms_tests/use_fieldset.html"
            field = CharField(widget=self.widget)

        form = TestForm()


CharField, Form, PasswordInput

from .base import WidgetTest

class PasswordInputTest(WidgetTest):
    widget = PasswordInput()

    def test_render(self):
        self.check_html(
            self.widget, "password", "", html='<input type="password" name="password">'
        )

    def test_render_ignore_value(self):
        self.check_html(
            self.widget,
            "password",
            "secret",
            html='<input type="password" name="password">',
        )

    def test_render_valu

e=True)
        self.check_html(
            widget, "password", "", html='<input type="password" name="password">'
        )
        self.check_html(
            widget, "password", None, html='<input type="password" name="password">'
        )
        se

e_true(self):
        """
        The render_value argument lets you specify whether the widget should
        render its value. For security reasons, this is off by default.
        """
        widget = PasswordInput(render_valu


def test_render(self):
        html = """

            <input type="radio" name="beatle" value="">
              - Select an option -

            <input checked type="radio" name="beatle" value="J">John

            <input type="radio" name="beatle" value="P">Paul

            <input type="radio" name="beatle" val

les
        for choices in (beatles_with_blank, dict(beatles_with_blank)):
            with self.subTest(choices):
                self.check_html(self.widget(choices=choices), "beatle", "J", html=html)

    def test_nested_choices(self):
        nested_ch

ue="G">George

            <input type="radio" name="beatle" value="R">Ringo

        """
        beatles_with_blank = BLANK_CHOICE + self.beat


ption>
          <option value="P">Paul</option>
          <option value="G">George</option>
          <option value="R">Ringo</option>
        </select>
        """
        for choices in (self.beatles, dict(self.beatles)):
            with self.subTest(choices):
                self.check_html(self.widget(choices=choices), "beatle", "J", html=html)

    def test_render_none(self):
        """
        If the value is None, none of the options are selected.
        """
        self.check_html(
            s

ue="G">George</option>
            <option value="R">Ringo</option>
            </select>"""),
        )

    def test_render_label_value(self):
        """
        If the value corresponds to a label (but not to an option value), none
        of the optio

elf.widget(choices=self.beatles),
            "beatle",
            None,
            html=("""<select name="beatle">
            <option value="J">John</option>
            <option value="P">Paul</option>
            <option val


             <option selected value="">---</option>
                <option value="1">January</option>
                <option value="2">February</option>
                <option value="3">March</option>
                <option value="4">April</option>
                <option value="5">May</option>
                <option value="6">June</option>
                <option value="7">July</option>
                <option value="8">August</option>
                <option value="9">September</option>

             <option selected value="">---</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                <option

   <option value="10">October</option>
                <option value="11">November</option>
                <option value="12">December</option>
            </select>

            <select name="mydate_day" id="id_mydate_day">


("2", "2"), ("3", "3"), ("0", "extra"))

    def test_format_value(self):
        widget = self.widget(choices=self.numeric_choices)
        self.assertEqual(widget.format_value(None), [])
        self.assertEqual(widget.format_value(""), [""])
        self.assertEqual(widget.format_value([3, 0, 1]), ["3", "0", "1"])

    def test_render_selected(self):
        self.check_html(
            self.widget(choices=self.beatles),
            "beatles",
            ["J"],
            html=("""<select multiple name

      )

    def test_render_multiple_selected(self):
        self.check_html(
            self.widget(choices=self.beatles),
            "beatles",
            ["J", "P"],
            html=("""<select multiple name="beatles">
            <option value="J"

="beatles">
            <option value="J" selected>John</option>
            <option value="P">Paul</option>
            <option value="G">George</option>
            <option value="R">Ringo</option>
            </select>"""),


eTimeWidget

from .base import WidgetTest

class SplitDateTimeWidgetTest(WidgetTest):
    widget = SplitDateTimeWidget()

    def test_render_empty(self):
        self.check_html(
            self.widget,
            "date",
            "",
            html=('<input type="text" name="date_0"><input type="text" name="date_1">'),
        )

    def test_render_none(self):
        self.check_html(
            self.widget,
            "date",
            None,
            html=('<input type="text" name="date_0

    '<input type="text" name="date_0" value="2006-01-10">'
                '<input type="text" name="date_1" value="07:30:00">'
            ),
        )

    def test_render_date_and_time(self):
        self.check_html(
            self.widget,

"><input type="text" name="date_1">'),
        )

    def test_render_datetime(self):
        self.check_html(
            self.widget,
            "date",
            datetime(2006, 1, 10, 7, 30),
            html=(


idget
from django.utils import translation

from .base import WidgetTest

class SplitHiddenDateTimeWidgetTest(WidgetTest):
    widget = SplitHiddenDateTimeWidget()

    def test_render_empty(self):
        self.check_html(
            self.widget,
            "date",
            "",
            html=(
                '<input type="hidden" name="date_0"><input type="hidden" name="date_1">'
            ),
        )

    def test_render_value(self):
        d = datetime(2007, 9, 17, 12, 51, 34, 482548)

  self.check_html(
            self.widget,
            "date",
            d,
            html=(
                '<input type="hidden" name="date_0" value="2007-09-17">'
                '<input type="hidden" name="date_1" value=


from django.utils.safestring import mark_safe

from .base import WidgetTest

class TextareaTest(WidgetTest):
    widget = Textarea()

    def test_render(self):
        self.check_html(
            self.widget,
            "msg",
            "value",
            html=('<textarea rows="10" cols="40" name="msg">value</textarea>'),
        )

    def test_render_required(self):
        widget = Textarea()
        widget.is_required = True
        self.check_html(
            widget,
            "msg",

    html='<textarea rows="10" cols="40" name="msg"></textarea>',
        )

    def test_render_none(self):
        self.check_html(
            self.widget,
            "msg",
            None,
            html='<textarea rows="10" cols="40" name="msg"></

     "value",
            html='<textarea rows="10" cols="40" name="msg">value</textarea>',
        )

    def test_render_empty(self):
        self.check_html(
            self.widget,
            "msg",
            "",


m .base import WidgetTest

class TextInputTest(WidgetTest):
    widget = TextInput()

    def test_render(self):
        self.check_html(
            self.widget, "email", "", html='<input type="text" name="email">'
        )

    def test_render_none(self):
        self.check_html(
            self.widget, "email", None, html='<input type="text" name="email">'
        )

    def test_render_value(self):
        self.check_html(
            self.widget,
            "email",
            "test@example.com",

     """
        self.check_html(
            self.widget,
            "get_spam",
            False,
            html=('<input type="text" name="get_spam" value="False">'),
        )
        self.check_html(
            self.widget,
            "get_spam"

            html=('<input type="text" name="email" value="test@example.com">'),
        )

    def test_render_boolean(self):
        """
        Boolean values are rendered to their string forms ("True" and
        "False").


 CharField, Form, TimeInput
from django.utils import translation

from .base import WidgetTest

class TimeInputTest(WidgetTest):
    widget = TimeInput()

    def test_render_none(self):
        self.check_html(
            self.widget, "time", None, html='<input type="text" name="time">'
        )

    def test_render_value(self):
        """
        The microseconds are trimmed on display, by default.
        """
        t = time(12, 51, 34, 482548)
        self.assertEqual(str(t), "12:51:34.482548")

,
            time(12, 51, 34),
            html=('<input type="text" name="time" value="12:51:34">'),
        )
        self.check_html(
            self.widget,
            "time",
            time(12, 51),
            html=('<input type="text" name="tim

     self.check_html(
            self.widget,
            "time",
            t,
            html='<input type="text" name="time" value="12:51:34">',
        )
        self.check_html(
            self.widget,
            "time"


m django.forms import Widget
from django.forms.widgets import Input

from .base import WidgetTest

class WidgetTests(WidgetTest):
    def test_format_value(self):
        widget = Widget()
        self.assertIsNone(widget.format_value(None))
        self.assertIsNone(widget.format_value(""))
        self.assertEqual(widget.format_value("español"), "español")
        self.assertEqual(widget.format_value(42.5), "42.5")

    def test_value_omitted_from_data(self):
        widget = Widget()
        self.assert

   self.check_html(
            Input(),
            "name",
            "value",
            strict=True,
            html='<input type="None" name="name" value="value">',
        )

    def test_attr_false_not_rendered(self):
        html = '<input type=

Is(widget.value_omitted_from_data({}, {}, "field"), True)
        self.assertIs(
            widget.value_omitted_from_data({"field": "value"}, {}, "field"), False
        )

    def test_no_trailing_newline_in_attrs(self):


forms import ChoiceField, Field, Form, Select
from django.test import SimpleTestCase

class BasicFieldsTests(SimpleTestCase):
    def test_field_sets_widget_is_required(self):
        self.assertTrue(Field(required=True).widget.is_required)
        self.assertFalse(Field(required=False).widget.is_required)

    def test_cooperative_multiple_inheritance(self):
        class A:
            def __init__(self):
                self.class_a_var = True
                super().__init__()

        class ComplexFie

ield(ChoiceField):
            widget = Select(attrs={"class": "my-custom-class"})

        class TestForm(Form):
            field1 = CustomChoiceField(choices=[])
            field2 = CustomChoiceField(choices=[])

        f = TestForm()
        f.fields

ld(Field, A):
            def __init__(self):
                super().__init__()

        f = ComplexField()
        self.assertTrue(f.class_a_var)

    def test_field_deepcopies_widget_instance(self):
        class CustomChoiceF


alidationError
from django.forms import BooleanField
from django.test import SimpleTestCase

class BooleanFieldTest(SimpleTestCase):
    def test_booleanfield_clean_1(self):
        f = BooleanField()
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean("")
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean(None)
        self.assertTrue(f.clean(True))
        with self.assertRaisesMessage(ValidationErr

f.clean("Django rocks"))
        self.assertTrue(f.clean("True"))
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean("False")

    def test_booleanfield_clean_2(self):
        f = BooleanField(required=

or, "'This field is required.'"):
            f.clean(False)
        self.assertTrue(f.clean(1))
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean(0)
        self.assertTrue(


ionsMixin

class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
    def test_charfield_1(self):
        f = CharField()
        self.assertEqual("1", f.clean(1))
        self.assertEqual("hello", f.clean("hello"))
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean(None)
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean("")
        self.assertEqual("[1, 2, 3]", f.clean([1, 2, 3]))
        s

llo"))
        self.assertEqual("", f.clean(None))
        self.assertEqual("", f.clean(""))
        self.assertEqual("[1, 2, 3]", f.clean([1, 2, 3]))
        self.assertIsNone(f.max_length)
        self.assertIsNone(f.min_length)

    def test_charfield_3

elf.assertIsNone(f.max_length)
        self.assertIsNone(f.min_length)

    def test_charfield_2(self):
        f = CharField(required=False)
        self.assertEqual("1", f.clean(1))
        self.assertEqual("hello", f.clean("he


class ChoiceFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
    def test_choicefield_1(self):
        f = ChoiceField(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"))
        msg = "'Select a valid choice. 3 is n

lse)
        self.assertEqual("", f.clean(""))
        self.assertEqual("", f.clean(None))
        self.assertEqual("1", f.clean(1))
        self.assertEqual("1", f.clean("1"))
        msg = "'Select a valid choice. 3 is not one of the available choices.'"

ot one of the available choices.'"
        with self.assertRaisesMessage(ValidationError, msg):
            f.clean("3")

    def test_choicefield_2(self):
        f = ChoiceField(choices=[("1", "One"), ("2", "Two")], required=Fa


ns import ValidationError
from django.forms import CharField, ComboField, EmailField
from django.test import SimpleTestCase

class ComboFieldTest(SimpleTestCase):
    def test_combofield_1(self):
        f = ComboField(fields=[CharField(max_length=20), EmailField()])
        self.assertEqual("test@example.com", f.clean("test@example.com"))
        with self.assertRaisesMessage(
            ValidationError,
            "'Ensure this value has at most 20 characters (it has 28).'",
        ):
            f.cl

ionError, "'This field is required.'"):
            f.clean("")
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean(None)

    def test_combofield_2(self):
        f = ComboField(fields=[CharField(max_le

ean("longemailaddress@example.com")
        with self.assertRaisesMessage(
            ValidationError, "'Enter a valid email address.'"
        ):
            f.clean("not an email")
        with self.assertRaisesMessage(Validat


tCase
from django.utils import translation

class GetDate(Form):
    mydate = DateField(widget=SelectDateWidget)

class DateFieldTest(SimpleTestCase):
    def test_form_field(self):
        a = GetDate({"mydate_month": "4", "mydate_day": "1", "mydate_year": "2008"})
        self.assertTrue(a.is_valid())
        self.assertEqual(a.cleaned_data["mydate"], date(2008, 4, 1))

        # As with any widget that implements get_value_from_datadict(), we must
        # accept the input from the "as_hidden" renderi

lf.assertTrue(b.is_valid())
        self.assertEqual(b.cleaned_data["mydate"], date(2008, 4, 1))

        # Invalid dates shouldn't be allowed
        c = GetDate({"mydate_month": "2", "mydate_day": "31", "mydate_year": "2010"})
        self.assertFalse(c.

ng as well.
        self.assertHTMLEqual(
            a["mydate"].as_hidden(),
            '<input type="hidden" name="mydate" value="2008-04-01" id="id_mydate">',
        )

        b = GetDate({"mydate": "2008-4-1"})
        se


4, decimal_places=2)
        self.assertWidgetRendersTo(
            f, '<input id="id_f" step="0.01" type="number" name="f" required>'
        )
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean("")
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean(None)
        self.assertEqual(f.clean("1"), decimal.Decimal("1"))
        self.assertIsInstance(f.clean("1"), decimal.Decimal)
        self.assertEqual

 decimal.Decimal("3.14"))
        self.assertEqual(f.clean("1.0 "), decimal.Decimal("1.0"))
        self.assertEqual(f.clean(" 1.0"), decimal.Decimal("1.0"))
        self.assertEqual(f.clean(" 1.0 "), decimal.Decimal("1.0"))
        with self.assertRaisesM

(f.clean("23"), decimal.Decimal("23"))
        self.assertEqual(f.clean("3.14"), decimal.Decimal("3.14"))
        self.assertEqual(f.clean(3.14), decimal.Decimal("3.14"))
        self.assertEqual(f.clean(decimal.Decimal("3.14")),


ield
from django.test import SimpleTestCase
from django.utils import translation
from django.utils.duration import duration_string

from . import FormFieldAssertionsMixin

class DurationFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
    def test_durationfield_clean(self):
        f = DurationField()
        self.assertEqual(datetime.timedelta(seconds=30), f.clean("30"))
        self.assertEqual(datetime.timedelta(minutes=15, seconds=30), f.clean("15:30"))
        self.assertEqual(
            datetim

     f.clean("1 1:15:30.3"),
        )
        self.assertEqual(
            datetime.timedelta(0, 10800),
            f.clean(datetime.timedelta(0, 10800)),
        )
        msg = "This field is required."
        with self.assertRaisesMessage(Validation

e.timedelta(hours=1, minutes=15, seconds=30), f.clean("1:15:30")
        )
        self.assertEqual(
            datetime.timedelta(
                days=1, hours=1, minutes=15, seconds=30, milliseconds=300
            ),


t import SimpleTestCase

from . import FormFieldAssertionsMixin

class EmailFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
    def test_emailfield_1(self):
        f = EmailField()
        self.assertEqual(f.max_length, 320)
        self.assertWidgetRendersTo(
            f, '<input type="email" name="f" id="id_f" maxlength="320" required>'
        )
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean("")
        with self.assertRaisesMessage(Valid

 email address.'"
        ):
            f.clean("foo")
        self.assertEqual(
            "local@domain.with.idn.xyz\xe4\xf6\xfc\xdfabc.part.com",
            f.clean("local@domain.with.idn.xyzäöüßabc.part.com"),
        )

    def test_email_regexp_fo

ationError, "'This field is required.'"):
            f.clean(None)
        self.assertEqual("person@example.com", f.clean("person@example.com"))
        with self.assertRaisesMessage(
            ValidationError, "'Enter a valid


sion
from django.forms import FileField, FileInput
from django.test import SimpleTestCase

try:
    from PIL import Image  # NOQA
except ImportError:
    HAS_PILLOW = False
else:
    HAS_PILLOW = True

class FileFieldTest(SimpleTestCase):
    def test_filefield_1(self):
        f = FileField()
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean("")
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean(""

e(ValidationError, "'This field is required.'"):
            f.clean(None, "")
        self.assertEqual("files/test2.pdf", f.clean(None, "files/test2.pdf"))
        no_file_msg = "'No file was submitted. Check the encoding type on the form.'"
        file

, "")
        self.assertEqual("files/test1.pdf", f.clean("", "files/test1.pdf"))
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean(None)
        with self.assertRaisesMessag


mport FilePathField
from django.test import SimpleTestCase

PATH = os.path.dirname(os.path.abspath(__file__))

def fix_os_paths(x):
    if isinstance(x, str):
        return x.removeprefix(PATH).replace("\\", "/")
    elif isinstance(x, tuple):
        return tuple(fix_os_paths(list(x)))
    elif isinstance(x, list):
        return [fix_os_paths(y) for y in x]
    else:
        return x

class FilePathFieldTest(SimpleTestCase):
    expected_choices = [
        ("/filepathfield_test_dir/__init__.py", "__in

        ("/filepathfield_test_dir/c/d.py", "d.py"),
        ("/filepathfield_test_dir/c/e.py", "e.py"),
        ("/filepathfield_test_dir/c/f/__init__.py", "__init__.py"),
        ("/filepathfield_test_dir/c/f/g.py", "g.py"),
        ("/filepathfield_test_

it__.py"),
        ("/filepathfield_test_dir/a.py", "a.py"),
        ("/filepathfield_test_dir/ab.py", "ab.py"),
        ("/filepathfield_test_dir/b.py", "b.py"),
        ("/filepathfield_test_dir/c/__init__.py", "__init__.py"),


t.utils import override_settings
from django.urls import reverse
from django.utils import formats, translation

from . import FormFieldAssertionsMixin

class FloatFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
    def test_floatfield_1(self):
        f = FloatField()
        self.assertWidgetRendersTo(
            f, '<input step="any" type="number" name="f" id="id_f" required>'
        )
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean("")

.0, f.clean("23"))
        self.assertEqual(3.1400000000000001, f.clean("3.14"))
        self.assertEqual(3.1400000000000001, f.clean(3.14))
        self.assertEqual(42.0, f.clean(42))
        with self.assertRaisesMessage(ValidationError, "'Enter a number

    with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean(None)
        self.assertEqual(1.0, f.clean("1"))
        self.assertIsInstance(f.clean("1"), float)
        self.assertEqual(23


self.assertRaises(ValueError):
            GenericIPAddressField(protocol="ipv4", unpack_ipv4=True)

    def test_generic_ipaddress_as_generic(self):
        # The edge cases of the IPv6 validation code are not deeply tested
        # here, they are covered in the tests for django.utils.ipv6
        f = GenericIPAddressField()
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean("")
        with self.assertRaisesMessage(ValidationError, "'This field is req

 f.clean("foo")
        with self.assertRaisesMessage(
            ValidationError, "'Enter a valid IPv4 or IPv6 address.'"
        ):
            f.clean("127.0.0.")
        with self.assertRaisesMessage(
            ValidationError, "'Enter a valid IPv4

uired.'"):
            f.clean(None)
        self.assertEqual(f.clean(" 127.0.0.1 "), "127.0.0.1")
        with self.assertRaisesMessage(
            ValidationError, "'Enter a valid IPv4 or IPv6 address.'"
        ):


ploadedfile import SimpleUploadedFile, TemporaryUploadedFile
from django.forms import ClearableFileInput, FileInput, ImageField, Widget
from django.test import SimpleTestCase

from . import FormFieldAssertionsMixin

try:
    from PIL import Image
except ImportError:
    Image = None

def get_img_path(path):
    return os.path.join(
        os.path.abspath(os.path.join(__file__, "..", "..")), "tests", path
    )

@unittest.skipUnless(Image, "Pillow is required to test ImageField")
class ImageFieldTest(Form

mg_file:
            img_data = img_file.read()

        img_file = SimpleUploadedFile("1x1.png", img_data)
        img_file.content_type = "text/plain"

        uploaded_file = f.clean(img_file)

        self.assertEqual("PNG", uploaded_file.image.format)

FieldAssertionsMixin, SimpleTestCase):
    def test_imagefield_annotate_with_image_after_clean(self):
        f = ImageField()

        img_path = get_img_path("filepath_test_files/1x1.png")
        with open(img_path, "rb") as i


ormFieldAssertionsMixin, SimpleTestCase):
    def test_integerfield_1(self):
        f = IntegerField()
        self.assertWidgetRendersTo(
            f, '<input type="number" name="f" id="id_f" required>'
        )
        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.assertIsInstance(f.c

ssertRaisesMessage(ValidationError, "'Enter a whole number.'"):
            f.clean(3.14)
        self.assertEqual(1, f.clean("1 "))
        self.assertEqual(1, f.clean(" 1"))
        self.assertEqual(1, f.clean(" 1 "))
        with self.assertRaisesMessag

lean("1"), int)
        self.assertEqual(23, f.clean("23"))
        with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
            f.clean("a")
        self.assertEqual(42, f.clean(42))
        with self.a


go.test.utils import captured_stderr, captured_stdout
from django.utils import translation
from django.utils.encoding import DEFAULT_LOCALE_ENCODING
from django.utils.functional import cached_property
from django.utils.translation import gettext

from .utils import RunInTmpDirMixin, copytree

has_msgfmt = find_command("msgfmt")

@unittest.skipUnless(has_msgfmt, "msgfmt is mandatory for compilation tests")
class MessageCompilationTests(RunInTmpDirMixin, SimpleTestCase):
    work_subdir = "commands"

class

        with self.assertRaisesMessage(
            CommandError, "compilemessages generated one or more errors."
        ):
            call_command(
                "compilemessages", locale=[self.LOCALE], verbosity=0, stderr=stderr
            )

PoFileTests(MessageCompilationTests):
    LOCALE = "es_AR"
    MO_FILE = "locale/%s/LC_MESSAGES/django.mo" % LOCALE
    MO_FILE_EN = "locale/en/LC_MESSAGES/django.mo"

    def test_bom_rejection(self):
        stderr = StringIO()


stack, use_quotes=True):
        return self._assertPoKeyword(
            "msgid_plural", msgid, haystack, use_quotes=use_quotes
        )

    def assertMsgStr(self, msgstr, haystack, use_quotes=True):
        return self._assertPoKeyword("msgstr", msgstr, haystack, use_quotes=use_quotes)

    def assertNotMsgId(self, msgid, s, use_quotes=True):
        if use_quotes:
            msgid = '"%s"' % msgid
        msgid = re.escape(msgid)
        return self.assertTrue(not re.search("^msgid %s" % msgid, s, re

       # #: .\path\to\file.html:123
            cwd_prefix = "%s%s" % (os.curdir, os.sep)
        else:
            # #: path/to/file.html:123
            cwd_prefix = ""

        path = os.path.join(cwd_prefix, *comment_parts)
        parts = [path]

.MULTILINE))

    def _assertPoLocComment(
        self, assert_presence, po_filename, line_number, *comment_parts
    ):
        with open(po_filename) as fp:
            po_contents = fp.read()
        if os.name == "nt":


rs", 2) % {"num": 2}, "2 years")

    @override_settings(LOCALE_PATHS=extended_locale_paths)
    @translation.override("fr")
    def test_multiple_plurals_per_language(self):
        """
        Normally, French has 2 plurals. As
        other/locale/fr/LC_MESSAGES/django.po has a different plural equation
        with 3 plurals, this tests if those plural are honored.
        """
        self.assertEqual(ngettext("%d singular", "%d plural", 0) % 0, "0 pluriel1")
        self.assertEqual(ngettext("%d singul

po files).
        self.assertEqual(french._catalog[("%d singular", 0)], "%d singulier")
        self.assertEqual(french._catalog[("%(num)d hour", 0)], "%(num)d heure")

    @translation.override("fr")
    @skipUnless(find_command("msgfmt"), "msgfmt is man

ar", "%d plural", 1) % 1, "1 singulier")
        self.assertEqual(ngettext("%d singular", "%d plural", 2) % 2, "2 pluriel2")
        french = trans_real.catalog()
        # Internal _catalog can query subcatalogs (from different


"
Helper script to update sampleproject's translation catalogs.

When a bug has been identified related to i18n, this helps capture the issue
by using catalogs created from management commands.

Example:

The string "Two %% Three %%%" renders differently using translate and
blocktranslate. This issue is difficult to debug, it could be a problem with
extraction, interpolation, or both.

How this script helps:
 * Add {% translate "Two %% Three %%%" %} and blocktranslate equivalent to
   templates.
 * Run this

   that is rendered using an activated language from sampleproject's locale.
 * Tests should fail, issue captured.
 * Fix issue.
 * Run this script.
 * Tests all pass.
"""

import os
import re
import sys

proj_dir = os.path.dirname(os.path.abspath(__file_

 script.
 * Test extraction - verify the new msgid in sampleproject's django.po.
 * Add a translation to sampleproject's django.po.
 * Run this script.
 * Test interpolation - verify templatetag rendering, test each in a template


conf.urls.i18n import i18n_patterns
from django.urls import include, path, re_path
from django.utils.translation import gettext_lazy as _
from django.views.generic import TemplateView

view = TemplateView.as_view(template_name="dummy.html")

urlpatterns = [
    path("not-prefixed/", view, name="not-prefixed"),
    path("not-prefixed-include/", include("i18n.patterns.urls.included")),
    path(_("translated/"), view, name="no-prefix-translated"),
    re_path(_(r"^translated-regex/$"), view, name="no-prefix-t

 view, name="prefixed"),
    path("prefixed.xml", view, name="prefixed_xml"),
    re_path(
        _(r"^with-arguments/(?P<argument>[\w-]+)/(?:(?P<optional>[\w-]+).html)?$"),
        view,
        name="with-arguments",
    ),
    path(
        _("path-wit

ranslated-regex"),
    re_path(
        _(r"^translated/(?P<slug>[\w-]+)/$"),
        view,
        {"slug": "default-slug"},
        name="no-prefix-translated-slug",
    ),
]

urlpatterns += i18n_patterns(
    path("prefixed/",


db.models.manager
from django.db import migrations, models

class Migration(migrations.Migration):
    dependencies = [
        ("sites", "0001_initial"),
    ]

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

tes.Site", models.CASCADE),
                ),
            ],
            options={
                "abstract": False,
            },
            managers=[
                ("objects", django.db.models.manager.Manager()),
                (

name="ID",
                    ),
                ),
                ("title", models.CharField(max_length=50)),
                (
                    "places_this_article_should_appear",
                    models.ForeignKey("si


       "django.contrib.messages",
        "admin_checks",
    ],
)
class SystemChecksTestCase(SimpleTestCase):
    databases = "__all__"

    def test_checks_are_performed(self):
        admin.site.register(Song, MyAdmin)
        try:
            errors = checks.run_checks()
            expected = ["error!"]
            self.assertEqual(errors, expected)
        finally:
            admin.site.unregister(Song)

    @override_settings(INSTALLED_APPS=["django.contrib.admin"])
    def test_apps_dependencies(se

ion.",
                id="admin.E401",
            ),
            checks.Error(
                "'django.contrib.auth' must be in INSTALLED_APPS in order "
                "to use the admin application.",
                id="admin.E405",
            ),

lf):
        errors = admin.checks.check_dependencies()
        expected = [
            checks.Error(
                "'django.contrib.contenttypes' must be in "
                "INSTALLED_APPS in order to use the admin applicat


Tests for the order_with_respect_to Meta attribute.
"""

from django.db import models

class Question(models.Model):
    text = models.CharField(max_length=200)

class Answer(models.Model):
    text = models.CharField(max_length=200)
    question = models.ForeignKey(Question, models.CASCADE)

    class Meta:
        order_with_respect_to = "question"

    def __str__(self):
        return self.text

class Post(models.Model):
    title = models.CharField(max_length=200)
    parent = models.ForeignKey(

a OneToOneField primary key.
class Entity(models.Model):
    pass

class Dimension(models.Model):
    entity = models.OneToOneField("Entity", primary_key=True, on_delete=models.CASCADE)

class Component(models.Model):
    dimension = models.ForeignKey("D

      "self", models.SET_NULL, related_name="children", null=True
    )

    class Meta:
        order_with_respect_to = "parent"

    def __str__(self):
        return self.title

# order_with_respect_to points to a model with


age
from django.db import models

callable_default_counter = itertools.count()

def callable_default():
    return next(callable_default_counter)

temp_storage = FileSystemStorage(location=tempfile.mkdtemp())

class BoundaryModel(models.Model):
    positive_integer = models.PositiveIntegerField(null=True, blank=True)

class Defaults(models.Model):
    name = models.CharField(max_length=255, default="class default value")
    def_date = models.DateField(default=datetime.date(1980, 1, 1))
    value = mode

"No Preference"),
        ("f", "Foo"),
        ("b", "Bar"),
    ]

    INTEGER_CHOICES = [
        (None, "No Preference"),
        (1, "Foo"),
        (2, "Bar"),
    ]

    STRING_CHOICES_WITH_NONE = [
        (None, "No Preference"),
        ("f", "Fo

ls.IntegerField(default=42)
    callable_default = models.IntegerField(default=callable_default)

class ChoiceModel(models.Model):
    """For ModelChoiceField and ModelMultipleChoiceField tests."""

    CHOICES = [
        ("",


boxInputTest(WidgetTest):
    widget = CheckboxInput()

    def test_render_empty(self):
        self.check_html(
            self.widget, "is_cool", "", html='<input type="checkbox" name="is_cool">'
        )

    def test_render_none(self):
        self.check_html(
            self.widget, "is_cool", None, html='<input type="checkbox" name="is_cool">'
        )

    def test_render_false(self):
        self.check_html(
            self.widget, "is_cool", False, html='<input type="checkbox" name="is_cool">

nder_value(self):
        """
        Using any value that's not in ('', None, False, True) will check the
        checkbox and set the 'value' attribute.
        """
        self.check_html(
            self.widget,
            "is_cool",
            "foo

'
        )

    def test_render_true(self):
        self.check_html(
            self.widget,
            "is_cool",
            True,
            html='<input checked type="checkbox" name="is_cool">',
        )

    def test_re


eWidgetTest(WidgetTest):
    widget = ChoiceWidget

    @property
    def nested_widgets(self):
        nested_widget = self.widget(
            choices=(
                ("outer1", "Outer 1"),
                ('Group "1"', (("inner1", "Inner 1"), ("inner2", "Inner 2"))),
            ),
        )
        nested_widget_dict = self.widget(
            choices={
                "outer1": "Outer 1",
                'Group "1"': {"inner1": "Inner 1", "inner2": "Inner 2"},
            },
        )
        nested_

ed_widget_dict, nested_widget_dict_tuple)

    def test_deepcopy(self):
        """
        __deepcopy__() should copy all attributes properly.
        """
        widget = self.widget()
        obj = copy.deepcopy(widget)
        self.assertIsNot(widget,

widget_dict_tuple = self.widget(
            choices={
                "outer1": "Outer 1",
                'Group "1"': (("inner1", "Inner 1"), ("inner2", "Inner 2")),
            },
        )
        return (nested_widget, nest


 CharField, DateInput, Form
from django.utils import translation

from .base import WidgetTest

class DateInputTest(WidgetTest):
    widget = DateInput()

    def test_render_none(self):
        self.check_html(
            self.widget, "date", None, html='<input type="text" name="date">'
        )

    def test_render_value(self):
        d = date(2007, 9, 17)
        self.assertEqual(str(d), "2007-09-17")

        self.check_html(
            self.widget,
            "date",
            d,
            ht

-09-17">'),
        )

    def test_string(self):
        """
        Should be able to initialize from a string value.
        """
        self.check_html(
            self.widget,
            "date",
            "2007-09-17",
            html=('<input ty

ml='<input type="text" name="date" value="2007-09-17">',
        )
        self.check_html(
            self.widget,
            "date",
            date(2007, 9, 17),
            html=('<input type="text" name="date" value="2007


port CharField, DateTimeInput, Form
from django.utils import translation

from .base import WidgetTest

class DateTimeInputTest(WidgetTest):
    widget = DateTimeInput()

    def test_render_none(self):
        self.check_html(self.widget, "date", None, '<input type="text" name="date">')

    def test_render_value(self):
        """
        The microseconds are trimmed on display, by default.
        """
        d = datetime(2007, 9, 17, 12, 51, 34, 482548)
        self.assertEqual(str(d), "2007-09-17 12:5

elf.widget,
            "date",
            datetime(2007, 9, 17, 12, 51, 34),
            html=('<input type="text" name="date" value="2007-09-17 12:51:34">'),
        )
        self.check_html(
            self.widget,
            "date",
            dat

1:34.482548")
        self.check_html(
            self.widget,
            "date",
            d,
            html=('<input type="text" name="date" value="2007-09-17 12:51:34">'),
        )
        self.check_html(
            s


ort TestCase

from .models import Article, Category

class M2MMultipleTests(TestCase):
    def test_multiple(self):
        c1, c2, c3, c4 = [
            Category.objects.create(name=name)
            for name in ["Sports", "News", "Crime", "Life"]
        ]

        a1 = Article.objects.create(
            headline="Parrot steals", pub_date=datetime(2005, 11, 27)
        )
        a1.primary_categories.add(c2, c3)
        a1.secondary_categories.add(c4)

        a2 = Article.objects.create(
            h

      [
                "Crime",
                "News",
            ],
            lambda c: c.name,
        )
        self.assertQuerySetEqual(
            a2.primary_categories.all(),
            [
                "News",
                "Sports",

eadline="Parrot runs", pub_date=datetime(2005, 11, 28)
        )
        a2.primary_categories.add(c1, c2)
        a2.secondary_categories.add(c4)

        self.assertQuerySetEqual(
            a1.primary_categories.all(),


    def setUpTestData(cls):
        cls.t1 = Tournament.objects.create(name="Tourney 1")
        cls.t2 = Tournament.objects.create(name="Tourney 2")
        cls.o1 = Organiser.objects.create(name="Organiser 1")
        cls.p1 = Pool.objects.create(
            name="T1 Pool 1", tournament=cls.t1, organiser=cls.o1
        )
        cls.p2 = Pool.objects.create(
            name="T1 Pool 2", tournament=cls.t1, organiser=cls.o1
        )
        cls.p3 = Pool.objects.create(
            name="T2 Pool 1", tou

cls.p2)
        cls.ps2 = PoolStyle.objects.create(name="T2 Pool 1 Style", pool=cls.p3)
        cls.ps3 = PoolStyle.objects.create(
            name="T1 Pool 1/3 Style", pool=cls.p1, another_pool=cls.p3
        )

    def test_foreign_key(self):
        wi

rnament=cls.t2, organiser=cls.o1
        )
        cls.p4 = Pool.objects.create(
            name="T2 Pool 2", tournament=cls.t2, organiser=cls.o1
        )
        cls.ps1 = PoolStyle.objects.create(name="T1 Pool 2 Style", pool=


import forms

from .models import Company

class I18nForm(forms.Form):
    decimal_field = forms.DecimalField(localize=True)
    float_field = forms.FloatField(localize=True)
    date_field = forms.DateField(localize=True)
    datetime_field = forms.DateTimeField(localize=True)
    time_field = forms.TimeField(localize=True)
    integer_field = forms.IntegerField(localize=True)

class SelectDateForm(forms.Form):
    date_field = forms.DateField(widget=forms.SelectDateWidget)

class CompanyForm(forms.Mode

nts_paid = forms.DecimalField(max_digits=4, decimal_places=2, localize=True)
    products_delivered = forms.IntegerField(localize=True)
    date_added = forms.DateTimeField(localize=True)

    class Meta:
        model = Company
        fields = "__all__"


mport os

from django.core.management.commands.makemessages import TranslatableFile
from django.test import SimpleTestCase

class TranslatableFileTests(SimpleTestCase):
    def test_repr(self):
        dirpath = "dir"
        file_name = "example"
        trans_file = TranslatableFile(
            dirpath=dirpath, file_name=file_name, locale_dir=None
        )
        self.assertEqual(
            repr(trans_file),
            "<TranslatableFile: %s>" % os.path.join(dirpath, file_name),
        )

    def

         dirpath=dirpath, file_name=file_name, locale_dir=None
        )
        trans_file_not_eq = TranslatableFile(
            dirpath="tmp", file_name=file_name, locale_dir=None
        )
        self.assertEqual(trans_file, trans_file_eq)
        sel

test_eq(self):
        dirpath = "dir"
        file_name = "example"
        trans_file = TranslatableFile(
            dirpath=dirpath, file_name=file_name, locale_dir=None
        )
        trans_file_eq = TranslatableFile(


AGES=[
        ("nl", "Dutch"),
        ("en", "English"),
        ("pt-br", "Brazilian Portuguese"),
    ],
    MIDDLEWARE=[
        "django.middleware.locale.LocaleMiddleware",
        "django.middleware.common.CommonMiddleware",
    ],
    ROOT_URLCONF="i18n.patterns.urls.default",
    TEMPLATES=[
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            "DIRS": [os.path.join(os.path.dirname(__file__), "templates")],
            "OPTIONS": {
                "context_

    def setUp(self):
        # Make sure the cache is empty before we are doing our tests.
        clear_url_caches()
        # Make sure we will leave an empty cache for other testcases.
        self.addCleanup(clear_url_caches)

class URLPrefixTests(UR

processors": [
                    "django.template.context_processors.i18n",
                ],
            },
        }
    ],
)
class URLTestCaseBase(SimpleTestCase):
    """
    TestCase base-class for the URL tests.
    """


b.sites.managers import CurrentSiteManager
from django.contrib.sites.models import Site
from django.core import checks
from django.db import models
from django.test import SimpleTestCase, TestCase
from django.test.utils import isolate_apps

from .models import CustomArticle, ExclusiveArticle, SyndicatedArticle

class SitesFrameworkTestCase(TestCase):
    @classmethod
    def setUpTestData(cls):
        Site.objects.get_or_create(
            id=settings.SITE_ID, domain="example.com", name="example.com"

king News!", site_id=settings.SITE_ID
        )
        self.assertEqual(ExclusiveArticle.on_site.get(), article)

    def test_sites_m2m(self):
        article = SyndicatedArticle.objects.create(title="Fresh News!")
        article.sites.add(Site.objects.

     )
        Site.objects.create(
            id=settings.SITE_ID + 1, domain="example2.com", name="example2.com"
        )

    def test_site_fk(self):
        article = ExclusiveArticle.objects.create(
            title="Brea


r import attrgetter

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

from .base_tests import BaseOrderWithRespectToTests
from .models import Answer, Dimension, Entity, Post, Question

class OrderWithRespectToBaseTests(BaseOrderWithRespectToTests, TestCase):
    Answer = Answer
    Post = Post
    Question = Question

class OrderWithRespectToTests(SimpleTestCase):
    @isolate_apps("order_with_respect_to")
    def test_duplicate_orde

der = models.OrderWrt()

            class Meta:
                order_with_respect_to = "bar"
                app_label = "order_with_respect_to"

        count = 0
        for field in Foo._meta.local_fields:
            if isinstance(field, models.Order

r_field(self):
        class Bar(models.Model):
            class Meta:
                app_label = "order_with_respect_to"

        class Foo(models.Model):
            bar = models.ForeignKey(Bar, models.CASCADE)
            or


"],
            html="""

<input checked type="checkbox" name="beatles" value="J"> John

<input type="checkbox" name="beatles" value="P"> Paul

<input type="checkbox" name="beatles" value="G"> George

<input type="checkbox" name="beatles" value="R"> Ringo

        """,

<input checked type="checkbox" name="beatles" value="J"> John

<input checked type="checkbox" name="beatles" value="P"> Paul

<input type="checkbox" name="b

)

    def test_render_value_multiple(self):
        self.check_html(
            self.widget(choices=self.beatles),
            "beatles",
            ["J", "P"],
            html="""


Input, Form
from django.utils.datastructures import MultiValueDict

from .base import WidgetTest

class FileInputTest(WidgetTest):
    widget = FileInput()

    def test_render(self):
        """
        FileInput widgets never render the value attribute. The old value
        isn't useful if a form is updated or an error occurred.
        """
        self.check_html(
            self.widget,
            "email",
            "test@example.com",
            html='<input type="file" name="email">',
        )

    def test_value_omitted_from_data(self):
        self.assertIs(self.widget.value_omitted_from_data({}, {}, "field"), True)
        self.assertIs(
            self.widget.value_omitted_from_data({}, {"field": "value"}, "field"), False
        )

    def

        self.check_html(
            self.widget, "email", "", html='<input type="file" name="email">'
        )
        self.check_html(
            self.widget, "email", None, html='<input type="file" name="email">'
        )


hips between the same two tables

In this example, an ``Article`` can have many "primary" ``Category`` objects
and many "secondary" ``Category`` objects.

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

from django.db import models

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

    class Meta:
        ordering = ("name",)

    def __str__(self):
        return self.name

class Article(models.Model):
    headline = models.CharField(max_length=50)

tegories = models.ManyToManyField(
        Category, related_name="primary_article_set"
    )
    secondary_categories = models.ManyToManyField(
        Category, related_name="secondary_article_set"
    )

    class Meta:
        ordering = ("pub_date",)

    pub_date = models.DateTimeField()
    primary_ca


rt POFileAssertionMixin

SAMPLEPROJECT_DIR = os.path.join(
    os.path.dirname(os.path.abspath(__file__)), "sampleproject"
)
SAMPLEPROJECT_LOCALE = os.path.join(SAMPLEPROJECT_DIR, "locale")

@override_settings(LOCALE_PATHS=[SAMPLEPROJECT_LOCALE])
class FrenchTestCase(SimpleTestCase):
    """Tests using the French translations of the sampleproject."""

    PO_FILE = os.path.join(SAMPLEPROJECT_LOCALE, "fr", "LC_MESSAGES", "django.po")

    def setUp(self):
        self._language = get_language()
        self

rtionMixin, FrenchTestCase):
    """
    Tests the extracted string found in the gettext catalog.

    Percent signs are python formatted.

    These tests should all have an analogous translation tests below, ensuring
    the Python formatting does not pe

._translations = trans_real._translations
        activate("fr")

    def tearDown(self):
        trans_real._translations = self._translations
        activate(self._language)

class ExtractingStringsWithPercentSigns(POFileAsse


source_code_dir = os.path.dirname(__file__)

def copytree(src, dst):
    shutil.copytree(src, dst, ignore=shutil.ignore_patterns("__pycache__"))

class POFileAssertionMixin:
    def _assertPoKeyword(self, keyword, expected_value, haystack, use_quotes=True):
        q = '"'
        if use_quotes:
            expected_value = '"%s"' % expected_value
            q = "'"
        needle = "%s %s" % (keyword, expected_value)
        expected_value = re.escape(expected_value)
        return self.assertTrue(

aystack, use_quotes=True):
        return self._assertPoKeyword("msgid", msgid, haystack, use_quotes=use_quotes)

class RunInTmpDirMixin:
    """
    Allow i18n tests that need to generate .po/.mo files to run in an isolated
    temporary filesystem tree

        re.search("^%s %s" % (keyword, expected_value), haystack, re.MULTILINE),
            "Could not find %(q)s%(n)s%(q)s in generated PO file"
            % {"n": needle, "q": q},
        )

    def assertMsgId(self, msgid, h


od
    def setUpTestData(cls):
        cls.q1 = cls.Question.objects.create(
            text="Which Beatle starts with the letter 'R'?"
        )
        cls.Answer.objects.create(text="John", question=cls.q1)
        cls.Answer.objects.create(text="Paul", question=cls.q1)
        cls.Answer.objects.create(text="George", question=cls.q1)
        cls.Answer.objects.create(text="Ringo", question=cls.q1)

    def test_default_to_insertion_order(self):
        # Answers will always be ordered in the order they

ttrgetter("text"),
        )

    def test_previous_and_next_in_order(self):
        # We can retrieve the answers related to a particular object, in the
        # order they were created, once we have a particular object.
        a1 = self.q1.answer_set.a

 were inserted.
        self.assertQuerySetEqual(
            self.q1.answer_set.all(),
            [
                "John",
                "Paul",
                "George",
                "Ringo",
            ],
            a


earableFileInputTest(WidgetTest):
    def setUp(self):
        self.widget = ClearableFileInput()

    def test_clear_input_renders(self):
        """
        A ClearableFileInput with is_required False and rendered with an
        initial value that is a file renders a clear checkbox.
        """
        self.check_html(
            self.widget,
            "myfile",
            FakeFieldFile(),
            html=("""
            Currently: something
            <input type="checkbox

"
        A ClearableFileInput should escape name, filename, and URL
        when rendering HTML (#15182).
        """

        class StrangeFieldFile:
            url = "something?chapter=1&sect=2&copy=3&lang=en"

            def __str__(self):

" name="myfile-clear" id="myfile-clear_id">
            Clear

            Change: <input type="file" name="myfile">
            """),
        )

    def test_html_escaped(self):
        ""


te
from django.core.exceptions import ImproperlyConfigured
from django.test import SimpleTestCase

from .models import Guest, Location, Person, Place, Traveler

class NameAdmin(admin.ModelAdmin):
    list_display = ["name"]
    save_on_top = True

class CustomSite(admin.AdminSite):
    pass

class TestRegistration(SimpleTestCase):
    def setUp(self):
        self.site = admin.AdminSite()

    def test_bare_registration(self):
        self.site.register(Person)
        self.assertIsInstance(self.site.get

   self.assertIsInstance(self.site.get_model_admin(Person), NameAdmin)
        self.site.unregister(Person)
        self.assertEqual(self.site._registry, {})

    def test_prevent_double_registration(self):
        self.site.register(Person)
        msg =

_model_admin(Person), admin.ModelAdmin)
        self.site.unregister(Person)
        self.assertEqual(self.site._registry, {})

    def test_registration_with_model_admin(self):
        self.site.register(Person, NameAdmin)


ystem checks logic.
"""

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

class Album(models.Model):
    title = models.CharField(max_length=150)

class Song(models.Model):
    title = models.CharField(max_length=150)
    album = models.ForeignKey(Album, models.CASCADE)
    original_release = models.DateField(editable=False)

    class Meta:
        ordering = ("title",)

    def __str__(self):

 models.ForeignKey(Album, models.CASCADE, related_name="album2_set")
    e = models.CharField(max_length=1)

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

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

 return self.title

    def readonly_method_on_model(self):
        # does nothing
        pass

class TwoAlbumFKAndAnE(models.Model):
    album1 = models.ForeignKey(Album, models.CASCADE, related_name="album1_set")
    album2 =


forms.renderers import DjangoTemplates, Jinja2
from django.test import SimpleTestCase

try:
    import jinja2
except ImportError:
    jinja2 = None

class WidgetTest(SimpleTestCase):
    beatles = (("J", "John"), ("P", "Paul"), ("G", "George"), ("R", "Ringo"))

    @classmethod
    def setUpClass(cls):
        cls.django_renderer = DjangoTemplates()
        cls.jinja2_renderer = Jinja2() if jinja2 else None
        cls.renderers = [cls.django_renderer] + (
            [cls.jinja2_renderer] if cls.jinja2_re

LEqual
        if self.jinja2_renderer:
            output = widget.render(
                name, value, attrs=attrs, renderer=self.jinja2_renderer, **kwargs
            )
            # Django escapes quotes with '"' while Jinja2 uses '"'.

nderer else []
        )
        super().setUpClass()

    def check_html(
        self, widget, name, value, html="", attrs=None, strict=False, **kwargs
    ):
        assertEqual = self.assertEqual if strict else self.assertHTM


     f = forms.TimeField(localize=True)
        # Parse a time in an unaccepted format; get an error
        with self.assertRaises(ValidationError):
            f.clean("1:30:05 PM")

        # Parse a time in a valid format, get a parsed result
        result = f.clean("13:30:05")
        self.assertEqual(result, time(13, 30, 5))

        # The parsed result does a round trip to the same format
        text = f.widget.format_value(result)
        self.assertEqual(text, "13:30:05")

        # Parse a time

lt)
        self.assertEqual(text, "13:30:00")

    def test_timeField_with_inputformat(self):
        """
        TimeFields with manually specified input formats can accept those
        formats
        """
        f = forms.TimeField(input_formats=["%H.

in a valid format, get a parsed result
        result = f.clean("13:30")
        self.assertEqual(result, time(13, 30, 0))

        # The parsed result does a round trip to default format
        text = f.widget.format_value(resu


mingError, connection
from django.db.backends.base.base import NO_DB_ALIAS
from django.test import TestCase

try:
    from django.contrib.gis.db.backends.postgis.operations import PostGISOperations

    HAS_POSTGRES = True
except ImportError:
    HAS_POSTGRES = False

class BaseSpatialFeaturesTests(TestCase):
    def test_invalid_has_func_function(self):
        msg = (
            'DatabaseFeatures.has_Invalid_function isn\'t valid. Is "Invalid" '
            "missing from BaseSpatialOperations.unsupporte

ngs_dict = {
                "NAME": "test",
            }

    class FakePostGISOperations(PostGISOperations):
        def __init__(self, version=None):
            self.version = version
            self.connection = FakeConnection()

        def _get_po

d_functions?"
        )
        with self.assertRaisesMessage(ValueError, msg):
            connection.features.has_Invalid_function

if HAS_POSTGRES:

    class FakeConnection:
        def __init__(self):
            self.setti


raps
from unittest import mock

from django.conf import settings
from django.contrib.gis.geos.libgeos import geos_version_tuple
from django.db import DEFAULT_DB_ALIAS, connection
from django.db.models import Func

def skipUnlessGISLookup(*gis_lookups):
    """
    Skip a test unless a database supports all of gis_lookups.
    """

    def decorator(test_func):
        @wraps(test_func)
        def skip_wrapper(*args, **kwargs):
            if any(key not in connection.ops.gis_operators for key in gis_looku

  return skip_wrapper

    return decorator

_default_db = settings.DATABASES[DEFAULT_DB_ALIAS]["ENGINE"].rsplit(".")[-1]
# MySQL spatial indices can't handle NULL geometries.
gisfield_may_be_null = _default_db != "mysql"
# GEOSWKTWriter_write() behavior

ps):
                raise unittest.SkipTest(
                    "Database doesn't support all the lookups: %s"
                    % ", ".join(gis_lookups)
                )
            return test_func(*args, **kwargs)


rom .models import City, site, site_gis, site_gis_custom

@override_settings(ROOT_URLCONF="django.contrib.gis.tests.geoadmin.urls")
class GeoAdminTest(SimpleTestCase):
    admin_site = site  # ModelAdmin

    def test_widget_empty_string(self):
        geoadmin = self.admin_site.get_model_admin(City)
        form = geoadmin.get_changelist_form(None)({"point": ""})
        with self.assertRaisesMessage(AssertionError, "no logs"):
            with self.assertLogs("django.contrib.gis", "ERROR"):

    def test_widget_invalid_string(self):
        geoadmin = self.admin_site.get_model_admin(City)
        form = geoadmin.get_changelist_form(None)({"point": "INVALID()"})
        with self.assertLogs("django.contrib.gis", "ERROR") as cm:
            out

   output = str(form["point"])
        self.assertInHTML(
            '<textarea id="id_point" class="vSerializedField required" cols="150"'
            ' rows="10" name="point" hidden></textarea>',
            output,
        )


test import mock

from django.contrib.gis.gdal import GDAL_VERSION, Driver, GDALException

valid_drivers = (
    # vector
    "ESRI Shapefile",
    "MapInfo File",
    "S57",
    "DGN",
    "Memory" if GDAL_VERSION[:2] <= (3, 10) else "MEM",
    "CSV",
    "GML",
    "KML",
    # raster
    "GTiff",
    "JPEG",
    "MEM",
    "PNG",
)

invalid_drivers = ("Foo baz", "clucka", "ESRI Shp", "ESRI rast")

aliases = {
    "eSrI": "ESRI Shapefile",
    "SHAPE": "ESRI Shapefile",
    "sHp": "ESRI Shapefile",
    "t

riverTest(unittest.TestCase):
    def test01_valid_driver(self):
        "Testing valid GDAL/OGR Data Source Drivers."
        for d in valid_drivers:
            dr = Driver(d)
            self.assertEqual(d, str(dr))

    def test02_invalid_driver(self):

iFf": "GTiff",
    "tIf": "GTiff",
    "jPEg": "JPEG",
    "jpG": "JPEG",
}

if GDAL_VERSION[:2] <= (3, 10):
    aliases.update(
        {
            "tiger": "TIGER",
            "tiger/line": "TIGER",
        }
    )

class D


  'GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_1984",'
    '6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",'
    "0.017453292519943295]]"
)
# Using a regex because of small differences depending on GDAL versions.
wgs_84_wkt_regex = r'^GEOGCS\["(GCS_)?WGS[ _](19)?84".*$'

datetime_format = "%Y-%m-%dT%H:%M:%S"

# List of acceptable data sources.
ds_list = (
    TestDS(
        "test_point",
        nfeat=5,
        nfld=3,
        geom="POINT",
        gtype=1,
        driver="ESRI Shape

[float(i) for i in range(1, 6)],
            "int": list(range(1, 6)),
            "str": [str(i) for i in range(1, 6)],
        },
        fids=range(5),
    ),
    TestDS(
        "test_vrt",
        ext="vrt",
        nfeat=3,
        nfld=3,
        ge

file",
        fields={"dbl": OFTReal, "int": OFTInteger, "str": OFTString},
        extent=(-1.35011, 0.166623, -0.524093, 0.824508),  # Got extent from QGIS
        srs_wkt=wgs_84_wkt,
        field_values={
            "dbl":


f __init__(self, x, y):
        self.x = x
        self.y = y

class EnvelopeTest(unittest.TestCase):
    def setUp(self):
        self.e = Envelope(0, 0, 5, 5)

    def test01_init(self):
        "Testing Envelope initialization."
        e1 = Envelope((0, 0, 5, 5))
        Envelope(0, 0, 5, 5)
        Envelope(0, "0", "5", 5)  # Thanks to ww for this
        Envelope(e1._envelope)
        with self.assertRaises(GDALException):
            Envelope((5, 5, 0, 0))
        with self.assertRaises(GDALExceptio

eError):
            Envelope(0, "a", 5, 5)
        with self.assertRaises(TypeError):
            Envelope("foo")
        with self.assertRaises(GDALException):
            Envelope((1, 1, 0, 0))
        # Shouldn't raise an exception for min_x == max_x o

n):
            Envelope(5, 5, 0, 0)
        with self.assertRaises(GDALException):
            Envelope((0, 0, 5, 5, 3))
        with self.assertRaises(GDALException):
            Envelope(())
        with self.assertRaises(Valu


"), OGRGeomType(6))

        # Testing the Django field name equivalent property.
        self.assertEqual("PointField", OGRGeomType("Point").django)
        self.assertEqual("GeometryField", OGRGeomType("Geometry").django)
        self.assertEqual("GeometryField", OGRGeomType("Unknown").django)
        self.assertIsNone(OGRGeomType("none").django)

        # 'Geometry' initialization implies an unknown geometry type.
        gt = OGRGeomType("Geometry")
        self.assertEqual(0, gt.num)
        self.asse

       wkb25bit = OGRGeomType.wkb25bit
        self.assertEqual(OGRGeomType(wkb25bit + 1), "Point25D")
        self.assertEqual(OGRGeomType("MultiLineString25D"), (5 + wkb25bit))
        self.assertEqual(
            "GeometryCollectionField", OGRGeomType(

rtEqual("Unknown", gt.name)

    def test_geom_type_repr(self):
        self.assertEqual(repr(OGRGeomType("point")), "<OGRGeomType: Point>")

    def test_geomtype_25d(self):
        "Testing OGRGeomType object with 25D types."


6,
                "srid": 4326,
            }
        )
        self.assertEqual(rast.srid, 4326)
        rast.srid = 3086
        self.assertEqual(rast.srid, 3086)

    def test_geotransform_and_friends(self):
        # Assert correct values for file based raster
        self.assertEqual(
            self.rs.geotransform,
            [511700.4680706557, 100.0, 0.0, 435103.3771231986, 0.0, -100.0],
        )
        self.assertEqual(self.rs.origin, [511700.4680706557, 435103.3771231986])
        self.asser

rtEqual(self.rs.scale.y, -100.0)
        self.assertEqual(self.rs.skew, [0, 0])
        self.assertEqual(self.rs.skew.x, 0)
        self.assertEqual(self.rs.skew.y, 0)
        # Create in-memory rasters and change gtvalues
        rsmem = GDALRaster(JSON_R

tEqual(self.rs.origin.x, 511700.4680706557)
        self.assertEqual(self.rs.origin.y, 435103.3771231986)
        self.assertEqual(self.rs.scale, [100.0, -100.0])
        self.assertEqual(self.rs.scale.x, 100.0)
        self.asse


patial Reference examples
srlist = (
    TestSRS(
        'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,'
        'AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],'
        'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",'
        '0.0174532925199433,AUTHORITY["EPSG","9122"]],AXIS["Latitude",NORTH],'
        'AXIS["Longitude",EAST],AUTHORITY["EPSG","4326"]]',
        epsg=4326,
        projected=False,
        geographic=True,
        loca

l=False,
        lin_name="unknown",
        ang_name="degree",
        lin_units=1.0,
        ang_units=0.0174532925199,
        auth={
            None: ("EPSG", "4326"),  # Top-level authority.
            "GEOGCS": ("EPSG", "


 django.test.utils import modify_settings

from ..test_data import TEST_DATA
from .models import AllOGRFields

@skipUnlessDBFeature("supports_inspectdb")
class InspectDbTests(TestCase):
    def test_geom_columns(self):
        """
        Test the geo-enabled inspectdb command.
        """
        out = StringIO()
        call_command(
            "inspectdb",
            table_name_filter=lambda tn: tn == "inspectapp_allogrfields",
            stdout=out,
        )
        output = out.getvalue()

tIn("geom = models.GeometryField(", output)
            self.assertIn("point = models.GeometryField(", output)

    @skipUnlessDBFeature("supports_3d_storage")
    def test_3d_columns(self):
        out = StringIO()
        call_command(
            "inspe

if connection.features.supports_geometry_field_introspection:
            self.assertIn("geom = models.PolygonField()", output)
            self.assertIn("point = models.PointField()", output)
        else:
            self.asser


b import models

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

class Location(SimpleModel):
    point = models.PointField()

    def __str__(self):
        return self.point.wkt

class City(SimpleModel):
    name = models.CharField(max_length=50)
    state = models.CharField(max_length=2)
    location = models.ForeignKey(Location, models.CASCADE)

    def __str__(self):
        return self.name

class AugmentedLocation(Location):
    extra_text = models.TextField(blank=True)

   city = models.ForeignKey(City, models.CASCADE)
    center1 = models.PointField()
    # Throwing a curveball w/`db_column` here.
    center2 = models.PointField(srid=2276, db_column="mycenter")
    border1 = models.PolygonField()
    border2 = models.Pol

class DirectoryEntry(SimpleModel):
    listing_text = models.CharField(max_length=50)
    location = models.ForeignKey(AugmentedLocation, models.CASCADE)

class Parcel(SimpleModel):
    name = models.CharField(max_length=30)


y("id")
        # RemovedInDjango70Warning: when the deprecation ends, the below
        # queryset can be removed.
        with ignore_warnings(
            category=RemovedInDjango70Warning,
            message=r"Calling select_related\(\) with no arguments is deprecated\.",
        ):
            qs2 = City.objects.order_by("id").select_related()
        qs3 = City.objects.order_by("id").select_related("location")

        # Reference data for what's in the fixtures.
        cities = (
            ("Auro

qs):
                nm, st, lon, lat = ref
                self.assertEqual(nm, c.name)
                self.assertEqual(st, c.state)
                self.assertAlmostEqual(lon, c.location.point.x, 6)
                self.assertAlmostEqual(lat, c.location


(max_length=25)

    class Meta:
        abstract = True

    def __str__(self):
        return self.name

class State(NamedModel):
    pass

class County(NamedModel):
    state = models.ForeignKey(State, models.CASCADE)
    mpoly = models.MultiPolygonField(srid=4269, null=True)  # Multipolygon in NAD83

class CountyFeat(NamedModel):
    poly = models.PolygonField(srid=4269)

class City(NamedModel):
    name_txt = models.TextField(default="")
    name_short = models.CharField(max_length=5)
    populatio

):
    length = models.DecimalField(max_digits=6, decimal_places=2)
    path = models.LineStringField()

    class Meta:
        app_label = "layermap"

# Same as `City` above, but for testing model inheritance.
class CityBase(NamedModel):
    population

n = models.IntegerField()
    density = models.DecimalField(max_digits=7, decimal_places=1)
    dt = models.DateField()
    point = models.PointField()

    class Meta:
        app_label = "layermap"

class Interstate(NamedModel


es" / "counties.shp"
inter_shp = shp_path / "interstates" / "interstates.shp"
invalid_shp = shp_path / "invalid" / "emptypoints.shp"
has_nulls_geojson = shp_path / "has_nulls" / "has_nulls.geojson"

# Dictionaries to hold what's expected in the county shapefile.
NAMES = ["Bexar", "Galveston", "Harris", "Honolulu", "Pueblo"]
NUMS = [1, 2, 1, 19, 1]  # Number of polygons for each.
STATES = ["Texas", "Texas", "Texas", "Hawaii", "Colorado"]

class LayerMapTest(TestCase):
    def test_init(self):
        "Testi

        bad2["name"] = "Nombre"

        # Nonexistent geographic field type.
        bad3 = copy(city_mapping)
        bad3["point"] = "CURVE"

        # Incrementing through the bad mapping dictionaries and
        # ensuring that a LayerMapError is rais

ng LayerMapping initialization."

        # Model field that does not exist.
        bad1 = copy(city_mapping)
        bad1["foobar"] = "FooField"

        # Shapefile field that does not exist.
        bad2 = copy(city_mapping)


mport feeds

from .models import City

class TestGeoRSS1(feeds.Feed):
    link = "/city/"
    title = "Test GeoDjango Cities"

    def items(self):
        return City.objects.all()

    def item_link(self, item):
        return "/city/%s/" % item.pk

    def item_geometry(self, item):
        return item.point

class TestGeoRSS2(TestGeoRSS1):
    def geometry(self, obj):
        # This should attach a <georss:box> element for the extent of
        # the cities in the database. This tuple came from

    # Returning a simple tuple for the geometry.
        return item.point.x, item.point.y

class TestGeoAtom1(TestGeoRSS1):
    feed_type = feeds.GeoAtom1Feed

class TestGeoAtom2(TestGeoRSS2):
    feed_type = feeds.GeoAtom1Feed

    def geometry(self, o

  # calling `City.objects.aggregate(Extent())` -- we can't do that call
        # here because `Extent` is not implemented for MySQL/Oracle.
        return (-123.30, -41.32, 174.78, 48.46)

    def item_geometry(self, item):


ils import gisfield_may_be_null

class NamedModel(models.Model):
    name = models.CharField(max_length=30)

    class Meta:
        abstract = True

    def __str__(self):
        return self.name

class Country(NamedModel):
    mpoly = models.MultiPolygonField()  # SRID, by default, is 4326

class CountryWebMercator(NamedModel):
    mpoly = models.MultiPolygonField(srid=3857)

class City(NamedModel):
    point = models.PointField()

    class Meta:
        app_label = "geoapp"

# This is an inherited

PolygonField(
        null=gisfield_may_be_null
    )  # Allowing NULL geometries here.

    class Meta:
        app_label = "geoapp"

class Track(NamedModel):
    line = models.LineStringField()

class MultiFields(NamedModel):
    city = models.ForeignK

 model from City
class PennsylvaniaCity(City):
    county = models.CharField(max_length=30)
    founded = models.DateTimeField(null=True)

    class Meta:
        app_label = "geoapp"

class State(NamedModel):
    poly = models.


os import Point, Polygon
from django.db import connection
from django.db.models import Count, Min
from django.test import TestCase, skipUnlessDBFeature

from .models import City, ManyPointModel, MultiFields

class GeoExpressionsTests(TestCase):
    fixtures = ["initial"]

    def test_geometry_value_annotation(self):
        p = Point(1, 1, srid=4326)
        point = City.objects.annotate(p=Value(p, GeometryField(srid=4326))).first().p
        self.assertEqual(point, p)

    @skipUnlessDBFeature("supports_

ls_exact(p.transform(4326, clone=True), 10**-5))
        self.assertEqual(point.srid, 4326)

    @skipUnlessDBFeature("supports_geography")
    def test_geography_value(self):
        p = Polygon(((1, 1), (1, 2), (2, 2), (2, 1), (1, 1)))
        area = (

transform")
    def test_geometry_value_annotation_different_srid(self):
        p = Point(1, 1, srid=32140)
        point = City.objects.annotate(p=Value(p, GeometryField(srid=4326))).first().p
        self.assertTrue(point.equa


Site
from django.test import TestCase, modify_settings, override_settings

from .models import City

@modify_settings(INSTALLED_APPS={"append": "django.contrib.sites"})
@override_settings(ROOT_URLCONF="gis_tests.geoapp.urls")
class GeoFeedTest(TestCase):
    fixtures = ["initial"]

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

    def assertChildNodes(self, elem, expected):
        "Taken from syndication/tests.py."

`GEOSGeometry` in `item_geometry`
        doc1 = minidom.parseString(self.client.get("/feeds/rss1/").content)
        # Uses a 2-tuple in `item_geometry`
        doc2 = minidom.parseString(self.client.get("/feeds/rss2/").content)
        feed1, feed2 = doc

actual = {n.nodeName for n in elem.childNodes}
        expected = set(expected)
        self.assertEqual(actual, expected)

    def test_geofeed_rss(self):
        "Tests geographic feeds using GeoRSS over RSSv2."
        # Uses


-87.650175, 41.850385]

        # Precision argument should only be an integer
        with self.assertRaises(TypeError):
            City.objects.annotate(geojson=functions.AsGeoJSON("point", precision="foo"))

        # Reference queries and values.

atures.unsupported_geojson_options:
            del chicago_json["bbox"]
            del victoria_json["bbox"]
        if "precision" in connection.features.unsupported_geojson_options:
            chicago_json["coordinates"] = [


o.db import connection
from django.db.models import Index
from django.test import TransactionTestCase
from django.test.utils import isolate_apps

from .models import City

class SchemaIndexesTests(TransactionTestCase):
    available_apps = []
    models = [City]

    def get_indexes(self, table):
        with connection.cursor() as cursor:
            constraints = connection.introspection.get_constraints(cursor, table)
            return {
                name: constraint["columns"]
                for na

  return connection.introspection.supports_spatial_index(cursor, table)
        elif connection.ops.oracle:
            # Spatial indexes in Meta.indexes are not supported by the Oracle
            # backend (see #31252).
            return False
        r

me, constraint in constraints.items()
                if constraint["index"]
            }

    def has_spatial_indexes(self, table):
        if connection.ops.mysql:
            with connection.cursor() as cursor:


.shortcuts import render_to_kmz
from django.db.models import Count, Min
from django.test import TestCase, skipUnlessDBFeature

from ..utils import skipUnlessGISLookup
from .models import City, PennsylvaniaCity, State, Truth

class GeoRegressionTests(TestCase):
    fixtures = ["initial"]

    def test_update(self):
        "Testing QuerySet.update() (#10411)."
        pueblo = City.objects.get(name="Pueblo")
        bak = pueblo.point.clone()
        pueblo.point.y += 0.005
        pueblo.point.x += 0.005

 6)
        City.objects.filter(name="Pueblo").update(point=bak)
        pueblo.refresh_from_db()
        self.assertAlmostEqual(bak.y, pueblo.point.y, 6)
        self.assertAlmostEqual(bak.x, pueblo.point.x, 6)

    def test_kmz(self):
        "Testing `r

        City.objects.filter(name="Pueblo").update(point=pueblo.point)
        pueblo.refresh_from_db()
        self.assertAlmostEqual(bak.y + 0.005, pueblo.point.y, 6)
        self.assertAlmostEqual(bak.x + 0.005, pueblo.point.x,


rializers
from django.test import TestCase

from .models import City, MultiFields, PennsylvaniaCity

class GeoJSONSerializerTests(TestCase):
    fixtures = ["initial"]

    def test_builtin_serializers(self):
        """
        'geojson' should be listed in available serializers.
        """
        all_formats = set(serializers.get_serializer_formats())
        public_formats = set(serializers.get_public_serializer_formats())

        self.assertIn("geojson", all_formats)
        self.assertIn("geojson",

e", "features"])
        self.assertEqual(geodata["type"], "FeatureCollection")
        self.assertEqual(len(geodata["features"]), len(City.objects.all()))
        self.assertEqual(geodata["features"][0]["geometry"]["type"], "Point")
        self.assertEqu

 public_formats)

    def test_serialization_base(self):
        geojson = serializers.serialize("geojson", City.objects.order_by("name"))
        geodata = json.loads(geojson)
        self.assertEqual(list(geodata.keys()), ["typ


import minidom

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

from .models import City, Country

@modify_settings(
    INSTALLED_APPS={"append": ["django.contrib.sites", "django.contrib.sitemaps"]}
)
@override_settings(ROOT_URLCONF="gis_tests.geoapp.urls")
class GeoSitemapTest(TestCase):
    @classmethod
    def setUpTestData(cls):
        Site(id=settings.SITE_ID, domain="example.com", name="example.com")

)

    def test_geositemap_kml(self):
        "Tests KML/KMZ geographic sitemaps."
        for kml_type in ("kml", "kmz"):
            doc = minidom.parseString(
                self.client.get("/sitemaps/%s.xml" % kml_type).content
            )

.save()

    def assertChildNodes(self, elem, expected):
        "Taken from syndication/tests.py."
        actual = {n.nodeName for n in elem.childNodes}
        expected = set(expected)
        self.assertEqual(actual, expected


    GeometryCollectionModel,
    Lines,
    MinusOneSRID,
    MultiFields,
    NonConcreteModel,
    PennsylvaniaCity,
    Points,
    State,
    ThreeDimensionalFeature,
    Track,
)

class GeoModelTest(TestCase):
    fixtures = ["initial"]

    def test_fixtures(self):
        "Testing geographic model initialization from fixtures."
        # Ensuring that data was loaded from initial data fixtures.
        self.assertEqual(2, Country.objects.count())
        self.assertEqual(8, City.objects.count())

ullCity", point=pnt)
        nullcity.save()

        # Making sure TypeError is thrown when trying to set with an
        #  incompatible type.
        for bad in [5, 2.0, LineString((0, 0), (1, 1))]:
            with self.assertRaisesMessage(TypeError, "

      self.assertEqual(2, State.objects.count())

    def test_proxy(self):
        "Testing Lazy-Geometry support (using the GeometryProxy)."
        # Testing on a Point
        pnt = Point(0, 0)
        nullcity = City(name="N


django.contrib.gis import views as gis_views
from django.contrib.gis.sitemaps import views as gis_sitemap_views
from django.contrib.sitemaps import views as sitemap_views
from django.urls import path

from .feeds import feed_dict
from .sitemaps import sitemaps

urlpatterns = [
    path("feeds/<path:url>/", gis_views.feed, {"feed_dict": feed_dict}),
]

urlpatterns += [
    path("sitemaps/<section>.xml", sitemap_views.sitemap, {"sitemaps": sitemaps}),
]

urlpatterns += [
    path(
        "sitemaps/kml/<label

ld_name>.kml",
        gis_sitemap_views.kml,
        name="django.contrib.gis.sitemaps.views.kml",
    ),
    path(
        "sitemaps/kml/<label>/<model>/<field_name>.kmz",
        gis_sitemap_views.kmz,
        name="django.contrib.gis.sitemaps.views.kmz


contrib.gis.db import models

from ..utils import gisfield_may_be_null

class NamedModel(models.Model):
    name = models.CharField(max_length=30)

    class Meta:
        abstract = True

    def __str__(self):
        return self.name

class SouthTexasCity(NamedModel):
    "City model on projected coordinate system for South Texas."

    point = models.PointField(srid=32140)
    radius = models.IntegerField(default=10000)

class SouthTexasCityFt(NamedModel):
    "Same City model as above, but U.S. surv

  allowed_distance = models.FloatField(default=0.5)
    ref_point = models.PointField(null=True)

class CensusZipcode(NamedModel):
    "Model for a few South Texas ZIP codes (in original Census NAD83)."

    poly = models.PolygonField(srid=4269)

class S

ey feet are the units."

    point = models.PointField(srid=2278)

class AustraliaCity(NamedModel):
    "City model for Australia, using WGS84."

    point = models.PointField()
    radius = models.IntegerField(default=10000)


elf):
        # A point we are testing distances with -- using a WGS84
        # coordinate that'll be implicitly transformed to that to
        # the coordinate system of the field, EPSG:32140 (Texas South Central
        # w/units in meters)
        self.stx_pnt = GEOSGeometry(
            "POINT (-95.370401017314293 29.704867409475465)", 4326
        )
        # Another one for Australia
        self.au_pnt = GEOSGeometry("POINT (150.791 -34.4919)", 4326)

    def get_names(self, qs):
        cities = [c

self.assertEqual(9, SouthTexasCityFt.objects.count())
        self.assertEqual(11, AustraliaCity.objects.count())
        self.assertEqual(4, SouthTexasZipcode.objects.count())
        self.assertEqual(4, CensusZipcode.objects.count())
        self.assertE

.name for c in qs]
        cities.sort()
        return cities

    def test_init(self):
        """
        Test initialization of distance models.
        """
        self.assertEqual(9, SouthTexasCity.objects.count())


b import models

class NamedModel(models.Model):
    name = models.CharField(max_length=30)

    class Meta:
        abstract = True

    def __str__(self):
        return self.name

class City3D(NamedModel):
    point = models.PointField(dim=3)
    pointg = models.PointField(dim=3, geography=True)

    class Meta:
        required_db_features = {"supports_3d_storage"}

class Interstate2D(NamedModel):
    line = models.LineStringField(srid=4269)

class Interstate3D(NamedModel):
    line = models.LineStr

 = models.LineStringField(dim=3, srid=32140)

    class Meta:
        required_db_features = {"supports_3d_storage"}

class Polygon2D(NamedModel):
    poly = models.PolygonField(srid=32140)

class Polygon3D(NamedModel):
    poly = models.PolygonField(dim

ingField(dim=3, srid=4269)

    class Meta:
        required_db_features = {"supports_3d_storage"}

class InterstateProj2D(NamedModel):
    line = models.LineStringField(srid=32140)

class InterstateProj3D(NamedModel):
    line


ty3D,
    Interstate2D,
    Interstate3D,
    InterstateProj2D,
    InterstateProj3D,
    MultiPoint3D,
    Point2D,
    Point3D,
    Polygon2D,
    Polygon3D,
)

data_path = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "data"))
city_file = os.path.join(data_path, "cities", "cities.shp")
vrt_file = os.path.join(data_path, "test_vrt", "test_vrt.vrt")

# The coordinates of each city, with Z values corresponding to their
# altitude in meters.
city_data = (
    ("Houston", (-95.363151, 29.7633

235060, 38.971823, 251)),
    ("Chicago", (-87.650175, 41.850385, 181)),
    ("Victoria", (-123.305196, 48.462611, 15)),
)

# Reference mapping of city name to its altitude (Z value).
city_dict = {name: coords for name, coords in city_data}

# 3D freeway d


harField(max_length=30)

    class Meta:
        abstract = True

    def __str__(self):
        return self.name

class City(NamedModel):
    point = models.PointField(geography=True)

    class Meta:
        app_label = "geogapp"

class CityUnique(NamedModel):
    point = models.PointField(geography=True, unique=True)

    class Meta:
        required_db_features = {
            "supports_geography",
            "supports_geometry_field_unique_index",
        }

class Zipcode(NamedModel):
    code = mo

gonField(geography=True)

class County(NamedModel):
    state = models.CharField(max_length=20)
    mpoly = models.MultiPolygonField(geography=True)

    class Meta:
        app_label = "geogapp"

    def __str__(self):
        return " County, ".join([se

dels.CharField(max_length=10)
    poly = models.Poly


 D
from django.core.exceptions import ValidationError
from django.db import NotSupportedError, connection
from django.db.models.functions import Cast
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from django.test.utils import CaptureQueriesContext

from ..utils import FuncTestMixin
from .models import City, CityUnique, County, Zipcode

class GeographyTest(TestCase):
    fixtures = ["initial"]

    def test01_fixture_load(self):
        "Ensure geography features loaded properly."

ography fields."
        z = Zipcode.objects.get(code="77002")
        cities1 = list(
            City.objects.filter(point__distance_lte=(z.poly, D(mi=500)))
            .order_by("name")
            .values_list("name", flat=True)
        )
        citi

       self.assertEqual(8, City.objects.count())

    @skipUnlessDBFeature("supports_distances_lookups", "supports_distance_geodetic")
    def test02_distance_lookup(self):
        "Testing distance lookup support on non-point ge


test_str(self):
        self.assertEqual(
            str(MediaAsset("path/to/css")),
            "http://media.example.com/static/path/to/css",
        )
        self.assertEqual(
            str(MediaAsset("http://media.other.com/path/to/css")),
            "http://media.other.com/path/to/css",
        )

    def test_repr(self):
        self.assertEqual(repr(MediaAsset("path/to/css")), "MediaAsset('path/to/css')")
        self.assertEqual(
            repr(MediaAsset("http://media.other.com/path/to/css")

        asset = MediaAsset("http://media.other.com/path/to/css")
        self.assertEqual(asset.path, "http://media.other.com/path/to/css")

        asset = MediaAsset("https://secure.other.com/path/to/css")
        self.assertEqual(asset.path, "https://s

),
            "MediaAsset('http://media.other.com/path/to/css')",
        )

    def test_path(self):
        asset = MediaAsset("path/to/css")
        self.assertEqual(asset.path, "http://media.example.com/static/path/to/css")


ort SimpleUploadedFile

class TestFieldWithValidators(TestCase):
    def test_all_errors_get_reported(self):
        class UserForm(forms.Form):
            full_name = forms.CharField(
                max_length=50,
                validators=[
                    validators.validate_integer,
                    validators.validate_email,
                ],
            )
            string = forms.CharField(
                max_length=50,
                validators=[
                    validators.RegexVa

ength=50,
                validators=[
                    validators.RegexValidator(
                        regex="^[a-z]*$",
                        message="Letters only.",
                        flags=re.IGNORECASE,
                    )

lidator(
                        regex="^[a-zA-Z]*$",
                        message="Letters only.",
                    )
                ],
            )
            ignore_case_string = forms.CharField(
                max_l


    class Meta:
        exclude = ["multi_choice"]
        model = ChoiceFieldModel

class EmptyCharLabelChoiceForm(ModelForm):
    class Meta:
        model = ChoiceModel
        fields = ["name", "choice"]

class EmptyIntegerLabelChoiceForm(ModelForm):
    class Meta:
        model = ChoiceModel
        fields = ["name", "choice_integer"]

class EmptyCharLabelNoneChoiceForm(ModelForm):
    class Meta:
        model = ChoiceModel
        fields = ["name", "choice_string_w_none"]

class FileForm(Form):

eld has blank=True and is saved with no data,
        a queryset is returned.
        """
        option = ChoiceOptionModel.objects.create(name="default")
        form = OptionalMultiChoiceModelForm(
            {"multi_choice_optional": "", "multi_choice

    file1 = FileField()

class TestTicket14567(TestCase):
    """
    The return values of ModelMultipleChoiceFields are QuerySets
    """

    def test_empty_queryset_return(self):
        """
        If a model's ManyToManyFi


_URLCONF="context_processors.urls",
    TEMPLATES=[
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            "APP_DIRS": True,
            "OPTIONS": {
                "context_processors": [
                    "django.template.context_processors.request",
                ],
            },
        }
    ],
)
class RequestContextProcessorTests(SimpleTestCase):
    """
    Tests for the ``django.template.context_processors.request`` processor.
    """

    def test_requ

 # We should have the request object in the template.
        response = self.client.get(url)
        self.assertContains(response, "Have request")
        # Test is_secure.
        response = self.client.get(url)
        self.assertContains(response, "Not

est_attributes(self):
        """
        The request object is available in the template and that its
        attributes can't be overridden by GET and POST parameters (#3828).
        """
        url = "/request_attrs/"


set."
        # Input that doesn't specify the SRID is assumed to be in the SRID
        # of the input field.
        fld = forms.GeometryField(srid=4326)
        geom = fld.clean("POINT(5 23)")
        self.assertEqual(4326, geom.srid)
        # Making the field in a different SRID from that of the geometry, and
        # asserting it transforms.
        fld = forms.GeometryField(srid=32140)
        # Different PROJ versions use different transformations, all are
        # correct as having a 1 meter accu

.
        cleaned_geom = fld.clean(
            "SRID=3857;POINT (-10615777.40976205 3473169.895707852)"
        )
        self.assertEqual(cleaned_geom.srid, 32140)
        self.assertTrue(xform_geom.equals_exact(cleaned_geom, tol))

    def test_null(sel

racy.
        tol = 1
        xform_geom = GEOSGeometry(
            "POINT (951640.547328465 4219369.26171664)", srid=32140
        )
        # The cleaned geometry is transformed to 32140 (the widget map_srid is
        # 3857)


nection, models
from django.test import SimpleTestCase

from .utils import FuncTestMixin

def test_mutation(raises=True):
    def wrapper(mutation_func):
        def test(test_case_instance, *args, **kwargs):
            class TestFunc(models.Func):
                output_field = models.IntegerField()

                def __init__(self):
                    self.attribute = "initial"
                    super().__init__("initial", ["initial"])

                def as_sql(self, *args, **kwargs):

or, msg):
                    getattr(TestFunc(), "as_" + connection.vendor)(None, None)
            else:
                getattr(TestFunc(), "as_" + connection.vendor)(None, None)

        return test

    return wrapper

class FuncTestMixinTests(FuncTe

         mutation_func(self)
                    return "", ()

            if raises:
                msg = "TestFunc Func was mutated during compilation."
                with test_case_instance.assertRaisesMessage(AssertionErr


o.contrib.gis.ptr import CPointerBase
from django.test import SimpleTestCase

class CPointerBaseTests(SimpleTestCase):
    def test(self):
        destructor_mock = mock.Mock()

        class NullPointerException(Exception):
            pass

        class FakeGeom1(CPointerBase):
            null_ptr_exception_class = NullPointerException

        class FakeGeom2(FakeGeom1):
            ptr_type = ctypes.POINTER(ctypes.c_float)
            destructor = destructor_mock

        fg1 = FakeGeom1()
        fg

3))
        fg2.ptr = None

        # Because pointers have been set to NULL, an exception is raised on
        # access. Raising an exception is preferable to a segmentation fault
        # that commonly occurs when a C method is given a NULL reference.

2 = FakeGeom2()

        # These assignments are OK. None is allowed because it's equivalent
        # to the NULL pointer.
        fg1.ptr = fg1.ptr_type()
        fg1.ptr = None
        fg2.ptr = fg2.ptr_type(ctypes.c_float(5.2


import (
    CharField,
    Form,
    JSONField,
    Textarea,
    TextInput,
    ValidationError,
)
from django.test import SimpleTestCase

class JSONFieldTest(SimpleTestCase):
    def test_valid(self):
        field = JSONField()
        value = field.clean('{"a": "b"}')
        self.assertEqual(value, {"a": "b"})

    def test_valid_empty(self):
        field = JSONField(required=False)
        self.assertIsNone(field.clean(""))
        self.assertIsNone(field.clean(None))

    def test_invalid(self):

 self.assertEqual(field.prepare_value({"a": "b"}), '{"a": "b"}')
        self.assertEqual(field.prepare_value(None), "null")
        self.assertEqual(field.prepare_value("foo"), '"foo"')
        self.assertEqual(field.prepare_value("你好，世界"), '"你好，世界"')

       field = JSONField()
        with self.assertRaisesMessage(ValidationError, "Enter a valid JSON."):
            field.clean("{some badly formed: json}")

    def test_prepare_value(self):
        field = JSONField()


ectMultiple,
    SplitDateTimeField,
    SplitDateTimeWidget,
    TextInput,
)
from django.test import SimpleTestCase

beatles = (("J", "John"), ("P", "Paul"), ("G", "George"), ("R", "Ringo"))

class PartiallyRequiredField(MultiValueField):
    def compress(self, data_list):
        return ",".join(data_list) if data_list else None

class PartiallyRequiredForm(Form):
    f = PartiallyRequiredField(
        fields=(CharField(required=True), CharField(required=False)),
        required=True,
        require

Multiple(choices=beatles),
            SplitDateTimeWidget(),
        )
        super().__init__(widgets, attrs)

    def decompress(self, value):
        if value:
            data = value.split(",")
            return [
                data[0],

_all_fields=False,
        widget=MultiWidget(widgets=[TextInput(), TextInput()]),
    )

class ComplexMultiWidget(MultiWidget):
    def __init__(self, attrs=None):
        widgets = (
            TextInput(),
            Select


leTestCase

from . import FormFieldAssertionsMixin

class NullBooleanFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
    def test_nullbooleanfield_clean(self):
        f = NullBooleanField()
        self.assertIsNone(f.clean(""))
        self.assertTrue(f.clean(True))
        self.assertFalse(f.clean(False))
        self.assertIsNone(f.clean(None))
        self.assertFalse(f.clean("0"))
        self.assertTrue(f.clean("1"))
        self.assertIsNone(f.clean("2"))
        self.assertIsNone(f.clean("3")

put (#7753).
        class HiddenNullBooleanForm(Form):
            hidden_nullbool1 = NullBooleanField(widget=HiddenInput, initial=True)
            hidden_nullbool2 = NullBooleanField(widget=HiddenInput, initial=False)

        f = HiddenNullBooleanForm(

)
        self.assertIsNone(f.clean("hello"))
        self.assertTrue(f.clean("true"))
        self.assertFalse(f.clean("false"))

    def test_nullbooleanfield_2(self):
        # The internal value is preserved if using HiddenIn


ase

class SlugFieldTest(SimpleTestCase):
    def test_slugfield_normalization(self):
        f = SlugField()
        self.assertEqual(f.clean("    aa-bb-cc    "), "aa-bb-cc")

    def test_slugfield_unicode_normalization(self):
        f = SlugField(allow_unicode=True)
        self.assertEqual(f.clean("a"), "a")
        self.assertEqual(f.clean("1"), "1")
        self.assertEqual(f.clean("a1"), "a1")
        self.assertEqual(f.clean("你好"), "你好")
        self.assertEqual(f.clean("  你-好  "), "你-好")

self.assertEqual(f.clean("foo-ıç-bar"), "foo-ıç-bar")

    def test_empty_value(self):
        f = SlugField(required=False)
        self.assertEqual(f.clean(""), "")
        self.assertEqual(f.clean(None), "")
        f = SlugField(required=False, empty_v


itDateTimeField
from django.forms.widgets import SplitDateTimeWidget
from django.test import SimpleTestCase

class SplitDateTimeFieldTest(SimpleTestCase):
    def test_splitdatetimefield_1(self):
        f = SplitDateTimeField()
        self.assertIsInstance(f.widget, SplitDateTimeWidget)
        self.assertEqual(
            datetime.datetime(2006, 1, 10, 7, 30),
            f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)]),
        )
        with self.assertRaisesMessage(ValidationError, "'This

of values.'"):
            f.clean("hello")
        with self.assertRaisesMessage(
            ValidationError, "'Enter a valid date.', 'Enter a valid time.'"
        ):
            f.clean(["hello", "there"])
        with self.assertRaisesMessage(Validati

 field is required.'"):
            f.clean(None)
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean("")
        with self.assertRaisesMessage(ValidationError, "'Enter a list


pleChoiceField
from django.test import SimpleTestCase

class TypedMultipleChoiceFieldTest(SimpleTestCase):
    def test_typedmultiplechoicefield_1(self):
        f = TypedMultipleChoiceField(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_typedmultiplechoicefield_2(self):
        # Dif

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

    def test_typedmultiplechoicefield_4(self):

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

    def test_typedmultiplechoicefield_3(self):
        # This