repo stringlengths 7 90 | file_url stringlengths 81 315 | file_path stringlengths 4 228 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:38:15 2026-01-05 02:33:18 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_emailfield.py | tests/forms_tests/field_tests/test_emailfield.py | from django.core.exceptions import ValidationError
from django.forms import EmailField
from django.test 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(ValidationError, "'This field is required.'"):
f.clean(None)
self.assertEqual("person@example.com", f.clean("person@example.com"))
with self.assertRaisesMessage(
ValidationError, "'Enter a 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_for_performance(self):
f = EmailField()
# Check for runaway regex security problem. This will take a long time
# if the security fix isn't in place.
addr = "viewx3dtextx26qx3d@yahoo.comx26latlngx3d15854521645943074058"
with self.assertRaisesMessage(ValidationError, "Enter a valid email address."):
f.clean(addr)
def test_emailfield_not_required(self):
f = EmailField(required=False)
self.assertEqual("", f.clean(""))
self.assertEqual("", f.clean(None))
self.assertEqual("person@example.com", f.clean("person@example.com"))
self.assertEqual(
"example@example.com", f.clean(" example@example.com \t \t ")
)
with self.assertRaisesMessage(
ValidationError, "'Enter a valid email address.'"
):
f.clean("foo")
def test_emailfield_min_max_length(self):
f = EmailField(min_length=10, max_length=15)
self.assertWidgetRendersTo(
f,
'<input id="id_f" type="email" name="f" maxlength="15" minlength="10" '
"required>",
)
with self.assertRaisesMessage(
ValidationError,
"'Ensure this value has at least 10 characters (it has 9).'",
):
f.clean("a@foo.com")
self.assertEqual("alf@foo.com", f.clean("alf@foo.com"))
with self.assertRaisesMessage(
ValidationError,
"'Ensure this value has at most 15 characters (it has 20).'",
):
f.clean("alf123456788@foo.com")
def test_emailfield_strip_on_none_value(self):
f = EmailField(required=False, empty_value=None)
self.assertIsNone(f.clean(""))
self.assertIsNone(f.clean(None))
def test_emailfield_unable_to_set_strip_kwarg(self):
msg = "got multiple values for keyword argument 'strip'"
with self.assertRaisesMessage(TypeError, msg):
EmailField(strip=False)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_decimalfield.py | tests/forms_tests/field_tests/test_decimalfield.py | import decimal
from django.core.exceptions import ValidationError
from django.forms import DecimalField, NumberInput, Widget
from django.test import SimpleTestCase, override_settings
from django.utils import formats, translation
from . import FormFieldAssertionsMixin
class DecimalFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
def test_decimalfield_1(self):
f = DecimalField(max_digits=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(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")), 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.assertRaisesMessage(
ValidationError, "'Ensure that there are no more than 4 digits in total.'"
):
f.clean("123.45")
with self.assertRaisesMessage(
ValidationError, "'Ensure that there are no more than 2 decimal places.'"
):
f.clean("1.234")
msg = "'Ensure that there are no more than 2 digits before the decimal point.'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean("123.4")
self.assertEqual(f.clean("-12.34"), decimal.Decimal("-12.34"))
with self.assertRaisesMessage(
ValidationError, "'Ensure that there are no more than 4 digits in total.'"
):
f.clean("-123.45")
self.assertEqual(f.clean("-.12"), decimal.Decimal("-0.12"))
self.assertEqual(f.clean("-00.12"), decimal.Decimal("-0.12"))
self.assertEqual(f.clean("-000.12"), decimal.Decimal("-0.12"))
with self.assertRaisesMessage(
ValidationError, "'Ensure that there are no more than 2 decimal places.'"
):
f.clean("-000.123")
with self.assertRaisesMessage(
ValidationError, "'Ensure that there are no more than 4 digits in total.'"
):
f.clean("-000.12345")
self.assertEqual(f.max_digits, 4)
self.assertEqual(f.decimal_places, 2)
self.assertIsNone(f.max_value)
self.assertIsNone(f.min_value)
def test_enter_a_number_error(self):
f = DecimalField(max_value=1, max_digits=4, decimal_places=2)
values = (
"-NaN",
"NaN",
"+NaN",
"-sNaN",
"sNaN",
"+sNaN",
"-Inf",
"Inf",
"+Inf",
"-Infinity",
"Infinity",
"+Infinity",
"a",
"łąść",
"1.0a",
"--0.12",
)
for value in values:
with (
self.subTest(value=value),
self.assertRaisesMessage(ValidationError, "'Enter a number.'"),
):
f.clean(value)
def test_decimalfield_2(self):
f = DecimalField(max_digits=4, decimal_places=2, required=False)
self.assertIsNone(f.clean(""))
self.assertIsNone(f.clean(None))
self.assertEqual(f.clean("1"), decimal.Decimal("1"))
self.assertEqual(f.max_digits, 4)
self.assertEqual(f.decimal_places, 2)
self.assertIsNone(f.max_value)
self.assertIsNone(f.min_value)
def test_decimalfield_3(self):
f = DecimalField(
max_digits=4,
decimal_places=2,
max_value=decimal.Decimal("1.5"),
min_value=decimal.Decimal("0.5"),
)
self.assertWidgetRendersTo(
f,
'<input step="0.01" name="f" min="0.5" max="1.5" type="number" id="id_f" '
"required>",
)
with self.assertRaisesMessage(
ValidationError, "'Ensure this value is less than or equal to 1.5.'"
):
f.clean("1.6")
with self.assertRaisesMessage(
ValidationError, "'Ensure this value is greater than or equal to 0.5.'"
):
f.clean("0.4")
self.assertEqual(f.clean("1.5"), decimal.Decimal("1.5"))
self.assertEqual(f.clean("0.5"), decimal.Decimal("0.5"))
self.assertEqual(f.clean(".5"), decimal.Decimal("0.5"))
self.assertEqual(f.clean("00.50"), decimal.Decimal("0.50"))
self.assertEqual(f.max_digits, 4)
self.assertEqual(f.decimal_places, 2)
self.assertEqual(f.max_value, decimal.Decimal("1.5"))
self.assertEqual(f.min_value, decimal.Decimal("0.5"))
def test_decimalfield_4(self):
f = DecimalField(decimal_places=2)
with self.assertRaisesMessage(
ValidationError, "'Ensure that there are no more than 2 decimal places.'"
):
f.clean("0.00000001")
def test_decimalfield_5(self):
f = DecimalField(max_digits=3)
# Leading whole zeros "collapse" to one digit.
self.assertEqual(f.clean("0000000.10"), decimal.Decimal("0.1"))
# But a leading 0 before the . doesn't count toward max_digits
self.assertEqual(f.clean("0000000.100"), decimal.Decimal("0.100"))
# Only leading whole zeros "collapse" to one digit.
self.assertEqual(f.clean("000000.02"), decimal.Decimal("0.02"))
with self.assertRaisesMessage(
ValidationError, "'Ensure that there are no more than 3 digits in total.'"
):
f.clean("000000.0002")
self.assertEqual(f.clean(".002"), decimal.Decimal("0.002"))
def test_decimalfield_6(self):
f = DecimalField(max_digits=2, decimal_places=2)
self.assertEqual(f.clean(".01"), decimal.Decimal(".01"))
msg = "'Ensure that there are no more than 0 digits before the decimal point.'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean("1.1")
def test_decimalfield_step_size_min_value(self):
f = DecimalField(
step_size=decimal.Decimal("0.3"),
min_value=decimal.Decimal("-0.4"),
)
self.assertWidgetRendersTo(
f,
'<input name="f" min="-0.4" step="0.3" type="number" id="id_f" required>',
)
msg = (
"Ensure this value is a multiple of step size 0.3, starting from -0.4, "
"e.g. -0.4, -0.1, 0.2, and so on."
)
with self.assertRaisesMessage(ValidationError, msg):
f.clean("1")
self.assertEqual(f.clean("0.2"), decimal.Decimal("0.2"))
self.assertEqual(f.clean(2), decimal.Decimal(2))
self.assertEqual(f.step_size, decimal.Decimal("0.3"))
def test_decimalfield_scientific(self):
f = DecimalField(max_digits=4, decimal_places=2)
with self.assertRaisesMessage(ValidationError, "Ensure that there are no more"):
f.clean("1E+2")
self.assertEqual(f.clean("1E+1"), decimal.Decimal("10"))
self.assertEqual(f.clean("1E-1"), decimal.Decimal("0.1"))
self.assertEqual(f.clean("0.546e+2"), decimal.Decimal("54.6"))
def test_decimalfield_widget_attrs(self):
f = DecimalField(max_digits=6, decimal_places=2)
self.assertEqual(f.widget_attrs(Widget()), {})
self.assertEqual(f.widget_attrs(NumberInput()), {"step": "0.01"})
f = DecimalField(max_digits=10, decimal_places=0)
self.assertEqual(f.widget_attrs(NumberInput()), {"step": "1"})
f = DecimalField(max_digits=19, decimal_places=19)
self.assertEqual(f.widget_attrs(NumberInput()), {"step": "1e-19"})
f = DecimalField(max_digits=20)
self.assertEqual(f.widget_attrs(NumberInput()), {"step": "any"})
f = DecimalField(max_digits=6, widget=NumberInput(attrs={"step": "0.01"}))
self.assertWidgetRendersTo(
f, '<input step="0.01" name="f" type="number" id="id_f" required>'
)
def test_decimalfield_localized(self):
"""
A localized DecimalField's widget renders to a text input without
number input specific attributes.
"""
f = DecimalField(localize=True)
self.assertWidgetRendersTo(f, '<input id="id_f" name="f" type="text" required>')
def test_decimalfield_changed(self):
f = DecimalField(max_digits=2, decimal_places=2)
d = decimal.Decimal("0.1")
self.assertFalse(f.has_changed(d, "0.10"))
self.assertTrue(f.has_changed(d, "0.101"))
with translation.override("fr"):
f = DecimalField(max_digits=2, decimal_places=2, localize=True)
localized_d = formats.localize_input(d) # -> '0,1' in French
self.assertFalse(f.has_changed(d, localized_d))
@override_settings(DECIMAL_SEPARATOR=",")
def test_decimalfield_support_decimal_separator(self):
with translation.override(None):
f = DecimalField(localize=True)
self.assertEqual(f.clean("1001,10"), decimal.Decimal("1001.10"))
self.assertEqual(f.clean("1001.10"), decimal.Decimal("1001.10"))
@override_settings(
DECIMAL_SEPARATOR=",",
USE_THOUSAND_SEPARATOR=True,
THOUSAND_SEPARATOR=".",
)
def test_decimalfield_support_thousands_separator(self):
with translation.override(None):
f = DecimalField(localize=True)
self.assertEqual(f.clean("1.001,10"), decimal.Decimal("1001.10"))
msg = "'Enter a number.'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean("1,001.1")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_uuidfield.py | tests/forms_tests/field_tests/test_uuidfield.py | import uuid
from django.core.exceptions import ValidationError
from django.forms import UUIDField
from django.test import SimpleTestCase
class UUIDFieldTest(SimpleTestCase):
def test_uuidfield_1(self):
field = UUIDField()
value = field.clean("550e8400e29b41d4a716446655440000")
self.assertEqual(value, uuid.UUID("550e8400e29b41d4a716446655440000"))
def test_clean_value_with_dashes(self):
field = UUIDField()
value = field.clean("550e8400-e29b-41d4-a716-446655440000")
self.assertEqual(value, uuid.UUID("550e8400e29b41d4a716446655440000"))
def test_uuidfield_2(self):
field = UUIDField(required=False)
self.assertIsNone(field.clean(""))
self.assertIsNone(field.clean(None))
def test_uuidfield_3(self):
field = UUIDField()
with self.assertRaisesMessage(ValidationError, "Enter a valid UUID."):
field.clean("550e8400")
def test_uuidfield_4(self):
field = UUIDField()
value = field.prepare_value(uuid.UUID("550e8400e29b41d4a716446655440000"))
self.assertEqual(value, "550e8400-e29b-41d4-a716-446655440000")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/__init__.py | tests/forms_tests/field_tests/__init__.py | from django import forms
class FormFieldAssertionsMixin:
def assertWidgetRendersTo(self, field, to):
class Form(forms.Form):
f = field
self.assertHTMLEqual(str(Form()["f"]), to)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_floatfield.py | tests/forms_tests/field_tests/test_floatfield.py | from django.core.exceptions import ValidationError
from django.forms import FloatField, NumberInput
from django.test import SimpleTestCase
from django.test.selenium import SeleniumTestCase
from django.test.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("")
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.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.'"):
f.clean("a")
self.assertEqual(1.0, f.clean("1.0 "))
self.assertEqual(1.0, f.clean(" 1.0"))
self.assertEqual(1.0, f.clean(" 1.0 "))
with self.assertRaisesMessage(ValidationError, "'Enter a number.'"):
f.clean("1.0a")
self.assertIsNone(f.max_value)
self.assertIsNone(f.min_value)
with self.assertRaisesMessage(ValidationError, "'Enter a number.'"):
f.clean("Infinity")
with self.assertRaisesMessage(ValidationError, "'Enter a number.'"):
f.clean("NaN")
with self.assertRaisesMessage(ValidationError, "'Enter a number.'"):
f.clean("-Inf")
def test_floatfield_2(self):
f = FloatField(required=False)
self.assertIsNone(f.clean(""))
self.assertIsNone(f.clean(None))
self.assertEqual(1.0, f.clean("1"))
self.assertIsNone(f.max_value)
self.assertIsNone(f.min_value)
def test_floatfield_3(self):
f = FloatField(max_value=1.5, min_value=0.5)
self.assertWidgetRendersTo(
f,
'<input step="any" name="f" min="0.5" max="1.5" type="number" id="id_f" '
"required>",
)
with self.assertRaisesMessage(
ValidationError, "'Ensure this value is less than or equal to 1.5.'"
):
f.clean("1.6")
with self.assertRaisesMessage(
ValidationError, "'Ensure this value is greater than or equal to 0.5.'"
):
f.clean("0.4")
self.assertEqual(1.5, f.clean("1.5"))
self.assertEqual(0.5, f.clean("0.5"))
self.assertEqual(f.max_value, 1.5)
self.assertEqual(f.min_value, 0.5)
def test_floatfield_4(self):
f = FloatField(step_size=0.02)
self.assertWidgetRendersTo(
f,
'<input name="f" step="0.02" type="number" id="id_f" required>',
)
msg = "'Ensure this value is a multiple of step size 0.02.'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean("0.01")
self.assertEqual(2.34, f.clean("2.34"))
self.assertEqual(2.1, f.clean("2.1"))
self.assertEqual(-0.50, f.clean("-.5"))
self.assertEqual(-1.26, f.clean("-1.26"))
self.assertEqual(f.step_size, 0.02)
def test_floatfield_step_size_min_value(self):
f = FloatField(step_size=0.02, min_value=0.01)
msg = (
"Ensure this value is a multiple of step size 0.02, starting from 0.01, "
"e.g. 0.01, 0.03, 0.05, and so on."
)
with self.assertRaisesMessage(ValidationError, msg):
f.clean("0.02")
self.assertEqual(f.clean("2.33"), 2.33)
self.assertEqual(f.clean("0.11"), 0.11)
self.assertEqual(f.step_size, 0.02)
def test_floatfield_widget_attrs(self):
f = FloatField(widget=NumberInput(attrs={"step": 0.01, "max": 1.0, "min": 0.0}))
self.assertWidgetRendersTo(
f,
'<input step="0.01" name="f" min="0.0" max="1.0" type="number" id="id_f" '
"required>",
)
def test_floatfield_localized(self):
"""
A localized FloatField's widget renders to a text input without any
number input specific attributes.
"""
f = FloatField(localize=True)
self.assertWidgetRendersTo(f, '<input id="id_f" name="f" type="text" required>')
def test_floatfield_changed(self):
f = FloatField()
n = 4.35
self.assertFalse(f.has_changed(n, "4.3500"))
with translation.override("fr"):
f = FloatField(localize=True)
localized_n = formats.localize_input(n) # -> '4,35' in French
self.assertFalse(f.has_changed(n, localized_n))
@override_settings(DECIMAL_SEPARATOR=",")
def test_floatfield_support_decimal_separator(self):
with translation.override(None):
f = FloatField(localize=True)
self.assertEqual(f.clean("1001,10"), 1001.10)
self.assertEqual(f.clean("1001.10"), 1001.10)
@override_settings(
DECIMAL_SEPARATOR=",",
USE_THOUSAND_SEPARATOR=True,
THOUSAND_SEPARATOR=".",
)
def test_floatfield_support_thousands_separator(self):
with translation.override(None):
f = FloatField(localize=True)
self.assertEqual(f.clean("1.001,10"), 1001.10)
msg = "'Enter a number.'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean("1,001.1")
@override_settings(ROOT_URLCONF="forms_tests.urls")
class FloatFieldHTMLTest(SeleniumTestCase):
available_apps = ["forms_tests"]
def test_float_field_rendering_passes_client_side_validation(self):
"""
Rendered widget allows non-integer value with the client-side
validation.
"""
from selenium.webdriver.common.by import By
self.selenium.get(self.live_server_url + reverse("form_view"))
number_input = self.selenium.find_element(By.ID, "id_number")
number_input.send_keys("0.5")
is_valid = self.selenium.execute_script(
"return document.getElementById('id_number').checkValidity()"
)
self.assertTrue(is_valid)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_datefield.py | tests/forms_tests/field_tests/test_datefield.py | import sys
from datetime import date, datetime
from django.core.exceptions import ValidationError
from django.forms import DateField, Form, HiddenInput, SelectDateWidget
from django.test import SimpleTestCase
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" rendering 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"})
self.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.is_valid())
self.assertEqual(c.errors, {"mydate": ["Enter a valid date."]})
# label tag is correctly associated with month dropdown
d = GetDate({"mydate_month": "1", "mydate_day": "1", "mydate_year": "2010"})
self.assertIn('<label for="id_mydate_month">', d.as_p())
# Inputs raising an OverflowError.
e = GetDate(
{
"mydate_month": str(sys.maxsize + 1),
"mydate_day": "31",
"mydate_year": "2010",
}
)
self.assertIs(e.is_valid(), False)
self.assertEqual(e.errors, {"mydate": ["Enter a valid date."]})
@translation.override("nl")
def test_l10n_date_changed(self):
"""
DateField.has_changed() with SelectDateWidget works with a localized
date format (#17165).
"""
# With Field.show_hidden_initial=False
b = GetDate(
{
"mydate_year": "2008",
"mydate_month": "4",
"mydate_day": "1",
},
initial={"mydate": date(2008, 4, 1)},
)
self.assertFalse(b.has_changed())
b = GetDate(
{
"mydate_year": "2008",
"mydate_month": "4",
"mydate_day": "2",
},
initial={"mydate": date(2008, 4, 1)},
)
self.assertTrue(b.has_changed())
# With Field.show_hidden_initial=True
class GetDateShowHiddenInitial(Form):
mydate = DateField(widget=SelectDateWidget, show_hidden_initial=True)
b = GetDateShowHiddenInitial(
{
"mydate_year": "2008",
"mydate_month": "4",
"mydate_day": "1",
"initial-mydate": HiddenInput().format_value(date(2008, 4, 1)),
},
initial={"mydate": date(2008, 4, 1)},
)
self.assertFalse(b.has_changed())
b = GetDateShowHiddenInitial(
{
"mydate_year": "2008",
"mydate_month": "4",
"mydate_day": "22",
"initial-mydate": HiddenInput().format_value(date(2008, 4, 1)),
},
initial={"mydate": date(2008, 4, 1)},
)
self.assertTrue(b.has_changed())
b = GetDateShowHiddenInitial(
{
"mydate_year": "2008",
"mydate_month": "4",
"mydate_day": "22",
"initial-mydate": HiddenInput().format_value(date(2008, 4, 1)),
},
initial={"mydate": date(2008, 4, 22)},
)
self.assertTrue(b.has_changed())
b = GetDateShowHiddenInitial(
{
"mydate_year": "2008",
"mydate_month": "4",
"mydate_day": "22",
"initial-mydate": HiddenInput().format_value(date(2008, 4, 22)),
},
initial={"mydate": date(2008, 4, 1)},
)
self.assertFalse(b.has_changed())
@translation.override("nl")
def test_l10n_invalid_date_in(self):
# Invalid dates shouldn't be allowed
a = GetDate({"mydate_month": "2", "mydate_day": "31", "mydate_year": "2010"})
self.assertFalse(a.is_valid())
# 'Geef een geldige datum op.' = 'Enter a valid date.'
self.assertEqual(a.errors, {"mydate": ["Voer een geldige datum in."]})
@translation.override("nl")
def test_form_label_association(self):
# label tag is correctly associated with first rendered dropdown
a = GetDate({"mydate_month": "1", "mydate_day": "1", "mydate_year": "2010"})
self.assertIn('<label for="id_mydate_day">', a.as_p())
def test_datefield_1(self):
f = DateField()
self.assertEqual(date(2006, 10, 25), f.clean(date(2006, 10, 25)))
self.assertEqual(date(2006, 10, 25), f.clean(datetime(2006, 10, 25, 14, 30)))
self.assertEqual(
date(2006, 10, 25), f.clean(datetime(2006, 10, 25, 14, 30, 59))
)
self.assertEqual(
date(2006, 10, 25), f.clean(datetime(2006, 10, 25, 14, 30, 59, 200))
)
self.assertEqual(date(2006, 10, 25), f.clean("2006-10-25"))
self.assertEqual(date(2006, 10, 25), f.clean("10/25/2006"))
self.assertEqual(date(2006, 10, 25), f.clean("10/25/06"))
self.assertEqual(date(2006, 10, 25), f.clean("Oct 25 2006"))
self.assertEqual(date(2006, 10, 25), f.clean("October 25 2006"))
self.assertEqual(date(2006, 10, 25), f.clean("October 25, 2006"))
self.assertEqual(date(2006, 10, 25), f.clean("25 October 2006"))
self.assertEqual(date(2006, 10, 25), f.clean("25 October, 2006"))
with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"):
f.clean("2006-4-31")
with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"):
f.clean("200a-10-25")
with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"):
f.clean("25/10/06")
with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"):
f.clean("0-0-0")
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
def test_datefield_2(self):
f = DateField(required=False)
self.assertIsNone(f.clean(None))
self.assertEqual("None", repr(f.clean(None)))
self.assertIsNone(f.clean(""))
self.assertEqual("None", repr(f.clean("")))
def test_datefield_3(self):
f = DateField(input_formats=["%Y %m %d"])
self.assertEqual(date(2006, 10, 25), f.clean(date(2006, 10, 25)))
self.assertEqual(date(2006, 10, 25), f.clean(datetime(2006, 10, 25, 14, 30)))
self.assertEqual(date(2006, 10, 25), f.clean("2006 10 25"))
with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"):
f.clean("2006-10-25")
with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"):
f.clean("10/25/2006")
with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"):
f.clean("10/25/06")
def test_datefield_4(self):
# Test whitespace stripping behavior (#5714)
f = DateField()
self.assertEqual(date(2006, 10, 25), f.clean(" 10/25/2006 "))
self.assertEqual(date(2006, 10, 25), f.clean(" 10/25/06 "))
self.assertEqual(date(2006, 10, 25), f.clean(" Oct 25 2006 "))
self.assertEqual(date(2006, 10, 25), f.clean(" October 25 2006 "))
self.assertEqual(date(2006, 10, 25), f.clean(" October 25, 2006 "))
self.assertEqual(date(2006, 10, 25), f.clean(" 25 October 2006 "))
with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"):
f.clean(" ")
def test_datefield_5(self):
# Test null bytes (#18982)
f = DateField()
with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"):
f.clean("a\x00b")
def test_datefield_changed(self):
format = "%d/%m/%Y"
f = DateField(input_formats=[format])
d = date(2007, 9, 17)
self.assertFalse(f.has_changed(d, "17/09/2007"))
def test_datefield_strptime(self):
"""field.strptime() doesn't raise a UnicodeEncodeError (#16123)"""
f = DateField()
try:
f.strptime("31 мая 2011", "%d-%b-%y")
except Exception as e:
# assertIsInstance or assertRaises cannot be used because
# UnicodeEncodeError is a subclass of ValueError
self.assertEqual(e.__class__, ValueError)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_timefield.py | tests/forms_tests/field_tests/test_timefield.py | import datetime
from django.core.exceptions import ValidationError
from django.forms import TimeField
from django.test import SimpleTestCase
from . import FormFieldAssertionsMixin
class TimeFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
def test_timefield_1(self):
f = TimeField()
self.assertEqual(datetime.time(14, 25), f.clean(datetime.time(14, 25)))
self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59)))
self.assertEqual(datetime.time(14, 25), f.clean("14:25"))
self.assertEqual(datetime.time(14, 25, 59), f.clean("14:25:59"))
with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"):
f.clean("hello")
with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"):
f.clean("1:24 p.m.")
def test_timefield_2(self):
f = TimeField(input_formats=["%I:%M %p"])
self.assertEqual(datetime.time(14, 25), f.clean(datetime.time(14, 25)))
self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59)))
self.assertEqual(datetime.time(4, 25), f.clean("4:25 AM"))
self.assertEqual(datetime.time(16, 25), f.clean("4:25 PM"))
with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"):
f.clean("14:30:45")
def test_timefield_3(self):
f = TimeField()
# Test whitespace stripping behavior (#5714)
self.assertEqual(datetime.time(14, 25), f.clean(" 14:25 "))
self.assertEqual(datetime.time(14, 25, 59), f.clean(" 14:25:59 "))
with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"):
f.clean(" ")
def test_timefield_changed(self):
t1 = datetime.time(12, 51, 34, 482548)
t2 = datetime.time(12, 51)
f = TimeField(input_formats=["%H:%M", "%H:%M %p"])
self.assertTrue(f.has_changed(t1, "12:51"))
self.assertFalse(f.has_changed(t2, "12:51"))
self.assertFalse(f.has_changed(t2, "12:51 PM"))
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_urlfield.py | tests/forms_tests/field_tests/test_urlfield.py | from django.core.exceptions import ValidationError
from django.forms import URLField
from django.test import SimpleTestCase
from . import FormFieldAssertionsMixin
class URLFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
def test_urlfield_widget(self):
f = URLField()
self.assertWidgetRendersTo(f, '<input type="url" name="f" id="id_f" required>')
def test_urlfield_widget_max_min_length(self):
f = URLField(min_length=15, max_length=20)
self.assertEqual("http://example.com", f.clean("http://example.com"))
self.assertWidgetRendersTo(
f,
'<input id="id_f" type="url" name="f" maxlength="20" '
'minlength="15" required>',
)
msg = "'Ensure this value has at least 15 characters (it has 12).'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean("http://f.com")
msg = "'Ensure this value has at most 20 characters (it has 37).'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean("http://abcdefghijklmnopqrstuvwxyz.com")
def test_urlfield_clean(self):
f = URLField(required=False)
tests = [
("http://localhost", "http://localhost"),
("http://example.com", "http://example.com"),
("http://example.com/test", "http://example.com/test"),
("http://example.com.", "http://example.com."),
("http://www.example.com", "http://www.example.com"),
("http://www.example.com:8000/test", "http://www.example.com:8000/test"),
(
"http://example.com?some_param=some_value",
"http://example.com?some_param=some_value",
),
("valid-with-hyphens.com", "https://valid-with-hyphens.com"),
("subdomain.domain.com", "https://subdomain.domain.com"),
("http://200.8.9.10", "http://200.8.9.10"),
("http://200.8.9.10:8000/test", "http://200.8.9.10:8000/test"),
("http://valid-----hyphens.com", "http://valid-----hyphens.com"),
(
"http://some.idn.xyzäöüßabc.domain.com:123/blah",
"http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah",
),
(
"www.example.com/s/http://code.djangoproject.com/ticket/13804",
"https://www.example.com/s/http://code.djangoproject.com/ticket/13804",
),
# Normalization.
("http://example.com/ ", "http://example.com/"),
# Valid IDN.
("http://עברית.idn.icann.org/", "http://עברית.idn.icann.org/"),
("http://sãopaulo.com/", "http://sãopaulo.com/"),
("http://sãopaulo.com.br/", "http://sãopaulo.com.br/"),
("http://пример.испытание/", "http://пример.испытание/"),
("http://مثال.إختبار/", "http://مثال.إختبار/"),
("http://例子.测试/", "http://例子.测试/"),
("http://例子.測試/", "http://例子.測試/"),
(
"http://उदाहरण.परीक्षा/",
"http://उदाहरण.परीक्षा/",
),
("http://例え.テスト/", "http://例え.テスト/"),
("http://مثال.آزمایشی/", "http://مثال.آزمایشی/"),
("http://실례.테스트/", "http://실례.테스트/"),
("http://العربية.idn.icann.org/", "http://العربية.idn.icann.org/"),
# IPv6.
("http://[12:34::3a53]/", "http://[12:34::3a53]/"),
("http://[a34:9238::]:8080/", "http://[a34:9238::]:8080/"),
]
for url, expected in tests:
with self.subTest(url=url):
self.assertEqual(f.clean(url), expected)
def test_urlfield_clean_invalid(self):
f = URLField()
tests = [
"foo",
"com.",
".",
"http://",
"http://example",
"http://example.",
"http://.com",
"http://invalid-.com",
"http://-invalid.com",
"http://inv-.alid-.com",
"http://inv-.-alid.com",
"[a",
"http://[a",
# Non-string.
23,
# Hangs "forever" before fixing a catastrophic backtracking,
# see #11198.
"http://%s" % ("X" * 60,),
# A second example, to make sure the problem is really addressed,
# even on domains that don't fail the domain label length check in
# the regex.
"http://%s" % ("X" * 200,),
# urlsplit() raises ValueError.
"////]@N.AN",
# Empty hostname.
"#@A.bO",
]
msg = "'Enter a valid URL.'"
for value in tests:
with self.subTest(value=value):
with self.assertRaisesMessage(ValidationError, msg):
f.clean(value)
def test_urlfield_clean_required(self):
f = URLField()
msg = "'This field is required.'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean(None)
with self.assertRaisesMessage(ValidationError, msg):
f.clean("")
def test_urlfield_clean_not_required(self):
f = URLField(required=False)
self.assertEqual(f.clean(None), "")
self.assertEqual(f.clean(""), "")
def test_urlfield_strip_on_none_value(self):
f = URLField(required=False, empty_value=None)
self.assertIsNone(f.clean(""))
self.assertIsNone(f.clean(None))
def test_urlfield_unable_to_set_strip_kwarg(self):
msg = "got multiple values for keyword argument 'strip'"
with self.assertRaisesMessage(TypeError, msg):
URLField(strip=False)
def test_urlfield_assume_scheme(self):
f = URLField()
self.assertEqual(f.clean("example.com"), "https://example.com")
f = URLField(assume_scheme="http")
self.assertEqual(f.clean("example.com"), "http://example.com")
f = URLField(assume_scheme="https")
self.assertEqual(f.clean("example.com"), "https://example.com")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_imagefield.py | tests/forms_tests/field_tests/test_imagefield.py | import os
import unittest
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile 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(FormFieldAssertionsMixin, 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 img_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)
self.assertEqual("image/png", uploaded_file.content_type)
def test_imagefield_annotate_with_bitmap_image_after_clean(self):
"""
This also tests the situation when Pillow doesn't detect the MIME type
of the image (#24948).
"""
from PIL.BmpImagePlugin import BmpImageFile
try:
Image.register_mime(BmpImageFile.format, None)
f = ImageField()
img_path = get_img_path("filepath_test_files/1x1.bmp")
with open(img_path, "rb") as img_file:
img_data = img_file.read()
img_file = SimpleUploadedFile("1x1.bmp", img_data)
img_file.content_type = "text/plain"
uploaded_file = f.clean(img_file)
self.assertEqual("BMP", uploaded_file.image.format)
self.assertIsNone(uploaded_file.content_type)
finally:
Image.register_mime(BmpImageFile.format, "image/bmp")
def test_file_extension_validation(self):
f = ImageField()
img_path = get_img_path("filepath_test_files/1x1.png")
with open(img_path, "rb") as img_file:
img_data = img_file.read()
img_file = SimpleUploadedFile("1x1.txt", img_data)
with self.assertRaisesMessage(
ValidationError, "File extension “txt” is not allowed."
):
f.clean(img_file)
def test_corrupted_image(self):
f = ImageField()
img_file = SimpleUploadedFile("not_an_image.jpg", b"not an image")
msg = (
"Upload a valid image. The file you uploaded was either not an "
"image or a corrupted image."
)
with self.assertRaisesMessage(ValidationError, msg):
f.clean(img_file)
with TemporaryUploadedFile(
"not_an_image_tmp.png", "text/plain", 1, "utf-8"
) as tmp_file:
with self.assertRaisesMessage(ValidationError, msg):
f.clean(tmp_file)
def test_widget_attrs_default_accept(self):
f = ImageField()
# Nothing added for non-FileInput widgets.
self.assertEqual(f.widget_attrs(Widget()), {})
self.assertEqual(f.widget_attrs(FileInput()), {"accept": "image/*"})
self.assertEqual(f.widget_attrs(ClearableFileInput()), {"accept": "image/*"})
self.assertWidgetRendersTo(
f, '<input type="file" name="f" accept="image/*" required id="id_f" />'
)
def test_widget_attrs_accept_specified(self):
f = ImageField(widget=FileInput(attrs={"accept": "image/png"}))
self.assertEqual(f.widget_attrs(f.widget), {})
self.assertWidgetRendersTo(
f, '<input type="file" name="f" accept="image/png" required id="id_f" />'
)
def test_widget_attrs_accept_false(self):
f = ImageField(widget=FileInput(attrs={"accept": False}))
self.assertEqual(f.widget_attrs(f.widget), {})
self.assertWidgetRendersTo(
f, '<input type="file" name="f" required id="id_f" />'
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/test_filefield.py | tests/forms_tests/field_tests/test_filefield.py | import pickle
import unittest
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.validators import validate_image_file_extension
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("", "")
self.assertEqual("files/test1.pdf", f.clean("", "files/test1.pdf"))
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
with self.assertRaisesMessage(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 = SimpleUploadedFile(None, b"")
file._name = ""
with self.assertRaisesMessage(ValidationError, no_file_msg):
f.clean(file)
with self.assertRaisesMessage(ValidationError, no_file_msg):
f.clean(file, "")
self.assertEqual("files/test3.pdf", f.clean(None, "files/test3.pdf"))
with self.assertRaisesMessage(ValidationError, no_file_msg):
f.clean("some content that is not a file")
with self.assertRaisesMessage(
ValidationError, "'The submitted file is empty.'"
):
f.clean(SimpleUploadedFile("name", None))
with self.assertRaisesMessage(
ValidationError, "'The submitted file is empty.'"
):
f.clean(SimpleUploadedFile("name", b""))
self.assertEqual(
SimpleUploadedFile,
type(f.clean(SimpleUploadedFile("name", b"Some File Content"))),
)
self.assertIsInstance(
f.clean(
SimpleUploadedFile(
"我隻氣墊船裝滿晒鱔.txt",
"मेरी मँडराने वाली नाव सर्पमीनों से भरी ह".encode(),
)
),
SimpleUploadedFile,
)
self.assertIsInstance(
f.clean(
SimpleUploadedFile("name", b"Some File Content"), "files/test4.pdf"
),
SimpleUploadedFile,
)
def test_filefield_2(self):
f = FileField(max_length=5)
with self.assertRaisesMessage(
ValidationError,
"'Ensure this filename has at most 5 characters (it has 18).'",
):
f.clean(SimpleUploadedFile("test_maxlength.txt", b"hello world"))
self.assertEqual("files/test1.pdf", f.clean("", "files/test1.pdf"))
self.assertEqual("files/test2.pdf", f.clean(None, "files/test2.pdf"))
self.assertIsInstance(
f.clean(SimpleUploadedFile("name", b"Some File Content")),
SimpleUploadedFile,
)
def test_filefield_3(self):
f = FileField(allow_empty_file=True)
self.assertIsInstance(
f.clean(SimpleUploadedFile("name", b"")), SimpleUploadedFile
)
def test_filefield_changed(self):
"""
The value of data will more than likely come from request.FILES. The
value of initial data will likely be a filename stored in the database.
Since its value is of no use to a FileField it is ignored.
"""
f = FileField()
# No file was uploaded and no initial data.
self.assertFalse(f.has_changed("", None))
# A file was uploaded and no initial data.
self.assertTrue(
f.has_changed("", {"filename": "resume.txt", "content": "My resume"})
)
# A file was not uploaded, but there is initial data
self.assertFalse(f.has_changed("resume.txt", None))
# A file was uploaded and there is initial data (file identity is not
# dealt with here)
self.assertTrue(
f.has_changed(
"resume.txt", {"filename": "resume.txt", "content": "My resume"}
)
)
def test_disabled_has_changed(self):
f = FileField(disabled=True)
self.assertIs(f.has_changed("x", "y"), False)
def test_file_picklable(self):
self.assertIsInstance(pickle.loads(pickle.dumps(FileField())), FileField)
class MultipleFileInput(FileInput):
allow_multiple_selected = True
class MultipleFileField(FileField):
def __init__(self, *args, **kwargs):
kwargs.setdefault("widget", MultipleFileInput())
super().__init__(*args, **kwargs)
def clean(self, data, initial=None):
single_file_clean = super().clean
if isinstance(data, (list, tuple)):
result = [single_file_clean(d, initial) for d in data]
else:
result = single_file_clean(data, initial)
return result
class MultipleFileFieldTest(SimpleTestCase):
def test_file_multiple(self):
f = MultipleFileField()
files = [
SimpleUploadedFile("name1", b"Content 1"),
SimpleUploadedFile("name2", b"Content 2"),
]
self.assertEqual(f.clean(files), files)
def test_file_multiple_empty(self):
f = MultipleFileField()
files = [
SimpleUploadedFile("empty", b""),
SimpleUploadedFile("nonempty", b"Some Content"),
]
msg = "'The submitted file is empty.'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean(files)
with self.assertRaisesMessage(ValidationError, msg):
f.clean(files[::-1])
@unittest.skipUnless(HAS_PILLOW, "Pillow not installed")
def test_file_multiple_validation(self):
f = MultipleFileField(validators=[validate_image_file_extension])
good_files = [
SimpleUploadedFile("image1.jpg", b"fake JPEG"),
SimpleUploadedFile("image2.png", b"faux image"),
SimpleUploadedFile("image3.bmp", b"fraudulent bitmap"),
]
self.assertEqual(f.clean(good_files), good_files)
evil_files = [
SimpleUploadedFile("image1.sh", b"#!/bin/bash -c 'echo pwned!'\n"),
SimpleUploadedFile("image2.png", b"faux image"),
SimpleUploadedFile("image3.jpg", b"fake JPEG"),
]
evil_rotations = (
evil_files[i:] + evil_files[:i] # Rotate by i.
for i in range(len(evil_files))
)
msg = "File extension “sh” is not allowed. Allowed extensions are: "
for rotated_evil_files in evil_rotations:
with self.assertRaisesMessage(ValidationError, msg):
f.clean(rotated_evil_files)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/filepathfield_test_dir/ab.py | tests/forms_tests/field_tests/filepathfield_test_dir/ab.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/filepathfield_test_dir/b.py | tests/forms_tests/field_tests/filepathfield_test_dir/b.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/filepathfield_test_dir/a.py | tests/forms_tests/field_tests/filepathfield_test_dir/a.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/filepathfield_test_dir/__init__.py | tests/forms_tests/field_tests/filepathfield_test_dir/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/filepathfield_test_dir/c/d.py | tests/forms_tests/field_tests/filepathfield_test_dir/c/d.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/filepathfield_test_dir/c/e.py | tests/forms_tests/field_tests/filepathfield_test_dir/c/e.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/filepathfield_test_dir/c/__init__.py | tests/forms_tests/field_tests/filepathfield_test_dir/c/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/filepathfield_test_dir/c/f/__init__.py | tests/forms_tests/field_tests/filepathfield_test_dir/c/f/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/filepathfield_test_dir/c/f/g.py | tests/forms_tests/field_tests/filepathfield_test_dir/c/f/g.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/filepathfield_test_dir/h/__init__.py | tests/forms_tests/field_tests/filepathfield_test_dir/h/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/field_tests/filepathfield_test_dir/j/__init__.py | tests/forms_tests/field_tests/filepathfield_test_dir/j/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_searchinput.py | tests/forms_tests/widget_tests/test_searchinput.py | from django.forms import SearchInput
from .base import WidgetTest
class SearchInputTest(WidgetTest):
widget = SearchInput()
def test_render(self):
self.check_html(
self.widget, "search", "", html='<input type="search" name="search">'
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_splitdatetimewidget.py | tests/forms_tests/widget_tests/test_splitdatetimewidget.py | from datetime import date, datetime, time
from django.forms import Form, SplitDateTimeField, SplitDateTimeWidget
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_1">'),
)
def test_render_datetime(self):
self.check_html(
self.widget,
"date",
datetime(2006, 1, 10, 7, 30),
html=(
'<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,
"date",
[date(2006, 1, 10), time(7, 30)],
html=(
'<input type="text" name="date_0" value="2006-01-10">'
'<input type="text" name="date_1" value="07:30:00">'
),
)
def test_constructor_attrs(self):
widget = SplitDateTimeWidget(attrs={"class": "pretty"})
self.check_html(
widget,
"date",
datetime(2006, 1, 10, 7, 30),
html=(
'<input type="text" class="pretty" value="2006-01-10" name="date_0">'
'<input type="text" class="pretty" value="07:30:00" name="date_1">'
),
)
def test_constructor_different_attrs(self):
html = (
'<input type="text" class="foo" value="2006-01-10" name="date_0">'
'<input type="text" class="bar" value="07:30:00" name="date_1">'
)
widget = SplitDateTimeWidget(
date_attrs={"class": "foo"}, time_attrs={"class": "bar"}
)
self.check_html(widget, "date", datetime(2006, 1, 10, 7, 30), html=html)
widget = SplitDateTimeWidget(
date_attrs={"class": "foo"}, attrs={"class": "bar"}
)
self.check_html(widget, "date", datetime(2006, 1, 10, 7, 30), html=html)
widget = SplitDateTimeWidget(
time_attrs={"class": "bar"}, attrs={"class": "foo"}
)
self.check_html(widget, "date", datetime(2006, 1, 10, 7, 30), html=html)
def test_formatting(self):
"""
Use 'date_format' and 'time_format' to change the way a value is
displayed.
"""
widget = SplitDateTimeWidget(
date_format="%d/%m/%Y",
time_format="%H:%M",
)
self.check_html(
widget,
"date",
datetime(2006, 1, 10, 7, 30),
html=(
'<input type="text" name="date_0" value="10/01/2006">'
'<input type="text" name="date_1" value="07:30">'
),
)
self.check_html(
widget,
"date",
datetime(2006, 1, 10, 7, 30),
html=(
'<input type="text" name="date_0" value="10/01/2006">'
'<input type="text" name="date_1" value="07:30">'
),
)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = SplitDateTimeField(widget=self.widget)
form = TestForm()
self.assertIs(self.widget.use_fieldset, True)
self.assertHTMLEqual(
'<div><fieldset><legend>Field:</legend><input type="text" '
'name="field_0" required id="id_field_0"><input type="text" '
'name="field_1" required id="id_field_1"></fieldset></div>',
form.render(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_passwordinput.py | tests/forms_tests/widget_tests/test_passwordinput.py | from django.forms import 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_value_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_value=True)
self.check_html(
widget, "password", "", html='<input type="password" name="password">'
)
self.check_html(
widget, "password", None, html='<input type="password" name="password">'
)
self.check_html(
widget,
"password",
"test@example.com",
html='<input type="password" name="password" value="test@example.com">',
)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = CharField(widget=self.widget)
form = TestForm()
self.assertIs(self.widget.use_fieldset, False)
self.assertHTMLEqual(
'<div><label for="id_field">Field:</label>'
'<input type="password" name="field" required id="id_field"></div>',
form.render(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_numberinput.py | tests/forms_tests/widget_tests/test_numberinput.py | from 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" '
'step="9999">',
)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = CharField(widget=self.widget)
form = TestForm()
self.assertIs(self.widget.use_fieldset, False)
self.assertHTMLEqual(
'<div><label for="id_field">Field:</label>'
'<input id="id_field" max="12345" min="1234" '
'name="field" required step="9999" type="number"></div>',
form.render(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_input.py | tests/forms_tests/widget_tests/test_input.py | from django.forms.widgets import Input
from .base import WidgetTest
class InputTests(WidgetTest):
def test_attrs_with_type(self):
attrs = {"type": "date"}
widget = Input(attrs)
self.check_html(
widget, "name", "value", '<input type="date" name="name" value="value">'
)
# reuse the same attrs for another widget
self.check_html(
Input(attrs),
"name",
"value",
'<input type="date" name="name" value="value">',
)
attrs["type"] = "number" # shouldn't change the widget type
self.check_html(
widget, "name", "value", '<input type="date" name="name" value="value">'
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_nullbooleanselect.py | tests/forms_tests/widget_tests/test_nullbooleanselect.py | from django.forms import Form, NullBooleanField, NullBooleanSelect
from django.utils import translation
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):
self.check_html(
self.widget,
"is_cool",
False,
html=(
"""<select name="is_cool">
<option value="unknown">Unknown</option>
<option value="true">Yes</option>
<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">
<option value="unknown" selected>Unknown</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>"""
),
)
def test_render_value_unknown(self):
self.check_html(
self.widget,
"is_cool",
"unknown",
html=(
"""<select name="is_cool">
<option value="unknown" selected>Unknown</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>"""
),
)
def test_render_value_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_value_false(self):
self.check_html(
self.widget,
"is_cool",
"false",
html=(
"""<select name="is_cool">
<option value="unknown">Unknown</option>
<option value="true">Yes</option>
<option value="false" selected>No</option>
</select>"""
),
)
def test_render_value_1(self):
self.check_html(
self.widget,
"is_cool",
"1",
html=(
"""<select name="is_cool">
<option value="unknown" selected>Unknown</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>"""
),
)
def test_render_value_2(self):
self.check_html(
self.widget,
"is_cool",
"2",
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_value_3(self):
self.check_html(
self.widget,
"is_cool",
"3",
html=(
"""<select name="is_cool">
<option value="unknown">Unknown</option>
<option value="true">Yes</option>
<option value="false" selected>No</option>
</select>"""
),
)
def test_l10n(self):
"""
The NullBooleanSelect widget's options are lazily localized (#17190).
"""
widget = NullBooleanSelect()
with translation.override("de-at"):
self.check_html(
widget,
"id_bool",
True,
html=(
"""
<select name="id_bool">
<option value="unknown">Unbekannt</option>
<option value="true" selected>Ja</option>
<option value="false">Nein</option>
</select>
"""
),
)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = NullBooleanField(widget=self.widget)
form = TestForm()
self.assertIs(self.widget.use_fieldset, False)
self.assertHTMLEqual(
'<div><label for="id_field">Field:</label>'
'<select name="field" id="id_field">'
'<option value="unknown" selected>Unknown</option>'
'<option value="true">Yes</option>'
'<option value="false">No</option></select></div>',
form.render(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_multiwidget.py | tests/forms_tests/widget_tests/test_multiwidget.py | import copy
from datetime import datetime
from django.forms import (
CharField,
FileInput,
Form,
MultipleChoiceField,
MultiValueField,
MultiWidget,
RadioSelect,
SelectMultiple,
SplitDateTimeField,
SplitDateTimeWidget,
TextInput,
)
from .base import WidgetTest
class MyMultiWidget(MultiWidget):
def decompress(self, value):
if value:
return value.split("__")
return ["", ""]
class ComplexMultiWidget(MultiWidget):
def __init__(self, attrs=None):
widgets = (
TextInput(),
SelectMultiple(choices=WidgetTest.beatles),
SplitDateTimeWidget(),
)
super().__init__(widgets, attrs)
def decompress(self, value):
if value:
data = value.split(",")
return [
data[0],
list(data[1]),
datetime.strptime(data[2], "%Y-%m-%d %H:%M:%S"),
]
return [None, None, None]
class ComplexField(MultiValueField):
def __init__(self, required=True, widget=None, label=None, initial=None):
fields = (
CharField(),
MultipleChoiceField(choices=WidgetTest.beatles),
SplitDateTimeField(),
)
super().__init__(
fields, required=required, widget=widget, label=label, initial=initial
)
def compress(self, data_list):
if data_list:
return "%s,%s,%s" % (
data_list[0],
"".join(data_list[1]),
data_list[2],
)
return None
class DeepCopyWidget(MultiWidget):
"""
Used to test MultiWidget.__deepcopy__().
"""
def __init__(self, choices=[]):
widgets = [
RadioSelect(choices=choices),
TextInput,
]
super().__init__(widgets)
def _set_choices(self, choices):
"""
When choices are set for this widget, we want to pass those along to
the Select widget.
"""
self.widgets[0].choices = choices
def _get_choices(self):
"""
The choices for this widget are the Select widget's choices.
"""
return self.widgets[0].choices
choices = property(_get_choices, _set_choices)
class MultiWidgetTest(WidgetTest):
def test_subwidgets_name(self):
widget = MultiWidget(
widgets={
"": TextInput(),
"big": TextInput(attrs={"class": "big"}),
"small": TextInput(attrs={"class": "small"}),
},
)
self.check_html(
widget,
"name",
["John", "George", "Paul"],
html=(
'<input type="text" name="name" value="John">'
'<input type="text" name="name_big" value="George" class="big">'
'<input type="text" name="name_small" value="Paul" class="small">'
),
)
def test_text_inputs(self):
widget = MyMultiWidget(
widgets=(
TextInput(attrs={"class": "big"}),
TextInput(attrs={"class": "small"}),
)
)
self.check_html(
widget,
"name",
["john", "lennon"],
html=(
'<input type="text" class="big" value="john" name="name_0">'
'<input type="text" class="small" value="lennon" name="name_1">'
),
)
self.check_html(
widget,
"name",
("john", "lennon"),
html=(
'<input type="text" class="big" value="john" name="name_0">'
'<input type="text" class="small" value="lennon" name="name_1">'
),
)
self.check_html(
widget,
"name",
"john__lennon",
html=(
'<input type="text" class="big" value="john" name="name_0">'
'<input type="text" class="small" value="lennon" name="name_1">'
),
)
self.check_html(
widget,
"name",
"john__lennon",
attrs={"id": "foo"},
html=(
'<input id="foo_0" type="text" class="big" value="john" name="name_0">'
'<input id="foo_1" type="text" class="small" value="lennon" '
'name="name_1">'
),
)
def test_constructor_attrs(self):
widget = MyMultiWidget(
widgets=(
TextInput(attrs={"class": "big"}),
TextInput(attrs={"class": "small"}),
),
attrs={"id": "bar"},
)
self.check_html(
widget,
"name",
["john", "lennon"],
html=(
'<input id="bar_0" type="text" class="big" value="john" name="name_0">'
'<input id="bar_1" type="text" class="small" value="lennon" '
'name="name_1">'
),
)
def test_constructor_attrs_with_type(self):
attrs = {"type": "number"}
widget = MyMultiWidget(widgets=(TextInput, TextInput()), attrs=attrs)
self.check_html(
widget,
"code",
["1", "2"],
html=(
'<input type="number" value="1" name="code_0">'
'<input type="number" value="2" name="code_1">'
),
)
widget = MyMultiWidget(
widgets=(TextInput(attrs), TextInput(attrs)), attrs={"class": "bar"}
)
self.check_html(
widget,
"code",
["1", "2"],
html=(
'<input type="number" value="1" name="code_0" class="bar">'
'<input type="number" value="2" name="code_1" class="bar">'
),
)
def test_value_omitted_from_data(self):
widget = MyMultiWidget(widgets=(TextInput(), TextInput()))
self.assertIs(widget.value_omitted_from_data({}, {}, "field"), True)
self.assertIs(
widget.value_omitted_from_data({"field_0": "x"}, {}, "field"), False
)
self.assertIs(
widget.value_omitted_from_data({"field_1": "y"}, {}, "field"), False
)
self.assertIs(
widget.value_omitted_from_data(
{"field_0": "x", "field_1": "y"}, {}, "field"
),
False,
)
def test_value_from_datadict_subwidgets_name(self):
widget = MultiWidget(widgets={"x": TextInput(), "": TextInput()})
tests = [
({}, [None, None]),
({"field": "x"}, [None, "x"]),
({"field_x": "y"}, ["y", None]),
({"field": "x", "field_x": "y"}, ["y", "x"]),
]
for data, expected in tests:
with self.subTest(data):
self.assertEqual(
widget.value_from_datadict(data, {}, "field"),
expected,
)
def test_value_omitted_from_data_subwidgets_name(self):
widget = MultiWidget(widgets={"x": TextInput(), "": TextInput()})
tests = [
({}, True),
({"field": "x"}, False),
({"field_x": "y"}, False),
({"field": "x", "field_x": "y"}, False),
]
for data, expected in tests:
with self.subTest(data):
self.assertIs(
widget.value_omitted_from_data(data, {}, "field"),
expected,
)
def test_needs_multipart_true(self):
"""
needs_multipart_form should be True if any widgets need it.
"""
widget = MyMultiWidget(widgets=(TextInput(), FileInput()))
self.assertTrue(widget.needs_multipart_form)
def test_needs_multipart_false(self):
"""
needs_multipart_form should be False if no widgets need it.
"""
widget = MyMultiWidget(widgets=(TextInput(), TextInput()))
self.assertFalse(widget.needs_multipart_form)
def test_nested_multiwidget(self):
"""
MultiWidgets can be composed of other MultiWidgets.
"""
widget = ComplexMultiWidget()
self.check_html(
widget,
"name",
"some text,JP,2007-04-25 06:24:00",
html=(
"""
<input type="text" name="name_0" value="some text">
<select multiple name="name_1">
<option value="J" selected>John</option>
<option value="P" selected>Paul</option>
<option value="G">George</option>
<option value="R">Ringo</option>
</select>
<input type="text" name="name_2_0" value="2007-04-25">
<input type="text" name="name_2_1" value="06:24:00">
"""
),
)
def test_no_whitespace_between_widgets(self):
widget = MyMultiWidget(widgets=(TextInput, TextInput()))
self.check_html(
widget,
"code",
None,
html=('<input type="text" name="code_0"><input type="text" name="code_1">'),
strict=True,
)
def test_deepcopy(self):
"""
MultiWidget should define __deepcopy__() (#12048).
"""
w1 = DeepCopyWidget(choices=[1, 2, 3])
w2 = copy.deepcopy(w1)
w2.choices = [4, 5, 6]
# w2 ought to be independent of w1, since MultiWidget ought
# to make a copy of its sub-widgets when it is copied.
self.assertEqual(w1.choices, [1, 2, 3])
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = ComplexField(widget=ComplexMultiWidget)
form = TestForm()
self.assertIs(form["field"].field.widget.use_fieldset, True)
self.assertHTMLEqual(
"<div><fieldset><legend>Field:</legend>"
'<input type="text" name="field_0" required id="id_field_0">'
'<select name="field_1" required id="id_field_1" multiple>'
'<option value="J">John</option><option value="P">Paul</option>'
'<option value="G">George</option><option value="R">Ringo</option></select>'
'<input type="text" name="field_2_0" required id="id_field_2_0">'
'<input type="text" name="field_2_1" required id="id_field_2_1">'
"</fieldset></div>",
form.render(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_choicewidget.py | tests/forms_tests/widget_tests/test_choicewidget.py | import copy
from django.forms.widgets import ChoiceWidget
from .base import WidgetTest
class ChoiceWidgetTest(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_widget_dict_tuple = self.widget(
choices={
"outer1": "Outer 1",
'Group "1"': (("inner1", "Inner 1"), ("inner2", "Inner 2")),
},
)
return (nested_widget, nested_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, obj)
self.assertEqual(widget.choices, obj.choices)
self.assertIsNot(widget.choices, obj.choices)
self.assertEqual(widget.attrs, obj.attrs)
self.assertIsNot(widget.attrs, obj.attrs)
def test_options(self):
options = list(
self.widget(choices=self.beatles).options(
"name",
["J"],
attrs={"class": "super"},
)
)
self.assertEqual(len(options), 4)
self.assertEqual(options[0]["name"], "name")
self.assertEqual(options[0]["value"], "J")
self.assertEqual(options[0]["label"], "John")
self.assertEqual(options[0]["index"], "0")
self.assertIs(options[0]["selected"], True)
# Template-related attributes
self.assertEqual(options[1]["name"], "name")
self.assertEqual(options[1]["value"], "P")
self.assertEqual(options[1]["label"], "Paul")
self.assertEqual(options[1]["index"], "1")
self.assertIs(options[1]["selected"], False)
def test_optgroups_integer_choices(self):
"""The option 'value' is the same type as what's in `choices`."""
groups = list(
self.widget(choices=[[0, "choice text"]]).optgroups("name", ["vhs"])
)
label, options, index = groups[0]
self.assertEqual(options[0]["value"], 0)
def test_renders_required_when_possible_to_select_empty_field_none(self):
widget = self.widget(choices=[(None, "select please"), ("P", "Paul")])
self.assertIs(widget.use_required_attribute(initial=None), True)
def test_renders_required_when_possible_to_select_empty_field_list(self):
widget = self.widget(choices=[["", "select please"], ["P", "Paul"]])
self.assertIs(widget.use_required_attribute(initial=None), True)
def test_renders_required_when_possible_to_select_empty_field_str(self):
widget = self.widget(choices=[("", "select please"), ("P", "Paul")])
self.assertIs(widget.use_required_attribute(initial=None), True)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_selectdatewidget.py | tests/forms_tests/widget_tests/test_selectdatewidget.py | import sys
from datetime import date
from django.forms import DateField, Form, SelectDateWidget
from django.test import override_settings
from django.utils import translation
from django.utils.dates import MONTHS_AP
from django.utils.version import PYPY
from .base import WidgetTest
class SelectDateWidgetTest(WidgetTest):
maxDiff = None
widget = SelectDateWidget(
years=(
"2007",
"2008",
"2009",
"2010",
"2011",
"2012",
"2013",
"2014",
"2015",
"2016",
),
)
def test_render_empty(self):
self.check_html(
self.widget,
"mydate",
"",
html=(
"""
<select name="mydate_month" id="id_mydate_month">
<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 value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="mydate_day" id="id_mydate_day">
<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 value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select name="mydate_year" id="id_mydate_year">
<option selected value="">---</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
</select>
"""
),
)
def test_render_none(self):
"""
Rendering the None or '' values should yield the same output.
"""
self.assertHTMLEqual(
self.widget.render("mydate", None),
self.widget.render("mydate", ""),
)
def test_render_string(self):
self.check_html(
self.widget,
"mydate",
"2010-04-15",
html=(
"""
<select name="mydate_month" id="id_mydate_month">
<option value="">---</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4" selected>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 value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="mydate_day" id="id_mydate_day">
<option value="">---</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15" selected>15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select name="mydate_year" id="id_mydate_year">
<option value="">---</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010" selected>2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
</select>
"""
),
)
def test_render_datetime(self):
self.assertHTMLEqual(
self.widget.render("mydate", date(2010, 4, 15)),
self.widget.render("mydate", "2010-04-15"),
)
def test_render_invalid_date(self):
"""
Invalid dates should still render the failed date.
"""
self.check_html(
self.widget,
"mydate",
"2010-02-31",
html=(
"""
<select name="mydate_month" id="id_mydate_month">
<option value="">---</option>
<option value="1">January</option>
<option value="2" selected>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 value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="mydate_day" id="id_mydate_day">
<option value="">---</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31" selected>31</option>
</select>
<select name="mydate_year" id="id_mydate_year">
<option value="">---</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010" selected>2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
</select>
"""
),
)
def test_custom_months(self):
widget = SelectDateWidget(months=MONTHS_AP, years=("2013",))
self.check_html(
widget,
"mydate",
"",
html=(
"""
<select name="mydate_month" id="id_mydate_month">
<option selected value="">---</option>
<option value="1">Jan.</option>
<option value="2">Feb.</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">Aug.</option>
<option value="9">Sept.</option>
<option value="10">Oct.</option>
<option value="11">Nov.</option>
<option value="12">Dec.</option>
</select>
<select name="mydate_day" id="id_mydate_day">
<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 value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select name="mydate_year" id="id_mydate_year">
<option selected value="">---</option>
<option value="2013">2013</option>
</select>
"""
),
)
def test_selectdate_required(self):
class GetNotRequiredDate(Form):
mydate = DateField(widget=SelectDateWidget, required=False)
class GetRequiredDate(Form):
mydate = DateField(widget=SelectDateWidget, required=True)
self.assertFalse(GetNotRequiredDate().fields["mydate"].widget.is_required)
self.assertTrue(GetRequiredDate().fields["mydate"].widget.is_required)
def test_selectdate_empty_label(self):
w = SelectDateWidget(years=("2014",), empty_label="empty_label")
# Rendering the default state with empty_label set as string.
self.assertInHTML(
'<option selected value="">empty_label</option>',
w.render("mydate", ""),
count=3,
)
w = SelectDateWidget(
years=("2014",), empty_label=("empty_year", "empty_month", "empty_day")
)
# Rendering the default state with empty_label tuple.
self.assertHTMLEqual(
w.render("mydate", ""),
"""
<select name="mydate_month" id="id_mydate_month">
<option selected value="">empty_month</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 value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="mydate_day" id="id_mydate_day">
<option selected value="">empty_day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select name="mydate_year" id="id_mydate_year">
<option selected value="">empty_year</option>
<option value="2014">2014</option>
</select>
""",
)
with self.assertRaisesMessage(
ValueError, "empty_label list/tuple must have 3 elements."
):
SelectDateWidget(years=("2014",), empty_label=("not enough", "values"))
@translation.override("nl")
def test_l10n(self):
w = SelectDateWidget(
years=(
"2007",
"2008",
"2009",
"2010",
"2011",
"2012",
"2013",
"2014",
"2015",
"2016",
)
)
self.assertEqual(
w.value_from_datadict(
{"date_year": "2010", "date_month": "8", "date_day": "13"}, {}, "date"
),
"13-08-2010",
)
self.assertHTMLEqual(
w.render("date", "13-08-2010"),
"""
<select name="date_day" id="id_date_day">
<option value="">---</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13" selected>13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select name="date_month" id="id_date_month">
<option value="">---</option>
<option value="1">januari</option>
<option value="2">februari</option>
<option value="3">maart</option>
<option value="4">april</option>
<option value="5">mei</option>
<option value="6">juni</option>
<option value="7">juli</option>
<option value="8" selected>augustus</option>
<option value="9">september</option>
<option value="10">oktober</option>
<option value="11">november</option>
<option value="12">december</option>
</select>
<select name="date_year" id="id_date_year">
<option value="">---</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010" selected>2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
</select>
""",
)
# Even with an invalid date, the widget should reflect the entered
# value.
self.assertEqual(w.render("mydate", "2010-02-30").count("selected"), 3)
# Years before 1900 should work.
w = SelectDateWidget(years=("1899",))
self.assertEqual(
w.value_from_datadict(
{"date_year": "1899", "date_month": "8", "date_day": "13"}, {}, "date"
),
"13-08-1899",
)
# And years before 1000 (demonstrating the need for
# sanitize_strftime_format).
w = SelectDateWidget(years=("0001",))
self.assertEqual(
w.value_from_datadict(
{"date_year": "0001", "date_month": "8", "date_day": "13"}, {}, "date"
),
"13-08-0001",
)
@override_settings(DATE_INPUT_FORMATS=["%d.%m.%Y"])
def test_custom_input_format(self):
w = SelectDateWidget(years=("0001", "1899", "2009", "2010"))
with translation.override(None):
for values, expected_value in (
(("0001", "8", "13"), "13.08.0001"),
(("1899", "7", "11"), "11.07.1899"),
(("2009", "3", "7"), "07.03.2009"),
):
with self.subTest(values=values):
data = {
"field_%s" % field: value
for field, value in zip(("year", "month", "day"), values)
}
self.assertEqual(
w.value_from_datadict(data, {}, "field"), expected_value
)
expected_dict = {
field: int(value)
for field, value in zip(("year", "month", "day"), values)
}
self.assertEqual(w.format_value(expected_value), expected_dict)
def test_format_value(self):
valid_formats = [
"2000-1-1",
"2000-10-15",
"2000-01-01",
"2000-01-0",
"2000-0-01",
"2000-0-0",
"0-01-01",
"0-01-0",
"0-0-01",
"0-0-0",
]
for value in valid_formats:
year, month, day = (int(x) or "" for x in value.split("-"))
with self.subTest(value=value):
self.assertEqual(
self.widget.format_value(value),
{"day": day, "month": month, "year": year},
)
invalid_formats = [
"2000-01-001",
"2000-001-01",
"2-01-01",
"20-01-01",
"200-01-01",
"20000-01-01",
]
for value in invalid_formats:
with self.subTest(value=value):
self.assertEqual(
self.widget.format_value(value),
{"day": None, "month": None, "year": None},
)
def test_value_from_datadict(self):
tests = [
(("2000", "12", "1"), "2000-12-01"),
(("", "12", "1"), "0-12-1"),
(("2000", "", "1"), "2000-0-1"),
(("2000", "12", ""), "2000-12-0"),
(("", "", "", ""), None),
((None, "12", "1"), None),
(("2000", None, "1"), None),
(("2000", "12", None), None),
(
(str(sys.maxsize + 1), "12", "1"),
# PyPy does not raise OverflowError.
f"{sys.maxsize + 1}-12-1" if PYPY else "0-0-0",
),
]
for values, expected in tests:
with self.subTest(values=values):
data = {}
for field_name, value in zip(("year", "month", "day"), values):
if value is not None:
data["field_%s" % field_name] = value
self.assertEqual(
self.widget.value_from_datadict(data, {}, "field"), expected
)
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_month": "12"}, {}, "field"),
False,
)
self.assertIs(
self.widget.value_omitted_from_data({"field_year": "2000"}, {}, "field"),
False,
)
self.assertIs(
self.widget.value_omitted_from_data({"field_day": "1"}, {}, "field"), False
)
data = {"field_day": "1", "field_month": "12", "field_year": "2000"}
self.assertIs(self.widget.value_omitted_from_data(data, {}, "field"), False)
@override_settings(USE_THOUSAND_SEPARATOR=True)
def test_years_rendered_without_separator(self):
widget = SelectDateWidget(years=(2007,))
self.check_html(
widget,
"mydate",
"",
html=(
"""
<select name="mydate_month" id="id_mydate_month">
<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 value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="mydate_day" id="id_mydate_day">
<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 value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select name="mydate_year" id="id_mydate_year">
<option selected value="">---</option>
<option value="2007">2007</option>
</select>
"""
),
)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = DateField(widget=self.widget)
form = TestForm()
self.assertIs(self.widget.use_fieldset, True)
self.assertHTMLEqual(
"<div><fieldset><legend>Field:</legend>"
'<select name="field_month" required id="id_field_month">'
'<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 value="10">October</option>'
'<option value="11">November</option><option value="12">December</option>'
'</select><select name="field_day" required id="id_field_day">'
'<option value="1">1</option><option value="2">2</option>'
'<option value="3">3</option><option value="4">4</option>'
'<option value="5">5</option><option value="6">6</option>'
'<option value="7">7</option><option value="8">8</option>'
'<option value="9">9</option><option value="10">10</option>'
'<option value="11">11</option><option value="12">12</option>'
'<option value="13">13</option><option value="14">14</option>'
'<option value="15">15</option><option value="16">16</option>'
'<option value="17">17</option><option value="18">18</option>'
'<option value="19">19</option><option value="20">20</option>'
'<option value="21">21</option><option value="22">22</option>'
'<option value="23">23</option><option value="24">24</option>'
'<option value="25">25</option><option value="26">26</option>'
'<option value="27">27</option><option value="28">28</option>'
'<option value="29">29</option><option value="30">30</option>'
'<option value="31">31</option></select>'
'<select name="field_year" required id="id_field_year">'
'<option value="2007">2007</option><option value="2008">2008</option>'
'<option value="2009">2009</option><option value="2010">2010</option>'
'<option value="2011">2011</option><option value="2012">2012</option>'
'<option value="2013">2013</option><option value="2014">2014</option>'
'<option value="2015">2015</option><option value="2016">2016</option>'
"</select></fieldset></div>",
form.render(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_multiplehiddeninput.py | tests/forms_tests/widget_tests/test_multiplehiddeninput.py | from django.forms import Form, MultipleChoiceField, MultipleHiddenInput
from django.utils.datastructures import MultiValueDict
from .base import WidgetTest
class MultipleHiddenInputTest(WidgetTest):
widget = MultipleHiddenInput()
def test_render_single(self):
self.check_html(
self.widget,
"email",
["test@example.com"],
html='<input type="hidden" name="email" value="test@example.com">',
)
def test_render_multiple(self):
self.check_html(
self.widget,
"email",
["test@example.com", "foo@example.com"],
html=(
'<input type="hidden" name="email" value="test@example.com">\n'
'<input type="hidden" name="email" value="foo@example.com">'
),
)
def test_render_attrs(self):
self.check_html(
self.widget,
"email",
["test@example.com"],
attrs={"class": "fun"},
html=(
'<input type="hidden" name="email" value="test@example.com" '
'class="fun">'
),
)
def test_render_attrs_multiple(self):
self.check_html(
self.widget,
"email",
["test@example.com", "foo@example.com"],
attrs={"class": "fun"},
html=(
'<input type="hidden" name="email" value="test@example.com" '
'class="fun">\n'
'<input type="hidden" name="email" value="foo@example.com" class="fun">'
),
)
def test_render_attrs_constructor(self):
widget = MultipleHiddenInput(attrs={"class": "fun"})
self.check_html(widget, "email", [], "")
self.check_html(
widget,
"email",
["foo@example.com"],
html=(
'<input type="hidden" class="fun" value="foo@example.com" name="email">'
),
)
self.check_html(
widget,
"email",
["foo@example.com", "test@example.com"],
html=(
'<input type="hidden" class="fun" value="foo@example.com" '
'name="email">\n'
'<input type="hidden" class="fun" value="test@example.com" '
'name="email">'
),
)
self.check_html(
widget,
"email",
["foo@example.com"],
attrs={"class": "special"},
html=(
'<input type="hidden" class="special" value="foo@example.com" '
'name="email">'
),
)
def test_render_empty(self):
self.check_html(self.widget, "email", [], "")
def test_render_none(self):
self.check_html(self.widget, "email", None, "")
def test_render_increment_id(self):
"""
Each input should get a separate ID.
"""
self.check_html(
self.widget,
"letters",
["a", "b", "c"],
attrs={"id": "hideme"},
html=(
'<input type="hidden" name="letters" value="a" id="hideme_0">\n'
'<input type="hidden" name="letters" value="b" id="hideme_1">\n'
'<input type="hidden" name="letters" value="c" id="hideme_2">'
),
)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
composers = MultipleChoiceField(
choices=[("J", "John Lennon"), ("P", "Paul McCartney")],
widget=MultipleHiddenInput,
)
form = TestForm(MultiValueDict({"composers": ["J", "P"]}))
self.assertIs(self.widget.use_fieldset, False)
self.assertHTMLEqual(
'<input type="hidden" name="composers" value="J" id="id_composers_0">'
'<input type="hidden" name="composers" value="P" id="id_composers_1">',
form.render(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_splithiddendatetimewidget.py | tests/forms_tests/widget_tests/test_splithiddendatetimewidget.py | from datetime import datetime
from django.forms import Form, SplitDateTimeField, SplitHiddenDateTimeWidget
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="12:51:34">'
),
)
self.check_html(
self.widget,
"date",
datetime(2007, 9, 17, 12, 51, 34),
html=(
'<input type="hidden" name="date_0" value="2007-09-17">'
'<input type="hidden" name="date_1" value="12:51:34">'
),
)
self.check_html(
self.widget,
"date",
datetime(2007, 9, 17, 12, 51),
html=(
'<input type="hidden" name="date_0" value="2007-09-17">'
'<input type="hidden" name="date_1" value="12:51:00">'
),
)
@translation.override("de-at")
def test_l10n(self):
d = datetime(2007, 9, 17, 12, 51)
self.check_html(
self.widget,
"date",
d,
html=(
"""
<input type="hidden" name="date_0" value="17.09.2007">
<input type="hidden" name="date_1" value="12:51:00">
"""
),
)
def test_constructor_different_attrs(self):
html = (
'<input type="hidden" class="foo" value="2006-01-10" name="date_0">'
'<input type="hidden" class="bar" value="07:30:00" name="date_1">'
)
widget = SplitHiddenDateTimeWidget(
date_attrs={"class": "foo"}, time_attrs={"class": "bar"}
)
self.check_html(widget, "date", datetime(2006, 1, 10, 7, 30), html=html)
widget = SplitHiddenDateTimeWidget(
date_attrs={"class": "foo"}, attrs={"class": "bar"}
)
self.check_html(widget, "date", datetime(2006, 1, 10, 7, 30), html=html)
widget = SplitHiddenDateTimeWidget(
time_attrs={"class": "bar"}, attrs={"class": "foo"}
)
self.check_html(widget, "date", datetime(2006, 1, 10, 7, 30), html=html)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = SplitDateTimeField(widget=self.widget)
form = TestForm()
self.assertIs(self.widget.use_fieldset, True)
self.assertHTMLEqual(
'<input type="hidden" name="field_0" id="id_field_0">'
'<input type="hidden" name="field_1" id="id_field_1">',
form.render(),
)
def test_fieldset_with_unhidden_field(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
hidden_field = SplitDateTimeField(widget=self.widget)
unhidden_field = SplitDateTimeField()
form = TestForm()
self.assertIs(self.widget.use_fieldset, True)
self.assertHTMLEqual(
"<div><fieldset><legend>Unhidden field:</legend>"
'<input type="text" name="unhidden_field_0" required '
'id="id_unhidden_field_0"><input type="text" '
'name="unhidden_field_1" required id="id_unhidden_field_1">'
'</fieldset><input type="hidden" name="hidden_field_0" '
'id="id_hidden_field_0"><input type="hidden" '
'name="hidden_field_1" id="id_hidden_field_1"></div>',
form.render(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_telinput.py | tests/forms_tests/widget_tests/test_telinput.py | from django.forms import TelInput
from .base import WidgetTest
class TelInputTest(WidgetTest):
widget = TelInput()
def test_render(self):
self.check_html(
self.widget, "telephone", "", html='<input type="tel" name="telephone">'
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_select.py | tests/forms_tests/widget_tests/test_select.py | import datetime
from django.forms import ChoiceField, Form, MultiWidget, Select, TextInput
from django.test import override_settings
from django.utils.safestring import mark_safe
from .test_choicewidget import ChoiceWidgetTest
class SelectTest(ChoiceWidgetTest):
widget = Select
def test_render(self):
html = """
<select name="beatle">
<option value="J" selected>John</option>
<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(
self.widget(choices=self.beatles),
"beatle",
None,
html=(
"""<select name="beatle">
<option value="J">John</option>
<option value="P">Paul</option>
<option value="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 options are selected.
"""
self.check_html(
self.widget(choices=self.beatles),
"beatle",
"John",
html=(
"""<select name="beatle">
<option value="J">John</option>
<option value="P">Paul</option>
<option value="G">George</option>
<option value="R">Ringo</option>
</select>"""
),
)
def test_render_selected(self):
"""
Only one option can be selected (#8103).
"""
choices = [("0", "0"), ("1", "1"), ("2", "2"), ("3", "3"), ("0", "extra")]
self.check_html(
self.widget(choices=choices),
"choices",
"0",
html=(
"""<select name="choices">
<option value="0" selected>0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="0">extra</option>
</select>"""
),
)
def test_constructor_attrs(self):
"""
Select options shouldn't inherit the parent widget attrs.
"""
widget = Select(
attrs={"class": "super", "id": "super"},
choices=[(1, 1), (2, 2), (3, 3)],
)
self.check_html(
widget,
"num",
2,
html=(
"""<select name="num" class="super" id="super">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
</select>"""
),
)
def test_compare_to_str(self):
"""
The value is compared to its str().
"""
self.check_html(
self.widget(choices=[("1", "1"), ("2", "2"), ("3", "3")]),
"num",
2,
html=(
"""<select name="num">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
</select>"""
),
)
self.check_html(
self.widget(choices=[(1, 1), (2, 2), (3, 3)]),
"num",
"2",
html=(
"""<select name="num">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
</select>"""
),
)
self.check_html(
self.widget(choices=[(1, 1), (2, 2), (3, 3)]),
"num",
2,
html=(
"""<select name="num">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
</select>"""
),
)
def test_choices_constructor(self):
widget = Select(choices=[(1, 1), (2, 2), (3, 3)])
self.check_html(
widget,
"num",
2,
html=(
"""<select name="num">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
</select>"""
),
)
def test_choices_constructor_generator(self):
"""
If choices is passed to the constructor and is a generator, it can be
iterated over multiple times without getting consumed.
"""
def get_choices():
for i in range(5):
yield (i, i)
widget = Select(choices=get_choices())
self.check_html(
widget,
"num",
2,
html=(
"""<select name="num">
<option value="0">0</option>
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>"""
),
)
self.check_html(
widget,
"num",
3,
html=(
"""<select name="num">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected>3</option>
<option value="4">4</option>
</select>"""
),
)
def test_choices_escaping(self):
choices = (("bad", "you & me"), ("good", mark_safe("you > me")))
self.check_html(
self.widget(choices=choices),
"escape",
None,
html=(
"""<select name="escape">
<option value="bad">you & me</option>
<option value="good">you > me</option>
</select>"""
),
)
def test_choices_unicode(self):
self.check_html(
self.widget(choices=[("ŠĐĆŽćžšđ", "ŠĐabcĆŽćžšđ"), ("ćžšđ", "abcćžšđ")]),
"email",
"ŠĐĆŽćžšđ",
html=(
"""
<select name="email">
<option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111"
selected>
\u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111
</option>
<option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111
</option>
</select>
"""
),
)
def test_choices_optgroup(self):
"""
Choices can be nested one level in order to create HTML optgroups.
"""
html = """
<select name="nestchoice">
<option value="outer1">Outer 1</option>
<optgroup label="Group "1"">
<option value="inner1">Inner 1</option>
<option value="inner2">Inner 2</option>
</optgroup>
</select>
"""
for widget in self.nested_widgets:
with self.subTest(widget):
self.check_html(widget, "nestchoice", None, html=html)
def test_choices_select_outer(self):
html = """
<select name="nestchoice">
<option value="outer1" selected>Outer 1</option>
<optgroup label="Group "1"">
<option value="inner1">Inner 1</option>
<option value="inner2">Inner 2</option>
</optgroup>
</select>
"""
for widget in self.nested_widgets:
with self.subTest(widget):
self.check_html(widget, "nestchoice", "outer1", html=html)
def test_choices_select_inner(self):
html = """
<select name="nestchoice">
<option value="outer1">Outer 1</option>
<optgroup label="Group "1"">
<option value="inner1" selected>Inner 1</option>
<option value="inner2">Inner 2</option>
</optgroup>
</select>
"""
for widget in self.nested_widgets:
with self.subTest(widget):
self.check_html(widget, "nestchoice", "inner1", html=html)
@override_settings(USE_THOUSAND_SEPARATOR=True)
def test_doesnt_localize_option_value(self):
choices = [
(1, "One"),
(1000, "One thousand"),
(1000000, "One million"),
]
html = """
<select name="number">
<option value="1">One</option>
<option value="1000">One thousand</option>
<option value="1000000">One million</option>
</select>
"""
self.check_html(self.widget(choices=choices), "number", None, html=html)
choices = [
(datetime.time(0, 0), "midnight"),
(datetime.time(12, 0), "noon"),
]
html = """
<select name="time">
<option value="00:00:00">midnight</option>
<option value="12:00:00">noon</option>
</select>
"""
self.check_html(self.widget(choices=choices), "time", None, html=html)
def _test_optgroups(self, choices):
groups = list(
self.widget(choices=choices).optgroups(
"name",
["vhs"],
attrs={"class": "super"},
)
)
audio, video, unknown = groups
label, options, index = audio
self.assertEqual(label, "Audio")
self.assertEqual(
options,
[
{
"value": "vinyl",
"type": "select",
"attrs": {},
"index": "0_0",
"label": "Vinyl",
"template_name": "django/forms/widgets/select_option.html",
"name": "name",
"selected": False,
"wrap_label": True,
},
{
"value": "cd",
"type": "select",
"attrs": {},
"index": "0_1",
"label": "CD",
"template_name": "django/forms/widgets/select_option.html",
"name": "name",
"selected": False,
"wrap_label": True,
},
],
)
self.assertEqual(index, 0)
label, options, index = video
self.assertEqual(label, "Video")
self.assertEqual(
options,
[
{
"value": "vhs",
"template_name": "django/forms/widgets/select_option.html",
"label": "VHS Tape",
"attrs": {"selected": True},
"index": "1_0",
"name": "name",
"selected": True,
"type": "select",
"wrap_label": True,
},
{
"value": "dvd",
"template_name": "django/forms/widgets/select_option.html",
"label": "DVD",
"attrs": {},
"index": "1_1",
"name": "name",
"selected": False,
"type": "select",
"wrap_label": True,
},
],
)
self.assertEqual(index, 1)
label, options, index = unknown
self.assertIsNone(label)
self.assertEqual(
options,
[
{
"value": "unknown",
"selected": False,
"template_name": "django/forms/widgets/select_option.html",
"label": "Unknown",
"attrs": {},
"index": "2",
"name": "name",
"type": "select",
"wrap_label": True,
}
],
)
self.assertEqual(index, 2)
def test_optgroups(self):
choices_dict = {
"Audio": [
("vinyl", "Vinyl"),
("cd", "CD"),
],
"Video": [
("vhs", "VHS Tape"),
("dvd", "DVD"),
],
"unknown": "Unknown",
}
choices_list = list(choices_dict.items())
choices_nested_dict = {
k: dict(v) if isinstance(v, list) else v for k, v in choices_dict.items()
}
for choices in (choices_dict, choices_list, choices_nested_dict):
with self.subTest(choices):
self._test_optgroups(choices)
def test_doesnt_render_required_when_impossible_to_select_empty_field(self):
widget = self.widget(choices=[("J", "John"), ("P", "Paul")])
self.assertIs(widget.use_required_attribute(initial=None), False)
def test_doesnt_render_required_when_no_choices_are_available(self):
widget = self.widget(choices=[])
self.assertIs(widget.use_required_attribute(initial=None), False)
def test_render_as_subwidget(self):
"""A RadioSelect as a subwidget of MultiWidget."""
choices = (("", "------"),) + self.beatles
self.check_html(
MultiWidget([self.widget(choices=choices), TextInput()]),
"beatle",
["J", "Some text"],
html=(
"""
<select name="beatle_0">
<option value="">------</option>
<option value="J" selected>John</option>
<option value="P">Paul</option>
<option value="G">George</option>
<option value="R">Ringo</option>
</select>
<input name="beatle_1" type="text" value="Some text">
"""
),
)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = ChoiceField(widget=self.widget, choices=self.beatles)
form = TestForm()
self.assertIs(self.widget.use_fieldset, False)
self.assertHTMLEqual(
'<div><label for="id_field">Field:</label>'
'<select name="field" id="id_field">'
'<option value="J">John</option> '
'<option value="P">Paul</option>'
'<option value="G">George</option>'
'<option value="R">Ringo</option></select></div>',
form.render(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_fileinput.py | tests/forms_tests/widget_tests/test_fileinput.py | from django.core.files.uploadedfile import SimpleUploadedFile
from django.forms import FileField, FileInput, 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">',
)
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">'
)
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 test_use_required_attribute(self):
# False when initial data exists. The file input is left blank by the
# user to keep the existing, initial value.
self.assertIs(self.widget.use_required_attribute(None), True)
self.assertIs(self.widget.use_required_attribute("resume.txt"), False)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = FileField(widget=self.widget)
form = TestForm()
self.assertIs(self.widget.use_fieldset, False)
self.assertHTMLEqual(
'<div><label for="id_field">Field:</label><input id="id_field" '
'name="field" required type="file"></div>',
form.render(),
)
def test_multiple_error(self):
msg = "FileInput doesn't support uploading multiple files."
with self.assertRaisesMessage(ValueError, msg):
FileInput(attrs={"multiple": True})
def test_value_from_datadict_multiple(self):
class MultipleFileInput(FileInput):
allow_multiple_selected = True
file_1 = SimpleUploadedFile("something1.txt", b"content 1")
file_2 = SimpleUploadedFile("something2.txt", b"content 2")
# Uploading multiple files is allowed.
widget = MultipleFileInput(attrs={"multiple": True})
value = widget.value_from_datadict(
data={"name": "Test name"},
files=MultiValueDict({"myfile": [file_1, file_2]}),
name="myfile",
)
self.assertEqual(value, [file_1, file_2])
# Uploading multiple files is not allowed.
widget = FileInput()
value = widget.value_from_datadict(
data={"name": "Test name"},
files=MultiValueDict({"myfile": [file_1, file_2]}),
name="myfile",
)
self.assertEqual(value, file_2)
def test_multiple_default(self):
class MultipleFileInput(FileInput):
allow_multiple_selected = True
tests = [
(None, True),
({"class": "myclass"}, True),
({"multiple": False}, False),
]
for attrs, expected in tests:
with self.subTest(attrs=attrs):
widget = MultipleFileInput(attrs=attrs)
self.assertIs(widget.attrs["multiple"], expected)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_textarea.py | tests/forms_tests/widget_tests/test_textarea.py | from django.forms import CharField, Form, Textarea
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",
"value",
html='<textarea rows="10" cols="40" name="msg">value</textarea>',
)
def test_render_empty(self):
self.check_html(
self.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"></textarea>',
)
def test_escaping(self):
self.check_html(
self.widget,
"msg",
'some "quoted" & ampersanded value',
html=(
'<textarea rows="10" cols="40" name="msg">'
"some "quoted" & ampersanded value</textarea>"
),
)
def test_mark_safe(self):
self.check_html(
self.widget,
"msg",
mark_safe("pre "quoted" value"),
html=(
'<textarea rows="10" cols="40" name="msg">pre "quoted" value'
"</textarea>"
),
)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = CharField(widget=self.widget)
form = TestForm()
self.assertIs(self.widget.use_fieldset, False)
self.assertHTMLEqual(
'<div><label for="id_field">Field:</label>'
'<textarea cols="40" id="id_field" name="field" '
'required rows="10"></textarea></div>',
form.render(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_hiddeninput.py | tests/forms_tests/widget_tests/test_hiddeninput.py | from django.forms import CharField, Form, HiddenInput
from .base import WidgetTest
class HiddenInputTest(WidgetTest):
widget = HiddenInput()
def test_render(self):
self.check_html(
self.widget, "email", "", html='<input type="hidden" name="email">'
)
def test_use_required_attribute(self):
# Always False to avoid browser validation on inputs hidden from the
# user.
self.assertIs(self.widget.use_required_attribute(None), False)
self.assertIs(self.widget.use_required_attribute(""), False)
self.assertIs(self.widget.use_required_attribute("foo"), False)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = CharField(widget=self.widget)
form = TestForm()
self.assertIs(self.widget.use_fieldset, False)
self.assertHTMLEqual(
'<input type="hidden" name="field" id="id_field">',
form.render(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_dateinput.py | tests/forms_tests/widget_tests/test_dateinput.py | from datetime import date
from django.forms import 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,
html='<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-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 type="text" name="date" value="2007-09-17">'),
)
def test_format(self):
"""
Use 'format' to change the way a value is displayed.
"""
d = date(2007, 9, 17)
widget = DateInput(format="%d/%m/%Y", attrs={"type": "date"})
self.check_html(
widget, "date", d, html='<input type="date" name="date" value="17/09/2007">'
)
@translation.override("de-at")
def test_l10n(self):
self.check_html(
self.widget,
"date",
date(2007, 9, 17),
html='<input type="text" name="date" value="17.09.2007">',
)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = CharField(widget=self.widget)
form = TestForm()
self.assertIs(self.widget.use_fieldset, False)
self.assertHTMLEqual(
form.render(),
'<div><label for="id_field">Field:</label>'
'<input id="id_field" name="field" required type="text"></div>',
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py | tests/forms_tests/widget_tests/test_checkboxselectmultiple.py | import datetime
from django import forms
from django.forms import CheckboxSelectMultiple, ChoiceField, Form
from django.test import override_settings
from .base import WidgetTest
class CheckboxSelectMultipleTest(WidgetTest):
widget = CheckboxSelectMultiple
def test_render_value(self):
self.check_html(
self.widget(choices=self.beatles),
"beatles",
["J"],
html="""
<div>
<div><label><input checked type="checkbox" name="beatles" value="J"> John
</label></div>
<div><label><input type="checkbox" name="beatles" value="P"> Paul
</label></div>
<div><label><input type="checkbox" name="beatles" value="G"> George
</label></div>
<div><label><input type="checkbox" name="beatles" value="R"> Ringo
</label></div>
</div>
""",
)
def test_render_value_multiple(self):
self.check_html(
self.widget(choices=self.beatles),
"beatles",
["J", "P"],
html="""
<div>
<div><label><input checked type="checkbox" name="beatles" value="J"> John
</label></div>
<div><label><input checked type="checkbox" name="beatles" value="P"> Paul
</label></div>
<div><label><input type="checkbox" name="beatles" value="G"> George
</label></div>
<div><label><input type="checkbox" name="beatles" value="R"> Ringo
</label></div>
</div>
""",
)
def test_render_none(self):
"""
If the value is None, none of the options are selected, even if the
choices have an empty option.
"""
self.check_html(
self.widget(choices=(("", "Unknown"),) + self.beatles),
"beatles",
None,
html="""
<div>
<div><label><input type="checkbox" name="beatles" value=""> Unknown
</label></div>
<div><label><input type="checkbox" name="beatles" value="J"> John
</label></div>
<div><label><input type="checkbox" name="beatles" value="P"> Paul
</label></div>
<div><label><input type="checkbox" name="beatles" value="G"> George
</label></div>
<div><label><input type="checkbox" name="beatles" value="R"> Ringo
</label></div>
</div>
""",
)
def test_nested_choices(self):
nested_choices = (
("unknown", "Unknown"),
("Audio", (("vinyl", "Vinyl"), ("cd", "CD"))),
("Video", (("vhs", "VHS"), ("dvd", "DVD"))),
)
html = """
<div id="media">
<div> <label for="media_0">
<input type="checkbox" name="nestchoice" value="unknown" id="media_0"> Unknown
</label></div>
<div>
<label>Audio</label>
<div> <label for="media_1_0">
<input checked type="checkbox" name="nestchoice" value="vinyl" id="media_1_0">
Vinyl</label></div>
<div> <label for="media_1_1">
<input type="checkbox" name="nestchoice" value="cd" id="media_1_1"> CD
</label></div>
</div><div>
<label>Video</label>
<div> <label for="media_2_0">
<input type="checkbox" name="nestchoice" value="vhs" id="media_2_0"> VHS
</label></div>
<div> <label for="media_2_1">
<input type="checkbox" name="nestchoice" value="dvd" id="media_2_1" checked> DVD
</label></div>
</div>
</div>
"""
self.check_html(
self.widget(choices=nested_choices),
"nestchoice",
("vinyl", "dvd"),
attrs={"id": "media"},
html=html,
)
def test_nested_choices_without_id(self):
nested_choices = (
("unknown", "Unknown"),
("Audio", (("vinyl", "Vinyl"), ("cd", "CD"))),
("Video", (("vhs", "VHS"), ("dvd", "DVD"))),
)
html = """
<div>
<div> <label>
<input type="checkbox" name="nestchoice" value="unknown"> Unknown</label></div>
<div>
<label>Audio</label>
<div> <label>
<input checked type="checkbox" name="nestchoice" value="vinyl"> Vinyl
</label></div>
<div> <label>
<input type="checkbox" name="nestchoice" value="cd"> CD</label></div>
</div><div>
<label>Video</label>
<div> <label>
<input type="checkbox" name="nestchoice" value="vhs"> VHS</label></div>
<div> <label>
<input type="checkbox" name="nestchoice" value="dvd"checked> DVD</label></div>
</div>
</div>
"""
self.check_html(
self.widget(choices=nested_choices),
"nestchoice",
("vinyl", "dvd"),
html=html,
)
def test_separate_ids(self):
"""
Each input gets a separate ID.
"""
choices = [("a", "A"), ("b", "B"), ("c", "C")]
html = """
<div id="abc">
<div>
<label for="abc_0">
<input checked type="checkbox" name="letters" value="a" id="abc_0"> A</label>
</div>
<div><label for="abc_1">
<input type="checkbox" name="letters" value="b" id="abc_1"> B</label></div>
<div>
<label for="abc_2">
<input checked type="checkbox" name="letters" value="c" id="abc_2"> C</label>
</div>
</div>
"""
self.check_html(
self.widget(choices=choices),
"letters",
["a", "c"],
attrs={"id": "abc"},
html=html,
)
def test_separate_ids_constructor(self):
"""
Each input gets a separate ID when the ID is passed to the constructor.
"""
widget = CheckboxSelectMultiple(
attrs={"id": "abc"}, choices=[("a", "A"), ("b", "B"), ("c", "C")]
)
html = """
<div id="abc">
<div>
<label for="abc_0">
<input checked type="checkbox" name="letters" value="a" id="abc_0"> A</label>
</div>
<div><label for="abc_1">
<input type="checkbox" name="letters" value="b" id="abc_1"> B</label></div>
<div>
<label for="abc_2">
<input checked type="checkbox" name="letters" value="c" id="abc_2"> C</label>
</div>
</div>
"""
self.check_html(widget, "letters", ["a", "c"], html=html)
@override_settings(USE_THOUSAND_SEPARATOR=True)
def test_doesnt_localize_input_value(self):
choices = [
(1, "One"),
(1000, "One thousand"),
(1000000, "One million"),
]
html = """
<div>
<div><label><input type="checkbox" name="numbers" value="1"> One</label></div>
<div><label>
<input type="checkbox" name="numbers" value="1000"> One thousand</label></div>
<div><label>
<input type="checkbox" name="numbers" value="1000000"> One million</label></div>
</div>
"""
self.check_html(self.widget(choices=choices), "numbers", None, html=html)
choices = [
(datetime.time(0, 0), "midnight"),
(datetime.time(12, 0), "noon"),
]
html = """
<div>
<div><label>
<input type="checkbox" name="times" value="00:00:00"> midnight</label></div>
<div><label>
<input type="checkbox" name="times" value="12:00:00"> noon</label></div>
</div>
"""
self.check_html(self.widget(choices=choices), "times", None, html=html)
def test_use_required_attribute(self):
widget = self.widget(choices=self.beatles)
# Always False because browser validation would require all checkboxes
# to be checked instead of at least one.
self.assertIs(widget.use_required_attribute(None), False)
self.assertIs(widget.use_required_attribute([]), False)
self.assertIs(widget.use_required_attribute(["J", "P"]), False)
def test_value_omitted_from_data(self):
widget = self.widget(choices=self.beatles)
self.assertIs(widget.value_omitted_from_data({}, {}, "field"), False)
self.assertIs(
widget.value_omitted_from_data({"field": "value"}, {}, "field"), False
)
def test_label(self):
"""
CheckboxSelectMultiple doesn't contain 'for="field_0"' in the <label>
because clicking that would toggle the first checkbox.
"""
class TestForm(forms.Form):
f = forms.MultipleChoiceField(widget=CheckboxSelectMultiple)
bound_field = TestForm()["f"]
self.assertEqual(bound_field.field.widget.id_for_label("id"), "")
self.assertEqual(bound_field.label_tag(), "<label>F:</label>")
self.assertEqual(bound_field.legend_tag(), "<legend>F:</legend>")
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = ChoiceField(widget=self.widget, choices=self.beatles)
form = TestForm()
self.assertIs(self.widget.use_fieldset, True)
self.assertHTMLEqual(
form.render(),
'<div><fieldset><legend>Field:</legend><div id="id_field">'
'<div><label for="id_field_0"><input type="checkbox" '
'name="field" value="J" id="id_field_0"> John</label></div>'
'<div><label for="id_field_1"><input type="checkbox" '
'name="field" value="P" id="id_field_1">Paul</label></div>'
'<div><label for="id_field_2"><input type="checkbox" '
'name="field" value="G" id="id_field_2"> George</label></div>'
'<div><label for="id_field_3"><input type="checkbox" '
'name="field" value="R" id="id_field_3">'
"Ringo</label></div></div></fieldset></div>",
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/__init__.py | tests/forms_tests/widget_tests/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_colorinput.py | tests/forms_tests/widget_tests/test_colorinput.py | from django.forms import ColorInput
from .base import WidgetTest
class ColorInputTest(WidgetTest):
widget = ColorInput()
def test_render(self):
self.check_html(
self.widget,
"color",
"",
html="<input type='color' name='color'>",
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_timeinput.py | tests/forms_tests/widget_tests/test_timeinput.py | from datetime import time
from django.forms import 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")
self.check_html(
self.widget,
"time",
t,
html='<input type="text" name="time" value="12:51:34">',
)
self.check_html(
self.widget,
"time",
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="time" value="12:51:00">'),
)
def test_string(self):
"""Initializing from a string value."""
self.check_html(
self.widget,
"time",
"13:12:11",
html=('<input type="text" name="time" value="13:12:11">'),
)
def test_format(self):
"""
Use 'format' to change the way a value is displayed.
"""
t = time(12, 51, 34, 482548)
widget = TimeInput(format="%H:%M", attrs={"type": "time"})
self.check_html(
widget, "time", t, html='<input type="time" name="time" value="12:51">'
)
@translation.override("de-at")
def test_l10n(self):
t = time(12, 51, 34, 482548)
self.check_html(
self.widget,
"time",
t,
html='<input type="text" name="time" value="12:51:34">',
)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = CharField(widget=self.widget)
form = TestForm()
self.assertIs(self.widget.use_fieldset, False)
self.assertHTMLEqual(
'<div><label for="id_field">Field:</label>'
'<input id="id_field" name="field" required type="text"></div>',
form.render(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_widget.py | tests/forms_tests/widget_tests/test_widget.py | from 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.assertIs(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):
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="None" name="name" value="value">'
self.check_html(Input(), "name", "value", html=html, attrs={"readonly": False})
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_datetimeinput.py | tests/forms_tests/widget_tests/test_datetimeinput.py | from datetime import datetime
from django.forms import 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:51: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(
self.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",
datetime(2007, 9, 17, 12, 51),
html=('<input type="text" name="date" value="2007-09-17 12:51:00">'),
)
def test_render_formatted(self):
"""
Use 'format' to change the way a value is displayed.
"""
widget = DateTimeInput(
format="%d/%m/%Y %H:%M",
attrs={"type": "datetime"},
)
d = datetime(2007, 9, 17, 12, 51, 34, 482548)
self.check_html(
widget,
"date",
d,
html='<input type="datetime" name="date" value="17/09/2007 12:51">',
)
@translation.override("de-at")
def test_l10n(self):
d = datetime(2007, 9, 17, 12, 51, 34, 482548)
self.check_html(
self.widget,
"date",
d,
html=('<input type="text" name="date" value="17.09.2007 12:51:34">'),
)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = CharField(widget=self.widget)
form = TestForm()
self.assertIs(self.widget.use_fieldset, False)
self.assertHTMLEqual(
'<div><label for="id_field">Field:</label>'
'<input id="id_field" name="field" required type="text"></div>',
form.render(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_radioselect.py | tests/forms_tests/widget_tests/test_radioselect.py | import datetime
from django.forms import ChoiceField, Form, MultiWidget, RadioSelect, TextInput
from django.test import override_settings
from django.utils.safestring import mark_safe
from .test_choicewidget import ChoiceWidgetTest
BLANK_CHOICE_DASH = (("", "------"),)
class RadioSelectTest(ChoiceWidgetTest):
widget = RadioSelect
def test_render(self):
html = """
<div>
<div>
<label><input type="radio" name="beatle" value="">------</label>
</div>
<div>
<label><input checked type="radio" name="beatle" value="J">John</label>
</div>
<div>
<label><input type="radio" name="beatle" value="P">Paul</label>
</div>
<div>
<label><input type="radio" name="beatle" value="G">George</label>
</div>
<div>
<label><input type="radio" name="beatle" value="R">Ringo</label>
</div>
</div>
"""
beatles_with_blank = BLANK_CHOICE_DASH + self.beatles
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_choices = (
("unknown", "Unknown"),
("Audio", (("vinyl", "Vinyl"), ("cd", "CD"))),
("Video", (("vhs", "VHS"), ("dvd", "DVD"))),
)
html = """
<div id="media">
<div>
<label for="media_0">
<input type="radio" name="nestchoice" value="unknown" id="media_0"> Unknown
</label></div>
<div>
<label>Audio</label>
<div>
<label for="media_1_0">
<input type="radio" name="nestchoice" value="vinyl" id="media_1_0"> Vinyl
</label></div>
<div> <label for="media_1_1">
<input type="radio" name="nestchoice" value="cd" id="media_1_1"> CD
</label></div>
</div><div>
<label>Video</label>
<div>
<label for="media_2_0">
<input type="radio" name="nestchoice" value="vhs" id="media_2_0"> VHS
</label></div>
<div>
<label for="media_2_1">
<input type="radio" name="nestchoice" value="dvd" id="media_2_1" checked> DVD
</label></div>
</div>
</div>
"""
self.check_html(
self.widget(choices=nested_choices),
"nestchoice",
"dvd",
attrs={"id": "media"},
html=html,
)
def test_render_none(self):
"""
If value is None, none of the options are selected.
"""
choices = BLANK_CHOICE_DASH + self.beatles
html = """
<div>
<div>
<label><input checked type="radio" name="beatle" value="">------</label>
</div>
<div>
<label><input type="radio" name="beatle" value="J">John</label>
</div>
<div>
<label><input type="radio" name="beatle" value="P">Paul</label>
</div>
<div>
<label><input type="radio" name="beatle" value="G">George</label>
</div>
<div>
<label><input type="radio" name="beatle" value="R">Ringo</label>
</div>
</div>
"""
self.check_html(self.widget(choices=choices), "beatle", None, html=html)
def test_render_label_value(self):
"""
If the value corresponds to a label (but not to an option value), none
of the options are selected.
"""
html = """
<div>
<div>
<label><input type="radio" name="beatle" value="J">John</label>
</div>
<div>
<label><input type="radio" name="beatle" value="P">Paul</label>
</div>
<div>
<label><input type="radio" name="beatle" value="G">George</label>
</div>
<div>
<label><input type="radio" name="beatle" value="R">Ringo</label>
</div>
</div>
"""
self.check_html(self.widget(choices=self.beatles), "beatle", "Ringo", html=html)
def test_render_selected(self):
"""
Only one option can be selected.
"""
choices = [("0", "0"), ("1", "1"), ("2", "2"), ("3", "3"), ("0", "extra")]
html = """
<div>
<div>
<label><input checked type="radio" name="choices" value="0">0</label>
</div>
<div>
<label><input type="radio" name="choices" value="1">1</label>
</div>
<div>
<label><input type="radio" name="choices" value="2">2</label>
</div>
<div>
<label><input type="radio" name="choices" value="3">3</label>
</div>
<div>
<label><input type="radio" name="choices" value="0">extra</label>
</div>
</div>
"""
self.check_html(self.widget(choices=choices), "choices", "0", html=html)
def test_constructor_attrs(self):
"""
Attributes provided at instantiation are passed to the constituent
inputs.
"""
widget = self.widget(attrs={"id": "foo"}, choices=self.beatles)
html = """
<div id="foo">
<div>
<label for="foo_0">
<input checked type="radio" id="foo_0" value="J" name="beatle">John</label>
</div>
<div><label for="foo_1">
<input type="radio" id="foo_1" value="P" name="beatle">Paul</label>
</div>
<div><label for="foo_2">
<input type="radio" id="foo_2" value="G" name="beatle">George</label>
</div>
<div><label for="foo_3">
<input type="radio" id="foo_3" value="R" name="beatle">Ringo</label>
</div>
</div>
"""
self.check_html(widget, "beatle", "J", html=html)
def test_compare_to_str(self):
"""
The value is compared to its str().
"""
html = """
<div>
<div>
<label><input type="radio" name="num" value="1">1</label>
</div>
<div>
<label><input type="radio" name="num" value="2">2</label>
</div>
<div>
<label><input checked type="radio" name="num" value="3">3</label>
</div>
</div>
"""
self.check_html(
self.widget(choices=[("1", "1"), ("2", "2"), ("3", "3")]),
"num",
3,
html=html,
)
self.check_html(
self.widget(choices=[(1, 1), (2, 2), (3, 3)]), "num", "3", html=html
)
self.check_html(
self.widget(choices=[(1, 1), (2, 2), (3, 3)]), "num", 3, html=html
)
def test_choices_constructor(self):
widget = self.widget(choices=[(1, 1), (2, 2), (3, 3)])
html = """
<div>
<div>
<label><input type="radio" name="num" value="1">1</label>
</div>
<div>
<label><input type="radio" name="num" value="2">2</label>
</div>
<div>
<label><input checked type="radio" name="num" value="3">3</label>
</div>
</div>
"""
self.check_html(widget, "num", 3, html=html)
def test_choices_constructor_generator(self):
"""
If choices is passed to the constructor and is a generator, it can be
iterated over multiple times without getting consumed.
"""
def get_choices():
for i in range(4):
yield (i, i)
html = """
<div>
<div>
<label><input type="radio" name="num" value="0">0</label>
</div>
<div>
<label><input type="radio" name="num" value="1">1</label>
</div>
<div>
<label><input type="radio" name="num" value="2">2</label>
</div>
<div>
<label><input checked type="radio" name="num" value="3">3</label>
</div>
</div>
"""
widget = self.widget(choices=get_choices())
self.check_html(widget, "num", 3, html=html)
def test_choices_escaping(self):
choices = (("bad", "you & me"), ("good", mark_safe("you > me")))
html = """
<div>
<div>
<label><input type="radio" name="escape" value="bad">you & me</label>
</div>
<div>
<label><input type="radio" name="escape" value="good">you > me</label>
</div>
</div>
"""
self.check_html(self.widget(choices=choices), "escape", None, html=html)
def test_choices_unicode(self):
html = """
<div>
<div>
<label>
<input checked type="radio" name="email"
value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111">
\u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</label>
</div>
<div>
<label>
<input type="radio" name="email" value="\u0107\u017e\u0161\u0111">
abc\u0107\u017e\u0161\u0111</label>
</div>
</div>
"""
self.check_html(
self.widget(choices=[("ŠĐĆŽćžšđ", "ŠĐabcĆŽćžšđ"), ("ćžšđ", "abcćžšđ")]),
"email",
"ŠĐĆŽćžšđ",
html=html,
)
def test_choices_optgroup(self):
"""
Choices can be nested one level in order to create HTML optgroups.
"""
html = """
<div>
<div>
<label><input type="radio" name="nestchoice" value="outer1">Outer 1</label>
</div>
<div>
<label>Group "1"</label>
<div>
<label>
<input type="radio" name="nestchoice" value="inner1">Inner 1</label>
</div>
<div>
<label>
<input type="radio" name="nestchoice" value="inner2">Inner 2</label>
</div>
</div>
</div>
"""
for widget in self.nested_widgets:
with self.subTest(widget):
self.check_html(widget, "nestchoice", None, html=html)
def test_choices_select_outer(self):
html = """
<div>
<div>
<label>
<input checked type="radio" name="nestchoice" value="outer1">Outer 1</label>
</div>
<div>
<label>Group "1"</label>
<div>
<label>
<input type="radio" name="nestchoice" value="inner1">Inner 1</label>
</div>
<div>
<label>
<input type="radio" name="nestchoice" value="inner2">Inner 2</label>
</div>
</div>
</div>
"""
for widget in self.nested_widgets:
with self.subTest(widget):
self.check_html(widget, "nestchoice", "outer1", html=html)
def test_choices_select_inner(self):
html = """
<div>
<div>
<label><input type="radio" name="nestchoice" value="outer1">Outer 1</label>
</div>
<div>
<label>Group "1"</label>
<div>
<label>
<input type="radio" name="nestchoice" value="inner1">Inner 1</label>
</div>
<div>
<label>
<input checked type="radio" name="nestchoice" value="inner2">Inner 2
</label>
</div>
</div>
</div>
"""
for widget in self.nested_widgets:
with self.subTest(widget):
self.check_html(widget, "nestchoice", "inner2", html=html)
def test_render_attrs(self):
"""
Attributes provided at render-time are passed to the constituent
inputs.
"""
html = """
<div id="bar">
<div>
<label for="bar_0">
<input checked type="radio" id="bar_0" value="J" name="beatle">John</label>
</div>
<div><label for="bar_1">
<input type="radio" id="bar_1" value="P" name="beatle">Paul</label>
</div>
<div><label for="bar_2">
<input type="radio" id="bar_2" value="G" name="beatle">George</label>
</div>
<div><label for="bar_3">
<input type="radio" id="bar_3" value="R" name="beatle">Ringo</label>
</div>
</div>
"""
self.check_html(
self.widget(choices=self.beatles),
"beatle",
"J",
attrs={"id": "bar"},
html=html,
)
def test_class_attrs(self):
"""
The <div> in the multiple_input.html widget template include the class
attribute.
"""
html = """
<div class="bar">
<div><label>
<input checked type="radio" class="bar" value="J" name="beatle">John</label>
</div>
<div><label>
<input type="radio" class="bar" value="P" name="beatle">Paul</label>
</div>
<div><label>
<input type="radio" class="bar" value="G" name="beatle">George</label>
</div>
<div><label>
<input type="radio" class="bar" value="R" name="beatle">Ringo</label>
</div>
</div>
"""
self.check_html(
self.widget(choices=self.beatles),
"beatle",
"J",
attrs={"class": "bar"},
html=html,
)
@override_settings(USE_THOUSAND_SEPARATOR=True)
def test_doesnt_localize_input_value(self):
choices = [
(1, "One"),
(1000, "One thousand"),
(1000000, "One million"),
]
html = """
<div>
<div><label><input type="radio" name="number" value="1">One</label></div>
<div>
<label><input type="radio" name="number" value="1000">One thousand</label>
</div>
<div>
<label><input type="radio" name="number" value="1000000">One million</label>
</div>
</div>
"""
self.check_html(self.widget(choices=choices), "number", None, html=html)
choices = [
(datetime.time(0, 0), "midnight"),
(datetime.time(12, 0), "noon"),
]
html = """
<div>
<div>
<label><input type="radio" name="time" value="00:00:00">midnight</label>
</div>
<div>
<label><input type="radio" name="time" value="12:00:00">noon</label>
</div>
</div>
"""
self.check_html(self.widget(choices=choices), "time", None, html=html)
def test_render_as_subwidget(self):
"""A RadioSelect as a subwidget of MultiWidget."""
choices = BLANK_CHOICE_DASH + self.beatles
html = """
<div>
<div><label>
<input type="radio" name="beatle_0" value="">------</label>
</div>
<div><label>
<input checked type="radio" name="beatle_0" value="J">John</label>
</div>
<div><label>
<input type="radio" name="beatle_0" value="P">Paul</label>
</div>
<div><label>
<input type="radio" name="beatle_0" value="G">George</label>
</div>
<div><label>
<input type="radio" name="beatle_0" value="R">Ringo</label>
</div>
</div>
<input name="beatle_1" type="text" value="Some text">
"""
self.check_html(
MultiWidget([self.widget(choices=choices), TextInput()]),
"beatle",
["J", "Some text"],
html=html,
)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = ChoiceField(
widget=self.widget, choices=self.beatles, required=False
)
form = TestForm()
self.assertIs(self.widget.use_fieldset, True)
self.assertHTMLEqual(
'<div><fieldset><legend>Field:</legend><div id="id_field">'
'<div><label for="id_field_0">'
'<input type="radio" name="field" value="J" id="id_field_0"> John'
'</label></div><div><label for="id_field_1">'
'<input type="radio" name="field" value="P" id="id_field_1">Paul'
'</label></div><div><label for="id_field_2"><input type="radio" '
'name="field" value="G" id="id_field_2"> George</label></div>'
'<div><label for="id_field_3"><input type="radio" name="field" '
'value="R" id="id_field_3">Ringo</label></div></div></fieldset>'
"</div>",
form.render(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_checkboxinput.py | tests/forms_tests/widget_tests/test_checkboxinput.py | from django.forms import BooleanField, CheckboxInput, Form
from .base import WidgetTest
class CheckboxInputTest(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">'
)
def test_render_true(self):
self.check_html(
self.widget,
"is_cool",
True,
html='<input checked type="checkbox" name="is_cool">',
)
def test_render_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",
html='<input checked type="checkbox" name="is_cool" value="foo">',
)
def test_render_int(self):
"""
Integers are handled by value, not as booleans (#17114).
"""
self.check_html(
self.widget,
"is_cool",
0,
html='<input checked type="checkbox" name="is_cool" value="0">',
)
self.check_html(
self.widget,
"is_cool",
1,
html='<input checked type="checkbox" name="is_cool" value="1">',
)
def test_render_check_test(self):
"""
You can pass 'check_test' to the constructor. This is a callable that
takes the value and returns True if the box should be checked.
"""
widget = CheckboxInput(check_test=lambda value: value.startswith("hello"))
self.check_html(
widget, "greeting", "", html=('<input type="checkbox" name="greeting">')
)
self.check_html(
widget,
"greeting",
"hello",
html=('<input checked type="checkbox" name="greeting" value="hello">'),
)
self.check_html(
widget,
"greeting",
"hello there",
html=(
'<input checked type="checkbox" name="greeting" value="hello there">'
),
)
self.check_html(
widget,
"greeting",
"hello & goodbye",
html=(
'<input checked type="checkbox" name="greeting" '
'value="hello & goodbye">'
),
)
def test_render_check_exception(self):
"""
Calling check_test() shouldn't swallow exceptions (#17888).
"""
widget = CheckboxInput(
check_test=lambda value: value.startswith("hello"),
)
with self.assertRaises(AttributeError):
widget.render("greeting", True)
def test_value_from_datadict(self):
"""
The CheckboxInput widget will return False if the key is not found in
the data dictionary (because HTML form submission doesn't send any
result for unchecked checkboxes).
"""
self.assertFalse(self.widget.value_from_datadict({}, {}, "testing"))
def test_value_from_datadict_string_int(self):
value = self.widget.value_from_datadict({"testing": "0"}, {}, "testing")
self.assertIs(value, True)
def test_value_omitted_from_data(self):
self.assertIs(
self.widget.value_omitted_from_data({"field": "value"}, {}, "field"), False
)
self.assertIs(self.widget.value_omitted_from_data({}, {}, "field"), False)
def test_get_context_does_not_mutate_attrs(self):
attrs = {"checked": False}
self.widget.get_context("name", True, attrs)
self.assertIs(attrs["checked"], False)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = BooleanField(widget=self.widget)
form = TestForm()
self.assertIs(self.widget.use_fieldset, False)
self.assertHTMLEqual(
form.render(),
'<div><label for="id_field">Field:</label>'
'<input id="id_field" name="field" required type="checkbox"></div>',
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/base.py | tests/forms_tests/widget_tests/base.py | from django.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_renderer else []
)
super().setUpClass()
def check_html(
self, widget, name, value, html="", attrs=None, strict=False, **kwargs
):
assertEqual = self.assertEqual if strict else self.assertHTMLEqual
if self.jinja2_renderer:
output = widget.render(
name, value, attrs=attrs, renderer=self.jinja2_renderer, **kwargs
)
# Django escapes quotes with '"' while Jinja2 uses '"'.
output = output.replace(""", """)
# Django escapes single quotes with ''' while Jinja2 uses
# '''.
output = output.replace("'", "'")
assertEqual(output, html)
output = widget.render(
name, value, attrs=attrs, renderer=self.django_renderer, **kwargs
)
assertEqual(output, html)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_clearablefileinput.py | tests/forms_tests/widget_tests/test_clearablefileinput.py | from django.core.files.uploadedfile import SimpleUploadedFile
from django.forms import ClearableFileInput, FileField, Form, MultiWidget
from .base import WidgetTest
class FakeFieldFile:
"""
Quacks like a FieldFile (has a .url and string representation), but
doesn't require us to care about storages etc.
"""
url = "something"
def __str__(self):
return self.url
class ClearableFileInputTest(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: <a href="something">something</a>
<input type="checkbox" name="myfile-clear" id="myfile-clear_id">
<label for="myfile-clear_id">Clear</label><br>
Change: <input type="file" name="myfile">
"""
),
)
def test_html_escaped(self):
"""
A ClearableFileInput should escape name, filename, and URL
when rendering HTML (#15182).
"""
class StrangeFieldFile:
url = "something?chapter=1§=2©=3&lang=en"
def __str__(self):
return """something<div onclick="alert('oops')">.jpg"""
self.check_html(
ClearableFileInput(),
"my<div>file",
StrangeFieldFile(),
html=(
"""
Currently:
<a href="something?chapter=1&sect=2&copy=3&lang=en">
something<div onclick="alert('oops')">.jpg</a>
<input type="checkbox" name="my<div>file-clear"
id="my<div>file-clear_id">
<label for="my<div>file-clear_id">Clear</label><br>
Change: <input type="file" name="my<div>file">
"""
),
)
def test_clear_input_renders_only_if_not_required(self):
"""
A ClearableFileInput with is_required=True does not render a clear
checkbox.
"""
widget = ClearableFileInput()
widget.is_required = True
self.check_html(
widget,
"myfile",
FakeFieldFile(),
html=(
"""
Currently: <a href="something">something</a> <br>
Change: <input type="file" name="myfile">
"""
),
)
def test_clear_input_renders_only_if_initial(self):
"""
A ClearableFileInput instantiated with no initial value does not render
a clear checkbox.
"""
self.check_html(
self.widget, "myfile", None, html='<input type="file" name="myfile">'
)
def test_render_disabled(self):
self.check_html(
self.widget,
"myfile",
FakeFieldFile(),
attrs={"disabled": True},
html=(
'Currently: <a href="something">something</a>'
'<input type="checkbox" name="myfile-clear" '
'id="myfile-clear_id" disabled>'
'<label for="myfile-clear_id">Clear</label><br>'
'Change: <input type="file" name="myfile" disabled>'
),
)
def test_render_checked(self):
self.widget.checked = True
self.check_html(
self.widget,
"myfile",
FakeFieldFile(),
html=(
'Currently: <a href="something">something</a>'
'<input type="checkbox" name="myfile-clear" id="myfile-clear_id" '
"checked>"
'<label for="myfile-clear_id">Clear</label><br>Change: '
'<input type="file" name="myfile" checked>'
),
)
def test_render_no_disabled(self):
class TestForm(Form):
clearable_file = FileField(
widget=self.widget, initial=FakeFieldFile(), required=False
)
form = TestForm()
with self.assertNoLogs("django.template", "DEBUG"):
form.render()
def test_render_as_subwidget(self):
"""A ClearableFileInput as a subwidget of MultiWidget."""
widget = MultiWidget(widgets=(self.widget,))
self.check_html(
widget,
"myfile",
[FakeFieldFile()],
html=(
"""
Currently: <a href="something">something</a>
<input type="checkbox" name="myfile_0-clear" id="myfile_0-clear_id">
<label for="myfile_0-clear_id">Clear</label><br>
Change: <input type="file" name="myfile_0">
"""
),
)
def test_clear_input_checked_returns_false(self):
"""
ClearableFileInput.value_from_datadict returns False if the clear
checkbox is checked, if not required.
"""
value = self.widget.value_from_datadict(
data={"myfile-clear": True},
files={},
name="myfile",
)
self.assertIs(value, False)
self.assertIs(self.widget.checked, True)
def test_clear_input_checked_returns_false_only_if_not_required(self):
"""
ClearableFileInput.value_from_datadict never returns False if the field
is required.
"""
widget = ClearableFileInput()
widget.is_required = True
field = SimpleUploadedFile("something.txt", b"content")
value = widget.value_from_datadict(
data={"myfile-clear": True},
files={"myfile": field},
name="myfile",
)
self.assertEqual(value, field)
self.assertIs(widget.checked, True)
def test_html_does_not_mask_exceptions(self):
"""
A ClearableFileInput should not mask exceptions produced while
checking that it has a value.
"""
class FailingURLFieldFile:
@property
def url(self):
raise ValueError("Canary")
def __str__(self):
return "value"
with self.assertRaisesMessage(ValueError, "Canary"):
self.widget.render("myfile", FailingURLFieldFile())
def test_url_as_property(self):
class URLFieldFile:
@property
def url(self):
return "https://www.python.org/"
def __str__(self):
return "value"
html = self.widget.render("myfile", URLFieldFile())
self.assertInHTML('<a href="https://www.python.org/">value</a>', html)
def test_return_false_if_url_does_not_exists(self):
class NoURLFieldFile:
def __str__(self):
return "value"
html = self.widget.render("myfile", NoURLFieldFile())
self.assertHTMLEqual(html, '<input name="myfile" type="file">')
def test_use_required_attribute(self):
# False when initial data exists. The file input is left blank by the
# user to keep the existing, initial value.
self.assertIs(self.widget.use_required_attribute(None), True)
self.assertIs(self.widget.use_required_attribute("resume.txt"), False)
def test_value_omitted_from_data(self):
widget = ClearableFileInput()
self.assertIs(widget.value_omitted_from_data({}, {}, "field"), True)
self.assertIs(
widget.value_omitted_from_data({}, {"field": "x"}, "field"), False
)
self.assertIs(
widget.value_omitted_from_data({"field-clear": "y"}, {}, "field"), False
)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = FileField(widget=self.widget)
with_file = FileField(widget=self.widget, initial=FakeFieldFile())
clearable_file = FileField(
widget=self.widget, initial=FakeFieldFile(), required=False
)
form = TestForm()
self.assertIs(self.widget.use_fieldset, False)
self.assertHTMLEqual(
'<div><label for="id_field">Field:</label>'
'<input id="id_field" name="field" type="file" required></div>'
'<div><label for="id_with_file">With file:</label>Currently: '
'<a href="something">something</a><br>Change:<input type="file" '
'name="with_file" id="id_with_file"></div>'
'<div><label for="id_clearable_file">Clearable file:</label>'
'Currently: <a href="something">something</a><input '
'type="checkbox" name="clearable_file-clear" id="clearable_file-clear_id">'
'<label for="clearable_file-clear_id">Clear</label><br>Change:'
'<input type="file" name="clearable_file" id="id_clearable_file"></div>',
form.render(),
)
def test_multiple_error(self):
msg = "ClearableFileInput doesn't support uploading multiple files."
with self.assertRaisesMessage(ValueError, msg):
ClearableFileInput(attrs={"multiple": True})
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_textinput.py | tests/forms_tests/widget_tests/test_textinput.py | from django.forms import CharField, Form, TextInput
from django.utils.safestring import mark_safe
from .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",
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").
"""
self.check_html(
self.widget,
"get_spam",
False,
html=('<input type="text" name="get_spam" value="False">'),
)
self.check_html(
self.widget,
"get_spam",
True,
html=('<input type="text" name="get_spam" value="True">'),
)
def test_render_quoted(self):
self.check_html(
self.widget,
"email",
'some "quoted" & ampersanded value',
html=(
'<input type="text" name="email" '
'value="some "quoted" & ampersanded value">'
),
)
def test_render_custom_attrs(self):
self.check_html(
self.widget,
"email",
"test@example.com",
attrs={"class": "fun"},
html=(
'<input type="text" name="email" value="test@example.com" class="fun">'
),
)
def test_render_unicode(self):
self.check_html(
self.widget,
"email",
"ŠĐĆŽćžšđ",
attrs={"class": "fun"},
html=(
'<input type="text" name="email" '
'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" class="fun">'
),
)
def test_constructor_attrs(self):
widget = TextInput(attrs={"class": "fun", "type": "email"})
self.check_html(
widget, "email", "", html='<input type="email" class="fun" name="email">'
)
self.check_html(
widget,
"email",
"foo@example.com",
html=(
'<input type="email" class="fun" value="foo@example.com" name="email">'
),
)
def test_attrs_precedence(self):
"""
`attrs` passed to render() get precedence over those passed to the
constructor
"""
widget = TextInput(attrs={"class": "pretty"})
self.check_html(
widget,
"email",
"",
attrs={"class": "special"},
html='<input type="text" class="special" name="email">',
)
def test_attrs_safestring(self):
widget = TextInput(attrs={"onBlur": mark_safe("function('foo')")})
self.check_html(
widget,
"email",
"",
html='<input onBlur="function(\'foo\')" type="text" name="email">',
)
def test_use_required_attribute(self):
# Text inputs can safely trigger the browser validation.
self.assertIs(self.widget.use_required_attribute(None), True)
self.assertIs(self.widget.use_required_attribute(""), True)
self.assertIs(self.widget.use_required_attribute("resume.txt"), True)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = CharField(widget=self.widget)
form = TestForm()
self.assertIs(self.widget.use_fieldset, False)
self.assertHTMLEqual(
'<div><label for="id_field">Field:</label>'
'<input type="text" name="field" required id="id_field"></div>',
form.render(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/forms_tests/widget_tests/test_selectmultiple.py | tests/forms_tests/widget_tests/test_selectmultiple.py | from django.forms import ChoiceField, Form, SelectMultiple
from .base import WidgetTest
class SelectMultipleTest(WidgetTest):
widget = SelectMultiple
numeric_choices = (("0", "0"), ("1", "1"), ("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="beatles">
<option value="J" selected>John</option>
<option value="P">Paul</option>
<option value="G">George</option>
<option value="R">Ringo</option>
</select>"""
),
)
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" selected>John</option>
<option value="P" selected>Paul</option>
<option value="G">George</option>
<option value="R">Ringo</option>
</select>"""
),
)
def test_render_none(self):
"""
If the value is None, none of the options are selected, even if the
choices have an empty option.
"""
self.check_html(
self.widget(choices=(("", "Unknown"),) + self.beatles),
"beatles",
None,
html=(
"""<select multiple name="beatles">
<option value="">Unknown</option>
<option value="J">John</option>
<option value="P">Paul</option>
<option value="G">George</option>
<option value="R">Ringo</option>
</select>"""
),
)
def test_render_value_label(self):
"""
If the value corresponds to a label (but not to an option value), none
of the options are selected.
"""
self.check_html(
self.widget(choices=self.beatles),
"beatles",
["John"],
html=(
"""<select multiple name="beatles">
<option value="J">John</option>
<option value="P">Paul</option>
<option value="G">George</option>
<option value="R">Ringo</option>
</select>"""
),
)
def test_multiple_options_same_value(self):
"""
Multiple options with the same value can be selected (#8103).
"""
self.check_html(
self.widget(choices=self.numeric_choices),
"choices",
["0"],
html=(
"""<select multiple name="choices">
<option value="0" selected>0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="0" selected>extra</option>
</select>"""
),
)
def test_multiple_values_invalid(self):
"""
If multiple values are given, but some of them are not valid, the valid
ones are selected.
"""
self.check_html(
self.widget(choices=self.beatles),
"beatles",
["J", "G", "foo"],
html=(
"""<select multiple name="beatles">
<option value="J" selected>John</option>
<option value="P">Paul</option>
<option value="G" selected>George</option>
<option value="R">Ringo</option>
</select>"""
),
)
def test_compare_string(self):
choices = [("1", "1"), ("2", "2"), ("3", "3")]
self.check_html(
self.widget(choices=choices),
"nums",
[2],
html=(
"""<select multiple name="nums">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
</select>"""
),
)
self.check_html(
self.widget(choices=choices),
"nums",
["2"],
html=(
"""<select multiple name="nums">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
</select>"""
),
)
self.check_html(
self.widget(choices=choices),
"nums",
[2],
html=(
"""<select multiple name="nums">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
</select>"""
),
)
def test_optgroup_select_multiple(self):
widget = SelectMultiple(
choices=(
("outer1", "Outer 1"),
('Group "1"', (("inner1", "Inner 1"), ("inner2", "Inner 2"))),
)
)
self.check_html(
widget,
"nestchoice",
["outer1", "inner2"],
html=(
"""<select multiple name="nestchoice">
<option value="outer1" selected>Outer 1</option>
<optgroup label="Group "1"">
<option value="inner1">Inner 1</option>
<option value="inner2" selected>Inner 2</option>
</optgroup>
</select>"""
),
)
def test_value_omitted_from_data(self):
widget = self.widget(choices=self.beatles)
self.assertIs(widget.value_omitted_from_data({}, {}, "field"), False)
self.assertIs(
widget.value_omitted_from_data({"field": "value"}, {}, "field"), False
)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = ChoiceField(
widget=self.widget, choices=self.beatles, required=False
)
form = TestForm()
self.assertIs(self.widget.use_fieldset, False)
self.assertHTMLEqual(
'<div><label for="id_field">Field:</label>'
'<select multiple name="field" id="id_field">'
'<option value="J">John</option> <option value="P">Paul</option>'
'<option value="G">George</option><option value="R">Ringo'
"</option></select></div>",
form.render(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_client/views.py | tests/test_client/views.py | import json
from urllib.parse import urlencode
from xml.dom.minidom import parseString
from django.contrib.auth.decorators import login_required, permission_required
from django.core import mail
from django.core.exceptions import ValidationError
from django.forms import fields
from django.forms.forms import Form
from django.http import (
HttpResponse,
HttpResponseBadRequest,
HttpResponseNotAllowed,
HttpResponseNotFound,
HttpResponseRedirect,
)
from django.shortcuts import render
from django.template import Context, Template
from django.test import Client
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
def get_view(request):
"A simple view that expects a GET request, and returns a rendered template"
t = Template("This is a test. {{ var }} is the value.", name="GET Template")
c = Context({"var": request.GET.get("var", 42)})
return HttpResponse(t.render(c))
async def async_get_view(request):
return HttpResponse(b"GET content.")
def trace_view(request):
"""
A simple view that expects a TRACE request and echoes its status line.
TRACE requests should not have an entity; the view will return a 400 status
response if it is present.
"""
if request.method.upper() != "TRACE":
return HttpResponseNotAllowed("TRACE")
elif request.body:
return HttpResponseBadRequest("TRACE requests MUST NOT include an entity")
else:
protocol = request.META["SERVER_PROTOCOL"]
t = Template(
"{{ method }} {{ uri }} {{ version }}",
name="TRACE Template",
)
c = Context(
{
"method": request.method,
"uri": request.path,
"version": protocol,
}
)
return HttpResponse(t.render(c))
def put_view(request):
if request.method == "PUT":
t = Template("Data received: {{ data }} is the body.", name="PUT Template")
c = Context(
{
"Content-Length": request.META["CONTENT_LENGTH"],
"data": request.body.decode(),
}
)
else:
t = Template("Viewing GET page.", name="Empty GET Template")
c = Context()
return HttpResponse(t.render(c))
def post_view(request):
"""A view that expects a POST, and returns a different template depending
on whether any POST data is available
"""
if request.method == "POST":
if request.POST:
t = Template(
"Data received: {{ data }} is the value.", name="POST Template"
)
c = Context({"data": request.POST["value"]})
else:
t = Template("Viewing POST page.", name="Empty POST Template")
c = Context()
else:
t = Template("Viewing GET page.", name="Empty GET Template")
# Used by test_body_read_on_get_data.
request.read(200)
c = Context()
return HttpResponse(t.render(c))
def post_then_get_view(request):
"""
A view that expects a POST request, returns a redirect response
to itself providing only a ?success=true querystring,
the value of this querystring is then rendered upon GET.
"""
if request.method == "POST":
return HttpResponseRedirect("?success=true")
t = Template("The value of success is {{ value }}.", name="GET Template")
c = Context({"value": request.GET.get("success", "false")})
return HttpResponse(t.render(c))
def json_view(request):
"""
A view that expects a request with the header 'application/json' and JSON
data, which is deserialized and included in the context.
"""
if request.META.get("CONTENT_TYPE") != "application/json":
return HttpResponse()
t = Template("Viewing {} page. With data {{ data }}.".format(request.method))
data = json.loads(request.body.decode("utf-8"))
c = Context({"data": data})
return HttpResponse(t.render(c))
def view_with_header(request):
"A view that has a custom header"
response = HttpResponse()
response.headers["X-DJANGO-TEST"] = "Slartibartfast"
return response
def raw_post_view(request):
"""A view which expects raw XML to be posted and returns content extracted
from the XML"""
if request.method == "POST":
root = parseString(request.body)
first_book = root.firstChild.firstChild
title, author = [n.firstChild.nodeValue for n in first_book.childNodes]
t = Template("{{ title }} - {{ author }}", name="Book template")
c = Context({"title": title, "author": author})
else:
t = Template("GET request.", name="Book GET template")
c = Context()
return HttpResponse(t.render(c))
def redirect_view(request):
"A view that redirects all requests to the GET view"
if request.GET:
query = "?" + urlencode(request.GET, True)
else:
query = ""
return HttpResponseRedirect("/get_view/" + query)
def method_saving_307_redirect_query_string_view(request):
return HttpResponseRedirect("/post_view/?hello=world", status=307)
def method_saving_308_redirect_query_string_view(request):
return HttpResponseRedirect("/post_view/?hello=world", status=308)
def _post_view_redirect(request, status_code):
"""Redirect to /post_view/ using the status code."""
redirect_to = request.GET.get("to", "/post_view/")
return HttpResponseRedirect(redirect_to, status=status_code)
def method_saving_307_redirect_view(request):
return _post_view_redirect(request, 307)
def method_saving_308_redirect_view(request):
return _post_view_redirect(request, 308)
def redirect_to_different_hostname(request):
return HttpResponseRedirect("https://hostname2/get_host_view/")
def get_host_view(request):
return HttpResponse(request.get_host())
def view_with_secure(request):
"A view that indicates if the request was secure"
response = HttpResponse()
response.test_was_secure_request = request.is_secure()
response.test_server_port = request.META.get("SERVER_PORT", 80)
return response
def double_redirect_view(request):
"A view that redirects all requests to a redirection view"
return HttpResponseRedirect("/permanent_redirect_view/")
def bad_view(request):
"A view that returns a 404 with some error content"
return HttpResponseNotFound("Not found!. This page contains some MAGIC content")
TestChoices = (
("a", "First Choice"),
("b", "Second Choice"),
("c", "Third Choice"),
("d", "Fourth Choice"),
("e", "Fifth Choice"),
)
class TestForm(Form):
text = fields.CharField()
email = fields.EmailField()
value = fields.IntegerField()
single = fields.ChoiceField(choices=TestChoices)
multi = fields.MultipleChoiceField(choices=TestChoices)
def clean(self):
cleaned_data = self.cleaned_data
if cleaned_data.get("text") == "Raise non-field error":
raise ValidationError("Non-field error.")
return cleaned_data
def form_view(request):
"A view that tests a simple form"
if request.method == "POST":
form = TestForm(request.POST)
if form.is_valid():
t = Template("Valid POST data.", name="Valid POST Template")
c = Context()
else:
t = Template(
"Invalid POST data. {{ form.errors }}", name="Invalid POST Template"
)
c = Context({"form": form})
else:
form = TestForm(request.GET)
t = Template("Viewing base form. {{ form }}.", name="Form GET Template")
c = Context({"form": form})
return HttpResponse(t.render(c))
def form_view_with_template(request):
"A view that tests a simple form"
if request.method == "POST":
form = TestForm(request.POST)
if form.is_valid():
message = "POST data OK"
else:
message = "POST data has errors"
else:
form = TestForm()
message = "GET form page"
return render(
request,
"form_view.html",
{
"form": form,
"message": message,
},
)
@login_required
def login_protected_view(request):
"A simple view that is login protected."
t = Template(
"This is a login protected test. Username is {{ user.username }}.",
name="Login Template",
)
c = Context({"user": request.user})
return HttpResponse(t.render(c))
@login_required(redirect_field_name="redirect_to")
def login_protected_view_changed_redirect(request):
"A simple view that is login protected with a custom redirect field set"
t = Template(
"This is a login protected test. Username is {{ user.username }}.",
name="Login Template",
)
c = Context({"user": request.user})
return HttpResponse(t.render(c))
def _permission_protected_view(request):
"A simple view that is permission protected."
t = Template(
"This is a permission protected test. "
"Username is {{ user.username }}. "
"Permissions are {{ user.get_all_permissions }}.",
name="Permissions Template",
)
c = Context({"user": request.user})
return HttpResponse(t.render(c))
permission_protected_view = permission_required("permission_not_granted")(
_permission_protected_view
)
permission_protected_view_exception = permission_required(
"permission_not_granted", raise_exception=True
)(_permission_protected_view)
class _ViewManager:
@method_decorator(login_required)
def login_protected_view(self, request):
t = Template(
"This is a login protected test using a method. "
"Username is {{ user.username }}.",
name="Login Method Template",
)
c = Context({"user": request.user})
return HttpResponse(t.render(c))
@method_decorator(permission_required("permission_not_granted"))
def permission_protected_view(self, request):
t = Template(
"This is a permission protected test using a method. "
"Username is {{ user.username }}. "
"Permissions are {{ user.get_all_permissions }}.",
name="Permissions Template",
)
c = Context({"user": request.user})
return HttpResponse(t.render(c))
_view_manager = _ViewManager()
login_protected_method_view = _view_manager.login_protected_view
permission_protected_method_view = _view_manager.permission_protected_view
def session_view(request):
"A view that modifies the session"
request.session["tobacconist"] = "hovercraft"
t = Template(
"This is a view that modifies the session.",
name="Session Modifying View Template",
)
c = Context()
return HttpResponse(t.render(c))
def broken_view(request):
"""A view which just raises an exception, simulating a broken view."""
raise KeyError("Oops! Looks like you wrote some bad code.")
def mail_sending_view(request):
mail.EmailMessage(
"Test message",
"This is a test email",
"from@example.com",
["first@example.com", "second@example.com"],
).send()
return HttpResponse("Mail sent")
def mass_mail_sending_view(request):
m1 = mail.EmailMessage(
"First Test message",
"This is the first test email",
"from@example.com",
["first@example.com", "second@example.com"],
)
m2 = mail.EmailMessage(
"Second Test message",
"This is the second test email",
"from@example.com",
["second@example.com", "third@example.com"],
)
c = mail.get_connection()
c.send_messages([m1, m2])
return HttpResponse("Mail sent")
def nesting_exception_view(request):
"""
A view that uses a nested client to call another view and then raises an
exception.
"""
client = Client()
client.get("/get_view/")
raise Exception("exception message")
def django_project_redirect(request):
return HttpResponseRedirect("https://www.djangoproject.com/")
def no_trailing_slash_external_redirect(request):
"""
RFC 3986 Section 6.2.3: Empty path should be normalized to "/".
Use https://testserver, rather than an external domain, in order to allow
use of follow=True, triggering Client._handle_redirects().
"""
return HttpResponseRedirect("https://testserver")
def index_view(request):
"""Target for no_trailing_slash_external_redirect with follow=True."""
return HttpResponse("Hello world")
def upload_view(request):
"""Prints keys of request.FILES to the response."""
return HttpResponse(", ".join(request.FILES))
class TwoArgException(Exception):
def __init__(self, one, two):
pass
def two_arg_exception(request):
raise TwoArgException("one", "two")
class CBView(TemplateView):
template_name = "base.html"
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_client/test_conditional_content_removal.py | tests/test_client/test_conditional_content_removal.py | import gzip
from django.http import HttpRequest, HttpResponse, StreamingHttpResponse
from django.test import SimpleTestCase
from django.test.client import conditional_content_removal
class ConditionalContentTests(SimpleTestCase):
def test_conditional_content_removal(self):
"""
Content is removed from regular and streaming responses with a
status_code of 100-199, 204, 304, or a method of "HEAD".
"""
req = HttpRequest()
# Do nothing for 200 responses.
res = HttpResponse("abc")
conditional_content_removal(req, res)
self.assertEqual(res.content, b"abc")
res = StreamingHttpResponse(["abc"])
conditional_content_removal(req, res)
self.assertEqual(b"".join(res), b"abc")
# Strip content for some status codes.
for status_code in (100, 150, 199, 204, 304):
res = HttpResponse("abc", status=status_code)
conditional_content_removal(req, res)
self.assertEqual(res.content, b"")
res = StreamingHttpResponse(["abc"], status=status_code)
conditional_content_removal(req, res)
self.assertEqual(b"".join(res), b"")
# Issue #20472
abc = gzip.compress(b"abc")
res = HttpResponse(abc, status=304)
res["Content-Encoding"] = "gzip"
conditional_content_removal(req, res)
self.assertEqual(res.content, b"")
res = StreamingHttpResponse([abc], status=304)
res["Content-Encoding"] = "gzip"
conditional_content_removal(req, res)
self.assertEqual(b"".join(res), b"")
# Strip content for HEAD requests.
req.method = "HEAD"
res = HttpResponse("abc")
conditional_content_removal(req, res)
self.assertEqual(res.content, b"")
res = StreamingHttpResponse(["abc"])
conditional_content_removal(req, res)
self.assertEqual(b"".join(res), b"")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_client/auth_backends.py | tests/test_client/auth_backends.py | from django.contrib.auth.backends import ModelBackend
class TestClientBackend(ModelBackend):
pass
class BackendWithoutGetUserMethod:
pass
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_client/test_fakepayload.py | tests/test_client/test_fakepayload.py | from django.test import SimpleTestCase
from django.test.client import FakePayload
class FakePayloadTests(SimpleTestCase):
def test_write_after_read(self):
payload = FakePayload()
for operation in [payload.read, payload.readline]:
with self.subTest(operation=operation.__name__):
operation()
msg = "Unable to write a payload after it's been read"
with self.assertRaisesMessage(ValueError, msg):
payload.write(b"abc")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_client/__init__.py | tests/test_client/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_client/tests.py | tests/test_client/tests.py | """
Testing using the Test Client
The test client is a class that can act like a simple
browser for testing purposes.
It allows the user to compose GET and POST requests, and
obtain the response that the server gave to those requests.
The server Response objects are annotated with the details
of the contexts and templates that were rendered during the
process of serving the request.
``Client`` objects are stateful - they will retain cookie (and
thus session) details for the lifetime of the ``Client`` instance.
This is not intended as a replacement for Twill, Selenium, or
other browser automation frameworks - it is here to allow
testing against the contexts and templates produced by a view,
rather than the HTML rendered to the end-user.
"""
import copy
import itertools
import tempfile
from unittest import mock
from django.contrib.auth.models import User
from django.core import mail
from django.http import HttpResponse, HttpResponseNotAllowed
from django.test import (
AsyncRequestFactory,
Client,
RequestFactory,
SimpleTestCase,
TestCase,
modify_settings,
override_settings,
)
from django.urls import reverse_lazy
from django.utils.decorators import async_only_middleware
from django.views.generic import RedirectView
from .views import TwoArgException, get_view, post_view, trace_view
def middleware_urlconf(get_response):
def middleware(request):
request.urlconf = "test_client.urls_middleware_urlconf"
return get_response(request)
return middleware
@async_only_middleware
def async_middleware_urlconf(get_response):
async def middleware(request):
request.urlconf = "test_client.urls_middleware_urlconf"
return await get_response(request)
return middleware
@override_settings(ROOT_URLCONF="test_client.urls")
class ClientTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.u1 = User.objects.create_user(username="testclient", password="password")
cls.u2 = User.objects.create_user(
username="inactive", password="password", is_active=False
)
def test_get_view(self):
"GET a view"
# The data is ignored, but let's check it doesn't crash the system
# anyway.
data = {"var": "\xf2"}
response = self.client.get("/get_view/", data)
# Check some response details
self.assertContains(response, "This is a test")
self.assertEqual(response.context["var"], "\xf2")
self.assertEqual(response.templates[0].name, "GET Template")
def test_copy_response(self):
tests = ["/cbv_view/", "/get_view/"]
for url in tests:
with self.subTest(url=url):
response = self.client.get(url)
response_copy = copy.copy(response)
self.assertEqual(repr(response), repr(response_copy))
self.assertIs(response_copy.client, response.client)
self.assertIs(response_copy.resolver_match, response.resolver_match)
self.assertIs(response_copy.wsgi_request, response.wsgi_request)
async def test_copy_response_async(self):
response = await self.async_client.get("/async_get_view/")
response_copy = copy.copy(response)
self.assertEqual(repr(response), repr(response_copy))
self.assertIs(response_copy.client, response.client)
self.assertIs(response_copy.resolver_match, response.resolver_match)
self.assertIs(response_copy.asgi_request, response.asgi_request)
def test_query_string_encoding(self):
# WSGI requires latin-1 encoded strings.
response = self.client.get("/get_view/?var=1\ufffd")
self.assertEqual(response.context["var"], "1\ufffd")
def test_get_data_none(self):
msg = (
"Cannot encode None for key 'value' in a query string. Did you "
"mean to pass an empty string or omit the value?"
)
with self.assertRaisesMessage(TypeError, msg):
self.client.get("/get_view/", {"value": None})
def test_get_post_view(self):
"GET a view that normally expects POSTs"
response = self.client.get("/post_view/", {})
# Check some response details
self.assertEqual(response.status_code, 200)
self.assertEqual(response.templates[0].name, "Empty GET Template")
self.assertTemplateUsed(response, "Empty GET Template")
self.assertTemplateNotUsed(response, "Empty POST Template")
def test_empty_post(self):
"POST an empty dictionary to a view"
response = self.client.post("/post_view/", {})
# Check some response details
self.assertEqual(response.status_code, 200)
self.assertEqual(response.templates[0].name, "Empty POST Template")
self.assertTemplateNotUsed(response, "Empty GET Template")
self.assertTemplateUsed(response, "Empty POST Template")
def test_post(self):
"POST some data to a view"
post_data = {"value": 37}
response = self.client.post("/post_view/", post_data)
# Check some response details
self.assertContains(response, "Data received")
self.assertEqual(response.context["data"], "37")
self.assertEqual(response.templates[0].name, "POST Template")
def test_post_data_none(self):
msg = (
"Cannot encode None for key 'value' as POST data. Did you mean "
"to pass an empty string or omit the value?"
)
with self.assertRaisesMessage(TypeError, msg):
self.client.post("/post_view/", {"value": None})
def test_json_serialization(self):
"""The test client serializes JSON data."""
methods = ("post", "put", "patch", "delete")
tests = (
({"value": 37}, {"value": 37}),
([37, True], [37, True]),
((37, False), [37, False]),
)
for method in methods:
with self.subTest(method=method):
for data, expected in tests:
with self.subTest(data):
client_method = getattr(self.client, method)
method_name = method.upper()
response = client_method(
"/json_view/", data, content_type="application/json"
)
self.assertContains(response, "Viewing %s page." % method_name)
self.assertEqual(response.context["data"], expected)
def test_json_encoder_argument(self):
"""The test Client accepts a json_encoder."""
mock_encoder = mock.MagicMock()
mock_encoding = mock.MagicMock()
mock_encoder.return_value = mock_encoding
mock_encoding.encode.return_value = '{"value": 37}'
client = self.client_class(json_encoder=mock_encoder)
# Vendored tree JSON content types are accepted.
client.post(
"/json_view/", {"value": 37}, content_type="application/vnd.api+json"
)
self.assertTrue(mock_encoder.called)
self.assertTrue(mock_encoding.encode.called)
def test_put(self):
response = self.client.put("/put_view/", {"foo": "bar"})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.templates[0].name, "PUT Template")
self.assertEqual(response.context["data"], "{'foo': 'bar'}")
self.assertEqual(response.context["Content-Length"], "14")
def test_trace(self):
"""TRACE a view"""
response = self.client.trace("/trace_view/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context["method"], "TRACE")
self.assertEqual(response.templates[0].name, "TRACE Template")
def test_response_headers(self):
"Check the value of HTTP headers returned in a response"
response = self.client.get("/header_view/")
self.assertEqual(response.headers["X-DJANGO-TEST"], "Slartibartfast")
def test_response_attached_request(self):
"""
The returned response has a ``request`` attribute with the originating
environ dict and a ``wsgi_request`` with the originating WSGIRequest.
"""
response = self.client.get("/header_view/")
self.assertTrue(hasattr(response, "request"))
self.assertTrue(hasattr(response, "wsgi_request"))
for key, value in response.request.items():
self.assertIn(key, response.wsgi_request.environ)
self.assertEqual(response.wsgi_request.environ[key], value)
def test_response_resolver_match(self):
"""
The response contains a ResolverMatch instance.
"""
response = self.client.get("/header_view/")
self.assertTrue(hasattr(response, "resolver_match"))
def test_response_resolver_match_redirect_follow(self):
"""
The response ResolverMatch instance contains the correct
information when following redirects.
"""
response = self.client.get("/redirect_view/", follow=True)
self.assertEqual(response.resolver_match.url_name, "get_view")
def test_response_resolver_match_regular_view(self):
"""
The response ResolverMatch instance contains the correct
information when accessing a regular view.
"""
response = self.client.get("/get_view/")
self.assertEqual(response.resolver_match.url_name, "get_view")
def test_response_resolver_match_class_based_view(self):
"""
The response ResolverMatch instance can be used to access the CBV view
class.
"""
response = self.client.get("/accounts/")
self.assertIs(response.resolver_match.func.view_class, RedirectView)
@modify_settings(MIDDLEWARE={"prepend": "test_client.tests.middleware_urlconf"})
def test_response_resolver_match_middleware_urlconf(self):
response = self.client.get("/middleware_urlconf_view/")
self.assertEqual(response.resolver_match.url_name, "middleware_urlconf_view")
def test_raw_post(self):
"POST raw data (with a content type) to a view"
test_doc = """<?xml version="1.0" encoding="utf-8"?>
<library><book><title>Blink</title><author>Malcolm Gladwell</author></book>
</library>
"""
response = self.client.post(
"/raw_post_view/", test_doc, content_type="text/xml"
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.templates[0].name, "Book template")
self.assertEqual(response.content, b"Blink - Malcolm Gladwell")
def test_insecure(self):
"GET a URL through http"
response = self.client.get("/secure_view/", secure=False)
self.assertFalse(response.test_was_secure_request)
self.assertEqual(response.test_server_port, "80")
def test_secure(self):
"GET a URL through https"
response = self.client.get("/secure_view/", secure=True)
self.assertTrue(response.test_was_secure_request)
self.assertEqual(response.test_server_port, "443")
def test_redirect(self):
"GET a URL that redirects elsewhere"
response = self.client.get("/redirect_view/")
self.assertRedirects(response, "/get_view/")
def test_redirect_with_query(self):
"GET a URL that redirects with given GET parameters"
response = self.client.get("/redirect_view/", {"var": "value"})
self.assertRedirects(response, "/get_view/?var=value")
def test_redirect_with_query_ordering(self):
"""assertRedirects() ignores the order of query string parameters."""
response = self.client.get("/redirect_view/", {"var": "value", "foo": "bar"})
self.assertRedirects(response, "/get_view/?var=value&foo=bar")
self.assertRedirects(response, "/get_view/?foo=bar&var=value")
def test_permanent_redirect(self):
"GET a URL that redirects permanently elsewhere"
response = self.client.get("/permanent_redirect_view/")
self.assertRedirects(response, "/get_view/", status_code=301)
def test_temporary_redirect(self):
"GET a URL that does a non-permanent redirect"
response = self.client.get("/temporary_redirect_view/")
self.assertRedirects(response, "/get_view/", status_code=302)
def test_redirect_to_strange_location(self):
"GET a URL that redirects to a non-200 page"
response = self.client.get("/double_redirect_view/")
# The response was a 302, and that the attempt to get the redirection
# location returned 301 when retrieved
self.assertRedirects(
response, "/permanent_redirect_view/", target_status_code=301
)
def test_follow_redirect(self):
"A URL that redirects can be followed to termination."
response = self.client.get("/double_redirect_view/", follow=True)
self.assertRedirects(
response, "/get_view/", status_code=302, target_status_code=200
)
self.assertEqual(len(response.redirect_chain), 2)
def test_follow_relative_redirect(self):
"A URL with a relative redirect can be followed."
response = self.client.get("/accounts/", follow=True)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.request["PATH_INFO"], "/accounts/login/")
def test_follow_relative_redirect_no_trailing_slash(self):
"""
A URL with a relative redirect with no trailing slash can be followed.
"""
response = self.client.get("/accounts/no_trailing_slash", follow=True)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.request["PATH_INFO"], "/accounts/login/")
def test_redirect_to_querystring_only(self):
"""A URL that consists of a querystring only can be followed"""
response = self.client.post("/post_then_get_view/", follow=True)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.request["PATH_INFO"], "/post_then_get_view/")
self.assertEqual(response.content, b"The value of success is true.")
def test_follow_307_and_308_redirect(self):
"""
A 307 or 308 redirect preserves the request method after the redirect.
"""
methods = ("get", "post", "head", "options", "put", "patch", "delete", "trace")
codes = (307, 308)
for method, code in itertools.product(methods, codes):
with self.subTest(method=method, code=code):
req_method = getattr(self.client, method)
response = req_method(
"/redirect_view_%s/" % code, data={"value": "test"}, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.request["PATH_INFO"], "/post_view/")
self.assertEqual(response.request["REQUEST_METHOD"], method.upper())
def test_follow_307_and_308_preserves_query_string(self):
methods = ("post", "options", "put", "patch", "delete", "trace")
codes = (307, 308)
for method, code in itertools.product(methods, codes):
with self.subTest(method=method, code=code):
req_method = getattr(self.client, method)
response = req_method(
"/redirect_view_%s_query_string/" % code,
data={"value": "test"},
follow=True,
)
self.assertRedirects(
response, "/post_view/?hello=world", status_code=code
)
self.assertEqual(response.request["QUERY_STRING"], "hello=world")
def test_follow_307_and_308_get_head_query_string(self):
methods = ("get", "head")
codes = (307, 308)
for method, code in itertools.product(methods, codes):
with self.subTest(method=method, code=code):
req_method = getattr(self.client, method)
response = req_method(
"/redirect_view_%s_query_string/" % code,
data={"value": "test"},
follow=True,
)
self.assertRedirects(
response, "/post_view/?hello=world", status_code=code
)
self.assertEqual(response.request["QUERY_STRING"], "value=test")
def test_follow_307_and_308_preserves_post_data(self):
for code in (307, 308):
with self.subTest(code=code):
response = self.client.post(
"/redirect_view_%s/" % code, data={"value": "test"}, follow=True
)
self.assertContains(response, "test is the value")
def test_follow_307_and_308_preserves_put_body(self):
for code in (307, 308):
with self.subTest(code=code):
response = self.client.put(
"/redirect_view_%s/?to=/put_view/" % code, data="a=b", follow=True
)
self.assertContains(response, "a=b is the body")
def test_follow_307_and_308_preserves_get_params(self):
data = {"var": 30, "to": "/get_view/"}
for code in (307, 308):
with self.subTest(code=code):
response = self.client.get(
"/redirect_view_%s/" % code, data=data, follow=True
)
self.assertContains(response, "30 is the value")
def test_redirect_http(self):
"""GET a URL that redirects to an HTTP URI."""
response = self.client.get("/http_redirect_view/", follow=True)
self.assertFalse(response.test_was_secure_request)
def test_redirect_https(self):
"""GET a URL that redirects to an HTTPS URI."""
response = self.client.get("/https_redirect_view/", follow=True)
self.assertTrue(response.test_was_secure_request)
def test_notfound_response(self):
"GET a URL that responds as '404:Not Found'"
response = self.client.get("/bad_view/")
self.assertContains(response, "MAGIC", status_code=404)
def test_valid_form(self):
"POST valid data to a form"
post_data = {
"text": "Hello World",
"email": "foo@example.com",
"value": 37,
"single": "b",
"multi": ("b", "c", "e"),
}
response = self.client.post("/form_view/", post_data)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "Valid POST Template")
def test_valid_form_with_hints(self):
"GET a form, providing hints in the GET data"
hints = {"text": "Hello World", "multi": ("b", "c", "e")}
response = self.client.get("/form_view/", data=hints)
# The multi-value data has been rolled out ok
self.assertContains(response, "Select a valid choice.", 0)
self.assertTemplateUsed(response, "Form GET Template")
def test_incomplete_data_form(self):
"POST incomplete data to a form"
post_data = {"text": "Hello World", "value": 37}
response = self.client.post("/form_view/", post_data)
self.assertContains(response, "This field is required.", 3)
self.assertTemplateUsed(response, "Invalid POST Template")
form = response.context["form"]
self.assertFormError(form, "email", "This field is required.")
self.assertFormError(form, "single", "This field is required.")
self.assertFormError(form, "multi", "This field is required.")
def test_form_error(self):
"POST erroneous data to a form"
post_data = {
"text": "Hello World",
"email": "not an email address",
"value": 37,
"single": "b",
"multi": ("b", "c", "e"),
}
response = self.client.post("/form_view/", post_data)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "Invalid POST Template")
self.assertFormError(
response.context["form"], "email", "Enter a valid email address."
)
def test_valid_form_with_template(self):
"POST valid data to a form using multiple templates"
post_data = {
"text": "Hello World",
"email": "foo@example.com",
"value": 37,
"single": "b",
"multi": ("b", "c", "e"),
}
response = self.client.post("/form_view_with_template/", post_data)
self.assertContains(response, "POST data OK")
self.assertTemplateUsed(response, "form_view.html")
self.assertTemplateUsed(response, "base.html")
self.assertTemplateNotUsed(response, "Valid POST Template")
def test_incomplete_data_form_with_template(self):
"POST incomplete data to a form using multiple templates"
post_data = {"text": "Hello World", "value": 37}
response = self.client.post("/form_view_with_template/", post_data)
self.assertContains(response, "POST data has errors")
self.assertTemplateUsed(response, "form_view.html")
self.assertTemplateUsed(response, "base.html")
self.assertTemplateNotUsed(response, "Invalid POST Template")
form = response.context["form"]
self.assertFormError(form, "email", "This field is required.")
self.assertFormError(form, "single", "This field is required.")
self.assertFormError(form, "multi", "This field is required.")
def test_form_error_with_template(self):
"POST erroneous data to a form using multiple templates"
post_data = {
"text": "Hello World",
"email": "not an email address",
"value": 37,
"single": "b",
"multi": ("b", "c", "e"),
}
response = self.client.post("/form_view_with_template/", post_data)
self.assertContains(response, "POST data has errors")
self.assertTemplateUsed(response, "form_view.html")
self.assertTemplateUsed(response, "base.html")
self.assertTemplateNotUsed(response, "Invalid POST Template")
self.assertFormError(
response.context["form"], "email", "Enter a valid email address."
)
def test_unknown_page(self):
"GET an invalid URL"
response = self.client.get("/unknown_view/")
# The response was a 404
self.assertEqual(response.status_code, 404)
def test_url_parameters(self):
"Make sure that URL ;-parameters are not stripped."
response = self.client.get("/unknown_view/;some-parameter")
# The path in the response includes it (ignore that it's a 404)
self.assertEqual(response.request["PATH_INFO"], "/unknown_view/;some-parameter")
def test_view_with_login(self):
"Request a page that is protected with @login_required"
# Get the page without logging in. Should result in 302.
response = self.client.get("/login_protected_view/")
self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/")
# Log in
login = self.client.login(username="testclient", password="password")
self.assertTrue(login, "Could not log in")
# Request a page that requires a login
response = self.client.get("/login_protected_view/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context["user"].username, "testclient")
@override_settings(
INSTALLED_APPS=["django.contrib.auth"],
SESSION_ENGINE="django.contrib.sessions.backends.file",
)
def test_view_with_login_when_sessions_app_is_not_installed(self):
self.test_view_with_login()
def test_view_with_force_login(self):
"Request a page that is protected with @login_required"
# Get the page without logging in. Should result in 302.
response = self.client.get("/login_protected_view/")
self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/")
# Log in
self.client.force_login(self.u1)
# Request a page that requires a login
response = self.client.get("/login_protected_view/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context["user"].username, "testclient")
def test_view_with_method_login(self):
"Request a page that is protected with a @login_required method"
# Get the page without logging in. Should result in 302.
response = self.client.get("/login_protected_method_view/")
self.assertRedirects(
response, "/accounts/login/?next=/login_protected_method_view/"
)
# Log in
login = self.client.login(username="testclient", password="password")
self.assertTrue(login, "Could not log in")
# Request a page that requires a login
response = self.client.get("/login_protected_method_view/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context["user"].username, "testclient")
def test_view_with_method_force_login(self):
"Request a page that is protected with a @login_required method"
# Get the page without logging in. Should result in 302.
response = self.client.get("/login_protected_method_view/")
self.assertRedirects(
response, "/accounts/login/?next=/login_protected_method_view/"
)
# Log in
self.client.force_login(self.u1)
# Request a page that requires a login
response = self.client.get("/login_protected_method_view/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context["user"].username, "testclient")
def test_view_with_login_and_custom_redirect(self):
"""
Request a page that is protected with
@login_required(redirect_field_name='redirect_to')
"""
# Get the page without logging in. Should result in 302.
response = self.client.get("/login_protected_view_custom_redirect/")
self.assertRedirects(
response,
"/accounts/login/?redirect_to=/login_protected_view_custom_redirect/",
)
# Log in
login = self.client.login(username="testclient", password="password")
self.assertTrue(login, "Could not log in")
# Request a page that requires a login
response = self.client.get("/login_protected_view_custom_redirect/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context["user"].username, "testclient")
def test_view_with_force_login_and_custom_redirect(self):
"""
Request a page that is protected with
@login_required(redirect_field_name='redirect_to')
"""
# Get the page without logging in. Should result in 302.
response = self.client.get("/login_protected_view_custom_redirect/")
self.assertRedirects(
response,
"/accounts/login/?redirect_to=/login_protected_view_custom_redirect/",
)
# Log in
self.client.force_login(self.u1)
# Request a page that requires a login
response = self.client.get("/login_protected_view_custom_redirect/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context["user"].username, "testclient")
def test_view_with_bad_login(self):
"Request a page that is protected with @login, but use bad credentials"
login = self.client.login(username="otheruser", password="nopassword")
self.assertFalse(login)
def test_view_with_inactive_login(self):
"""
An inactive user may login if the authenticate backend allows it.
"""
credentials = {"username": "inactive", "password": "password"}
self.assertFalse(self.client.login(**credentials))
with self.settings(
AUTHENTICATION_BACKENDS=[
"django.contrib.auth.backends.AllowAllUsersModelBackend"
]
):
self.assertTrue(self.client.login(**credentials))
@override_settings(
AUTHENTICATION_BACKENDS=[
"django.contrib.auth.backends.ModelBackend",
"django.contrib.auth.backends.AllowAllUsersModelBackend",
]
)
def test_view_with_inactive_force_login(self):
"""
Request a page that is protected with @login, but use an inactive login
"""
# Get the page without logging in. Should result in 302.
response = self.client.get("/login_protected_view/")
self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/")
# Log in
self.client.force_login(
self.u2, backend="django.contrib.auth.backends.AllowAllUsersModelBackend"
)
# Request a page that requires a login
response = self.client.get("/login_protected_view/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context["user"].username, "inactive")
def test_logout(self):
"Request a logout after logging in"
# Log in
self.client.login(username="testclient", password="password")
# Request a page that requires a login
response = self.client.get("/login_protected_view/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context["user"].username, "testclient")
# Log out
self.client.logout()
# Request a page that requires a login
response = self.client.get("/login_protected_view/")
self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/")
def test_logout_with_force_login(self):
"Request a logout after logging in"
# Log in
self.client.force_login(self.u1)
# Request a page that requires a login
response = self.client.get("/login_protected_view/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context["user"].username, "testclient")
# Log out
self.client.logout()
# Request a page that requires a login
response = self.client.get("/login_protected_view/")
self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/")
@override_settings(
AUTHENTICATION_BACKENDS=[
"django.contrib.auth.backends.ModelBackend",
"test_client.auth_backends.TestClientBackend",
],
)
def test_force_login_with_backend(self):
"""
Request a page that is protected with @login_required when using
force_login() and passing a backend.
"""
# Get the page without logging in. Should result in 302.
response = self.client.get("/login_protected_view/")
self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/")
# Log in
self.client.force_login(
self.u1, backend="test_client.auth_backends.TestClientBackend"
)
self.assertEqual(self.u1.backend, "test_client.auth_backends.TestClientBackend")
# Request a page that requires a login
response = self.client.get("/login_protected_view/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context["user"].username, "testclient")
@override_settings(
AUTHENTICATION_BACKENDS=[
"django.contrib.auth.backends.ModelBackend",
"test_client.auth_backends.TestClientBackend",
],
)
def test_force_login_without_backend(self):
"""
force_login() without passing a backend and with multiple backends
configured should automatically use the first backend.
"""
self.client.force_login(self.u1)
response = self.client.get("/login_protected_view/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context["user"].username, "testclient")
self.assertEqual(self.u1.backend, "django.contrib.auth.backends.ModelBackend")
@override_settings(
AUTHENTICATION_BACKENDS=[
"test_client.auth_backends.BackendWithoutGetUserMethod",
"django.contrib.auth.backends.ModelBackend",
]
)
def test_force_login_with_backend_missing_get_user(self):
"""
force_login() skips auth backends without a get_user() method.
"""
self.client.force_login(self.u1)
self.assertEqual(self.u1.backend, "django.contrib.auth.backends.ModelBackend")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | true |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_client/urls_middleware_urlconf.py | tests/test_client/urls_middleware_urlconf.py | from django.http import HttpResponse
from django.urls import path
def empty_response(request):
return HttpResponse()
urlpatterns = [
path("middleware_urlconf_view/", empty_response, name="middleware_urlconf_view"),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_client/urls.py | tests/test_client/urls.py | from django.contrib.auth import views as auth_views
from django.urls import path
from django.views.generic import RedirectView
from . import views
urlpatterns = [
path("upload_view/", views.upload_view, name="upload_view"),
path("get_view/", views.get_view, name="get_view"),
path("cbv_view/", views.CBView.as_view()),
path("post_view/", views.post_view),
path("post_then_get_view/", views.post_then_get_view),
path("put_view/", views.put_view),
path("trace_view/", views.trace_view),
path("header_view/", views.view_with_header),
path("raw_post_view/", views.raw_post_view),
path("redirect_view/", views.redirect_view),
path("redirect_view_307/", views.method_saving_307_redirect_view),
path(
"redirect_view_307_query_string/",
views.method_saving_307_redirect_query_string_view,
),
path("redirect_view_308/", views.method_saving_308_redirect_view),
path(
"redirect_view_308_query_string/",
views.method_saving_308_redirect_query_string_view,
),
path(
"redirect_to_different_hostname/",
views.redirect_to_different_hostname,
name="redirect_to_different_hostname",
),
path("get_host_view/", views.get_host_view, name="get_host_view"),
path("secure_view/", views.view_with_secure),
path(
"permanent_redirect_view/",
RedirectView.as_view(url="/get_view/", permanent=True),
),
path(
"temporary_redirect_view/",
RedirectView.as_view(url="/get_view/", permanent=False),
),
path("http_redirect_view/", RedirectView.as_view(url="/secure_view/")),
path(
"https_redirect_view/",
RedirectView.as_view(url="https://testserver/secure_view/"),
),
path("double_redirect_view/", views.double_redirect_view),
path("bad_view/", views.bad_view),
path("form_view/", views.form_view),
path("form_view_with_template/", views.form_view_with_template),
path("json_view/", views.json_view),
path("login_protected_view/", views.login_protected_view),
path("login_protected_method_view/", views.login_protected_method_view),
path(
"login_protected_view_custom_redirect/",
views.login_protected_view_changed_redirect,
),
path("permission_protected_view/", views.permission_protected_view),
path(
"permission_protected_view_exception/",
views.permission_protected_view_exception,
),
path("permission_protected_method_view/", views.permission_protected_method_view),
path("session_view/", views.session_view),
path("broken_view/", views.broken_view),
path("mail_sending_view/", views.mail_sending_view),
path("mass_mail_sending_view/", views.mass_mail_sending_view),
path("nesting_exception_view/", views.nesting_exception_view),
path("django_project_redirect/", views.django_project_redirect),
path(
"no_trailing_slash_external_redirect/",
views.no_trailing_slash_external_redirect,
),
path(
"", views.index_view, name="index"
), # Target for no_trailing_slash_external_redirect/ with follow=True
path("two_arg_exception/", views.two_arg_exception),
path("accounts/", RedirectView.as_view(url="login/")),
path("accounts/no_trailing_slash", RedirectView.as_view(url="login/")),
path("accounts/login/", auth_views.LoginView.as_view(template_name="login.html")),
path("accounts/logout/", auth_views.LogoutView.as_view()),
# Async views.
path("async_get_view/", views.async_get_view, name="async_get_view"),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/absolute_url_overrides/__init__.py | tests/absolute_url_overrides/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/absolute_url_overrides/tests.py | tests/absolute_url_overrides/tests.py | from django.db import models
from django.test import SimpleTestCase
from django.test.utils import isolate_apps
@isolate_apps("absolute_url_overrides")
class AbsoluteUrlOverrideTests(SimpleTestCase):
def test_get_absolute_url(self):
"""
get_absolute_url() functions as a normal method.
"""
def get_absolute_url(o):
return "/test-a/%s/" % o.pk
TestA = self._create_model_class("TestA", get_absolute_url)
self.assertTrue(hasattr(TestA, "get_absolute_url"))
obj = TestA(pk=1, name="Foo")
self.assertEqual("/test-a/%s/" % obj.pk, obj.get_absolute_url())
def test_override_get_absolute_url(self):
"""
ABSOLUTE_URL_OVERRIDES should override get_absolute_url().
"""
def get_absolute_url(o):
return "/test-b/%s/" % o.pk
with self.settings(
ABSOLUTE_URL_OVERRIDES={
"absolute_url_overrides.testb": lambda o: "/overridden-test-b/%s/"
% o.pk,
},
):
TestB = self._create_model_class("TestB", get_absolute_url)
obj = TestB(pk=1, name="Foo")
self.assertEqual("/overridden-test-b/%s/" % obj.pk, obj.get_absolute_url())
def test_insert_get_absolute_url(self):
"""
ABSOLUTE_URL_OVERRIDES should work even if the model doesn't have a
get_absolute_url() method.
"""
with self.settings(
ABSOLUTE_URL_OVERRIDES={
"absolute_url_overrides.testc": lambda o: "/test-c/%s/" % o.pk,
},
):
TestC = self._create_model_class("TestC")
obj = TestC(pk=1, name="Foo")
self.assertEqual("/test-c/%s/" % obj.pk, obj.get_absolute_url())
def _create_model_class(self, class_name, get_absolute_url_method=None):
attrs = {
"name": models.CharField(max_length=50),
"__module__": "absolute_url_overrides",
}
if get_absolute_url_method:
attrs["get_absolute_url"] = get_absolute_url_method
return type(class_name, (models.Model,), attrs)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/test_extraction.py | tests/i18n/test_extraction.py | import os
import re
import shutil
import tempfile
import time
import warnings
from io import StringIO
from pathlib import Path
from unittest import mock, skipUnless
from admin_scripts.tests import AdminScriptTestCase
from django.core import management
from django.core.management import execute_from_command_line
from django.core.management.base import CommandError
from django.core.management.commands.makemessages import Command as MakeMessagesCommand
from django.core.management.commands.makemessages import (
TranslatableFile,
write_pot_file,
)
from django.core.management.utils import find_command
from django.test import SimpleTestCase, override_settings
from django.test.utils import captured_stderr, captured_stdout
from django.utils._os import symlinks_supported
from django.utils.translation import TranslatorCommentWarning
from .utils import POFileAssertionMixin, RunInTmpDirMixin, copytree
LOCALE = "de"
has_xgettext = find_command("xgettext")
@skipUnless(has_xgettext, "xgettext is mandatory for extraction tests")
class ExtractorTests(POFileAssertionMixin, RunInTmpDirMixin, SimpleTestCase):
work_subdir = "commands"
PO_FILE = "locale/%s/LC_MESSAGES/django.po" % LOCALE
def _run_makemessages(self, **options):
out = StringIO()
management.call_command(
"makemessages", locale=[LOCALE], verbosity=2, stdout=out, **options
)
output = out.getvalue()
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
return output, po_contents
def assertMsgIdPlural(self, msgid, haystack, 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.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":
# #: .\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]
if isinstance(line_number, str):
line_number = self._get_token_line_number(path, line_number)
if line_number is not None:
parts.append(":%d" % line_number)
needle = "".join(parts)
pattern = re.compile(r"^\#\:.*" + re.escape(needle), re.MULTILINE)
if assert_presence:
return self.assertRegex(
po_contents, pattern, '"%s" not found in final .po file.' % needle
)
else:
return self.assertNotRegex(
po_contents, pattern, '"%s" shouldn\'t be in final .po file.' % needle
)
def _get_token_line_number(self, path, token):
with open(path) as f:
for line, content in enumerate(f, 1):
if token in content:
return line
self.fail(
"The token '%s' could not be found in %s, please check the test config"
% (token, path)
)
def assertLocationCommentPresent(self, po_filename, line_number, *comment_parts):
r"""
self.assertLocationCommentPresent('django.po', 42, 'dirA', 'dirB',
'foo.py')
verifies that the django.po file has a gettext-style location comment
of the form
`#: dirA/dirB/foo.py:42`
(or `#: .\dirA\dirB\foo.py:42` on Windows)
None can be passed for the line_number argument to skip checking of
the :42 suffix part.
A string token can also be passed as line_number, in which case it
will be searched in the template, and its line number will be used.
A msgid is a suitable candidate.
"""
return self._assertPoLocComment(True, po_filename, line_number, *comment_parts)
def assertLocationCommentNotPresent(self, po_filename, line_number, *comment_parts):
"""Check the opposite of assertLocationComment()"""
return self._assertPoLocComment(False, po_filename, line_number, *comment_parts)
def assertRecentlyModified(self, path):
"""
Assert that file was recently modified (modification time was less than
10 seconds ago).
"""
delta = time.time() - os.stat(path).st_mtime
self.assertLess(delta, 10, "%s was recently modified" % path)
def assertNotRecentlyModified(self, path):
"""
Assert that file was not recently modified (modification time was more
than 10 seconds ago).
"""
delta = time.time() - os.stat(path).st_mtime
self.assertGreater(delta, 10, "%s wasn't recently modified" % path)
class BasicExtractorTests(ExtractorTests):
@override_settings(USE_I18N=False)
def test_use_i18n_false(self):
"""
makemessages also runs successfully when USE_I18N is False.
"""
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE, encoding="utf-8") as fp:
po_contents = fp.read()
# Check two random strings
self.assertIn("#. Translators: One-line translator comment #1", po_contents)
self.assertIn('msgctxt "Special trans context #1"', po_contents)
def test_no_option(self):
# One of either the --locale, --exclude, or --all options is required.
msg = "Type 'manage.py help makemessages' for usage information."
with mock.patch(
"django.core.management.commands.makemessages.sys.argv",
["manage.py", "makemessages"],
):
with self.assertRaisesRegex(CommandError, msg):
management.call_command("makemessages")
def test_valid_locale(self):
out = StringIO()
management.call_command("makemessages", locale=["de"], stdout=out, verbosity=1)
self.assertNotIn("invalid locale de", out.getvalue())
self.assertIn("processing locale de", out.getvalue())
self.assertIs(Path(self.PO_FILE).exists(), True)
def test_valid_locale_with_country(self):
out = StringIO()
management.call_command(
"makemessages", locale=["en_GB"], stdout=out, verbosity=1
)
self.assertNotIn("invalid locale en_GB", out.getvalue())
self.assertIn("processing locale en_GB", out.getvalue())
self.assertIs(Path("locale/en_GB/LC_MESSAGES/django.po").exists(), True)
def test_valid_locale_with_numeric_region_code(self):
out = StringIO()
management.call_command(
"makemessages", locale=["ar_002"], stdout=out, verbosity=1
)
self.assertNotIn("invalid locale ar_002", out.getvalue())
self.assertIn("processing locale ar_002", out.getvalue())
self.assertIs(Path("locale/ar_002/LC_MESSAGES/django.po").exists(), True)
def test_valid_locale_tachelhit_latin_morocco(self):
out = StringIO()
management.call_command(
"makemessages", locale=["shi_Latn_MA"], stdout=out, verbosity=1
)
self.assertNotIn("invalid locale shi_Latn_MA", out.getvalue())
self.assertIn("processing locale shi_Latn_MA", out.getvalue())
self.assertIs(Path("locale/shi_Latn_MA/LC_MESSAGES/django.po").exists(), True)
def test_valid_locale_private_subtag(self):
out = StringIO()
management.call_command(
"makemessages", locale=["nl_NL-x-informal"], stdout=out, verbosity=1
)
self.assertNotIn("invalid locale nl_NL-x-informal", out.getvalue())
self.assertIn("processing locale nl_NL-x-informal", out.getvalue())
self.assertIs(
Path("locale/nl_NL-x-informal/LC_MESSAGES/django.po").exists(), True
)
def test_invalid_locale_uppercase(self):
out = StringIO()
management.call_command("makemessages", locale=["PL"], stdout=out, verbosity=1)
self.assertIn("invalid locale PL, did you mean pl?", out.getvalue())
self.assertNotIn("processing locale pl", out.getvalue())
self.assertIs(Path("locale/pl/LC_MESSAGES/django.po").exists(), False)
def test_invalid_locale_hyphen(self):
out = StringIO()
management.call_command(
"makemessages", locale=["pl-PL"], stdout=out, verbosity=1
)
self.assertIn("invalid locale pl-PL, did you mean pl_PL?", out.getvalue())
self.assertNotIn("processing locale pl-PL", out.getvalue())
self.assertIs(Path("locale/pl-PL/LC_MESSAGES/django.po").exists(), False)
def test_invalid_locale_lower_country(self):
out = StringIO()
management.call_command(
"makemessages", locale=["pl_pl"], stdout=out, verbosity=1
)
self.assertIn("invalid locale pl_pl, did you mean pl_PL?", out.getvalue())
self.assertNotIn("processing locale pl_pl", out.getvalue())
self.assertIs(Path("locale/pl_pl/LC_MESSAGES/django.po").exists(), False)
def test_invalid_locale_private_subtag(self):
out = StringIO()
management.call_command(
"makemessages", locale=["nl-nl-x-informal"], stdout=out, verbosity=1
)
self.assertIn(
"invalid locale nl-nl-x-informal, did you mean nl_NL-x-informal?",
out.getvalue(),
)
self.assertNotIn("processing locale nl-nl-x-informal", out.getvalue())
self.assertIs(
Path("locale/nl-nl-x-informal/LC_MESSAGES/django.po").exists(), False
)
def test_invalid_locale_plus(self):
out = StringIO()
management.call_command(
"makemessages", locale=["en+GB"], stdout=out, verbosity=1
)
self.assertIn("invalid locale en+GB, did you mean en_GB?", out.getvalue())
self.assertNotIn("processing locale en+GB", out.getvalue())
self.assertIs(Path("locale/en+GB/LC_MESSAGES/django.po").exists(), False)
def test_invalid_locale_end_with_underscore(self):
out = StringIO()
management.call_command("makemessages", locale=["en_"], stdout=out, verbosity=1)
self.assertIn("invalid locale en_", out.getvalue())
self.assertNotIn("processing locale en_", out.getvalue())
self.assertIs(Path("locale/en_/LC_MESSAGES/django.po").exists(), False)
def test_invalid_locale_start_with_underscore(self):
out = StringIO()
management.call_command("makemessages", locale=["_en"], stdout=out, verbosity=1)
self.assertIn("invalid locale _en", out.getvalue())
self.assertNotIn("processing locale _en", out.getvalue())
self.assertIs(Path("locale/_en/LC_MESSAGES/django.po").exists(), False)
def test_comments_extractor(self):
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE, encoding="utf-8") as fp:
po_contents = fp.read()
self.assertNotIn("This comment should not be extracted", po_contents)
# Comments in templates
self.assertIn(
"#. Translators: This comment should be extracted", po_contents
)
self.assertIn(
"#. Translators: Django comment block for translators\n#. "
"string's meaning unveiled",
po_contents,
)
self.assertIn("#. Translators: One-line translator comment #1", po_contents)
self.assertIn(
"#. Translators: Two-line translator comment #1\n#. continued here.",
po_contents,
)
self.assertIn("#. Translators: One-line translator comment #2", po_contents)
self.assertIn(
"#. Translators: Two-line translator comment #2\n#. continued here.",
po_contents,
)
self.assertIn("#. Translators: One-line translator comment #3", po_contents)
self.assertIn(
"#. Translators: Two-line translator comment #3\n#. continued here.",
po_contents,
)
self.assertIn("#. Translators: One-line translator comment #4", po_contents)
self.assertIn(
"#. Translators: Two-line translator comment #4\n#. continued here.",
po_contents,
)
self.assertIn(
"#. Translators: One-line translator comment #5 -- with "
"non ASCII characters: áéíóúö",
po_contents,
)
self.assertIn(
"#. Translators: Two-line translator comment #5 -- with "
"non ASCII characters: áéíóúö\n#. continued here.",
po_contents,
)
def test_special_char_extracted(self):
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE, encoding="utf-8") as fp:
po_contents = fp.read()
self.assertMsgId("Non-breaking space\u00a0:", po_contents)
def test_blocktranslate_trimmed(self):
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
# should not be trimmed
self.assertNotMsgId("Text with a few line breaks.", po_contents)
# should be trimmed
self.assertMsgId(
"Again some text with a few line breaks, this time should be trimmed.",
po_contents,
)
# #21406 -- Should adjust for eaten line numbers
self.assertMsgId("Get my line number", po_contents)
self.assertLocationCommentPresent(
self.PO_FILE, "Get my line number", "templates", "test.html"
)
def test_extraction_error(self):
msg = (
"Translation blocks must not include other block tags: blocktranslate "
"(file %s, line 3)" % os.path.join("templates", "template_with_error.tpl")
)
with self.assertRaisesMessage(SyntaxError, msg):
management.call_command(
"makemessages", locale=[LOCALE], extensions=["tpl"], verbosity=0
)
# The temporary files were cleaned up.
self.assertFalse(os.path.exists("./templates/template_with_error.tpl.py"))
self.assertFalse(os.path.exists("./templates/template_0_with_no_error.tpl.py"))
def test_unicode_decode_error(self):
shutil.copyfile("./not_utf8.sample", "./not_utf8.txt")
out = StringIO()
management.call_command("makemessages", locale=[LOCALE], stdout=out)
self.assertIn(
"UnicodeDecodeError: skipped file not_utf8.txt in .", out.getvalue()
)
def test_unicode_file_name(self):
open(os.path.join(self.test_dir, "vidéo.txt"), "a").close()
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
def test_extraction_warning(self):
"""
test xgettext warning about multiple bare interpolation placeholders
"""
shutil.copyfile("./code.sample", "./code_sample.py")
out = StringIO()
management.call_command("makemessages", locale=[LOCALE], stdout=out)
self.assertIn("code_sample.py:4", out.getvalue())
def test_template_message_context_extractor(self):
"""
Message contexts are correctly extracted for the {% translate %} and
{% blocktranslate %} template tags (#14806).
"""
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
# {% translate %}
self.assertIn('msgctxt "Special trans context #1"', po_contents)
self.assertMsgId("Translatable literal #7a", po_contents)
self.assertIn('msgctxt "Special trans context #2"', po_contents)
self.assertMsgId("Translatable literal #7b", po_contents)
self.assertIn('msgctxt "Special trans context #3"', po_contents)
self.assertMsgId("Translatable literal #7c", po_contents)
# {% translate %} with a filter
for (
minor_part
) in "abcdefgh": # Iterate from #7.1a to #7.1h template markers
self.assertIn(
'msgctxt "context #7.1{}"'.format(minor_part), po_contents
)
self.assertMsgId(
"Translatable literal #7.1{}".format(minor_part), po_contents
)
# {% blocktranslate %}
self.assertIn('msgctxt "Special blocktranslate context #1"', po_contents)
self.assertMsgId("Translatable literal #8a", po_contents)
self.assertIn('msgctxt "Special blocktranslate context #2"', po_contents)
self.assertMsgId("Translatable literal #8b-singular", po_contents)
self.assertIn("Translatable literal #8b-plural", po_contents)
self.assertIn('msgctxt "Special blocktranslate context #3"', po_contents)
self.assertMsgId("Translatable literal #8c-singular", po_contents)
self.assertIn("Translatable literal #8c-plural", po_contents)
self.assertIn('msgctxt "Special blocktranslate context #4"', po_contents)
self.assertMsgId("Translatable literal #8d %(a)s", po_contents)
# {% trans %} and {% blocktrans %}
self.assertMsgId("trans text", po_contents)
self.assertMsgId("blocktrans text", po_contents)
def test_context_in_single_quotes(self):
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
# {% translate %}
self.assertIn('msgctxt "Context wrapped in double quotes"', po_contents)
self.assertIn('msgctxt "Context wrapped in single quotes"', po_contents)
# {% blocktranslate %}
self.assertIn(
'msgctxt "Special blocktranslate context wrapped in double quotes"',
po_contents,
)
self.assertIn(
'msgctxt "Special blocktranslate context wrapped in single quotes"',
po_contents,
)
def test_template_comments(self):
"""
Template comment tags on the same line of other constructs (#19552)
"""
# Test detection/end user reporting of old, incorrect templates
# translator comments syntax
with warnings.catch_warnings(record=True) as ws:
warnings.simplefilter("always")
management.call_command(
"makemessages", locale=[LOCALE], extensions=["thtml"], verbosity=0
)
self.assertEqual(len(ws), 3)
for w in ws:
self.assertTrue(issubclass(w.category, TranslatorCommentWarning))
self.assertRegex(
str(ws[0].message),
r"The translator-targeted comment 'Translators: ignored i18n "
r"comment #1' \(file templates[/\\]comments.thtml, line 4\) "
r"was ignored, because it wasn't the last item on the line\.",
)
self.assertRegex(
str(ws[1].message),
r"The translator-targeted comment 'Translators: ignored i18n "
r"comment #3' \(file templates[/\\]comments.thtml, line 6\) "
r"was ignored, because it wasn't the last item on the line\.",
)
self.assertRegex(
str(ws[2].message),
r"The translator-targeted comment 'Translators: ignored i18n "
r"comment #4' \(file templates[/\\]comments.thtml, line 8\) "
r"was ignored, because it wasn't the last item on the line\.",
)
# Now test .po file contents
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
self.assertMsgId("Translatable literal #9a", po_contents)
self.assertNotIn("ignored comment #1", po_contents)
self.assertNotIn("Translators: ignored i18n comment #1", po_contents)
self.assertMsgId("Translatable literal #9b", po_contents)
self.assertNotIn("ignored i18n comment #2", po_contents)
self.assertNotIn("ignored comment #2", po_contents)
self.assertMsgId("Translatable literal #9c", po_contents)
self.assertNotIn("ignored comment #3", po_contents)
self.assertNotIn("ignored i18n comment #3", po_contents)
self.assertMsgId("Translatable literal #9d", po_contents)
self.assertNotIn("ignored comment #4", po_contents)
self.assertMsgId("Translatable literal #9e", po_contents)
self.assertNotIn("ignored comment #5", po_contents)
self.assertNotIn("ignored i18n comment #4", po_contents)
self.assertMsgId("Translatable literal #9f", po_contents)
self.assertIn("#. Translators: valid i18n comment #5", po_contents)
self.assertMsgId("Translatable literal #9g", po_contents)
self.assertIn("#. Translators: valid i18n comment #6", po_contents)
self.assertMsgId("Translatable literal #9h", po_contents)
self.assertIn("#. Translators: valid i18n comment #7", po_contents)
self.assertMsgId("Translatable literal #9i", po_contents)
self.assertRegex(po_contents, r"#\..+Translators: valid i18n comment #8")
self.assertRegex(po_contents, r"#\..+Translators: valid i18n comment #9")
self.assertMsgId("Translatable literal #9j", po_contents)
def test_makemessages_find_files(self):
"""
find_files only discover files having the proper extensions.
"""
cmd = MakeMessagesCommand()
cmd.ignore_patterns = ["CVS", ".*", "*~", "*.pyc"]
cmd.symlinks = False
cmd.domain = "django"
cmd.extensions = [".html", ".txt", ".py"]
cmd.verbosity = 0
cmd.locale_paths = []
cmd.default_locale_path = os.path.join(self.test_dir, "locale")
found_files = cmd.find_files(self.test_dir)
self.assertGreater(len(found_files), 1)
found_exts = {os.path.splitext(tfile.file)[1] for tfile in found_files}
self.assertEqual(found_exts.difference({".py", ".html", ".txt"}), set())
cmd.extensions = [".js"]
cmd.domain = "djangojs"
found_files = cmd.find_files(self.test_dir)
self.assertGreater(len(found_files), 1)
found_exts = {os.path.splitext(tfile.file)[1] for tfile in found_files}
self.assertEqual(found_exts.difference({".js"}), set())
@mock.patch("django.core.management.commands.makemessages.popen_wrapper")
def test_makemessages_gettext_version(self, mocked_popen_wrapper):
# "Normal" output:
mocked_popen_wrapper.return_value = (
"xgettext (GNU gettext-tools) 0.18.1\n"
"Copyright (C) 1995-1998, 2000-2010 Free Software Foundation, Inc.\n"
"License GPLv3+: GNU GPL version 3 or later "
"<http://gnu.org/licenses/gpl.html>\n"
"This is free software: you are free to change and redistribute it.\n"
"There is NO WARRANTY, to the extent permitted by law.\n"
"Written by Ulrich Drepper.\n",
"",
0,
)
cmd = MakeMessagesCommand()
self.assertEqual(cmd.gettext_version, (0, 18, 1))
# Version number with only 2 parts (#23788)
mocked_popen_wrapper.return_value = (
"xgettext (GNU gettext-tools) 0.17\n",
"",
0,
)
cmd = MakeMessagesCommand()
self.assertEqual(cmd.gettext_version, (0, 17))
# Bad version output
mocked_popen_wrapper.return_value = ("any other return value\n", "", 0)
cmd = MakeMessagesCommand()
with self.assertRaisesMessage(
CommandError, "Unable to get gettext version. Is it installed?"
):
cmd.gettext_version
def test_po_file_encoding_when_updating(self):
"""
Update of PO file doesn't corrupt it with non-UTF-8 encoding on Windows
(#23271).
"""
BR_PO_BASE = "locale/pt_BR/LC_MESSAGES/django"
shutil.copyfile(BR_PO_BASE + ".pristine", BR_PO_BASE + ".po")
management.call_command("makemessages", locale=["pt_BR"], verbosity=0)
self.assertTrue(os.path.exists(BR_PO_BASE + ".po"))
with open(BR_PO_BASE + ".po", encoding="utf-8") as fp:
po_contents = fp.read()
self.assertMsgStr("Größe", po_contents)
def test_pot_charset_header_is_utf8(self):
"""Content-Type: ... charset=CHARSET is replaced with charset=UTF-8"""
msgs = (
"# SOME DESCRIPTIVE TITLE.\n"
"# (some lines truncated as they are not relevant)\n"
'"Content-Type: text/plain; charset=CHARSET\\n"\n'
'"Content-Transfer-Encoding: 8bit\\n"\n'
"\n"
"#: somefile.py:8\n"
'msgid "mañana; charset=CHARSET"\n'
'msgstr ""\n'
)
with tempfile.NamedTemporaryFile() as pot_file:
pot_filename = pot_file.name
write_pot_file(pot_filename, msgs)
with open(pot_filename, encoding="utf-8") as fp:
pot_contents = fp.read()
self.assertIn("Content-Type: text/plain; charset=UTF-8", pot_contents)
self.assertIn("mañana; charset=CHARSET", pot_contents)
def test_no_duplicate_locale_paths(self):
for locale_paths in [
[],
[os.path.join(self.test_dir, "locale")],
[Path(self.test_dir, "locale")],
]:
with self.subTest(locale_paths=locale_paths):
with override_settings(LOCALE_PATHS=locale_paths):
cmd = MakeMessagesCommand()
management.call_command(cmd, locale=["en", "ru"], verbosity=0)
self.assertTrue(
all(isinstance(path, str) for path in cmd.locale_paths)
)
self.assertEqual(len(cmd.locale_paths), len(set(cmd.locale_paths)))
def test_no_duplicate_write_po_file_calls(self):
with mock.patch.object(
MakeMessagesCommand, "write_po_file"
) as mock_write_po_file:
cmd = MakeMessagesCommand()
management.call_command(cmd, locale=["en", "ru"], verbosity=0)
self.assertEqual(
len(mock_write_po_file.call_args_list),
len({call.args for call in mock_write_po_file.call_args_list}),
)
def test_correct_translatable_file_locale_dir(self):
class ReturnTrackingMock(mock.Mock):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.call_return_value_list = []
def __call__(self, *args, **kwargs):
value = super().__call__(*args, **kwargs)
self.call_return_value_list.append(value)
return value
for locale_paths in [
[],
[
os.path.join(self.test_dir, "app_with_locale", "locale"),
],
[
os.path.join(self.test_dir, "locale"),
os.path.join(self.test_dir, "app_with_locale", "locale"),
],
]:
with self.subTest(locale_paths=locale_paths):
with override_settings(LOCALE_PATHS=locale_paths):
cmd = MakeMessagesCommand()
rtm = ReturnTrackingMock(wraps=cmd.find_files)
with mock.patch.object(cmd, "find_files", new=rtm):
management.call_command(cmd, locale=["en", "ru"], verbosity=0)
self.assertEqual(len(rtm.call_args_list), 1)
self.assertEqual(len(rtm.call_return_value_list), 1)
for tf in rtm.call_return_value_list[0]:
self.assertIsInstance(tf, TranslatableFile)
abs_file_path = os.path.abspath(
os.path.join(self.test_dir, tf.dirpath, tf.file)
)
max_common_path = max(
[
os.path.commonpath([abs_file_path, locale_path])
for locale_path in cmd.locale_paths
],
key=len,
)
correct_locale_dir = os.path.join(max_common_path, "locale")
self.assertEqual(tf.locale_dir, correct_locale_dir)
class JavaScriptExtractorTests(ExtractorTests):
PO_FILE = "locale/%s/LC_MESSAGES/djangojs.po" % LOCALE
def test_javascript_literals(self):
_, po_contents = self._run_makemessages(domain="djangojs")
self.assertMsgId("This literal should be included.", po_contents)
self.assertMsgId("gettext_noop should, too.", po_contents)
self.assertMsgId("This one as well.", po_contents)
self.assertMsgId(r"He said, \"hello\".", po_contents)
self.assertMsgId("okkkk", po_contents)
self.assertMsgId("TEXT", po_contents)
self.assertMsgId("It's at http://example.com", po_contents)
self.assertMsgId("String", po_contents)
self.assertMsgId(
"/* but this one will be too */ 'cause there is no way of telling...",
po_contents,
)
self.assertMsgId("foo", po_contents)
self.assertMsgId("bar", po_contents)
self.assertMsgId("baz", po_contents)
self.assertMsgId("quz", po_contents)
self.assertMsgId("foobar", po_contents)
def test_media_static_dirs_ignored(self):
"""
Regression test for #23583.
"""
with override_settings(
STATIC_ROOT=os.path.join(self.test_dir, "static/"),
MEDIA_ROOT=os.path.join(self.test_dir, "media_root/"),
):
_, po_contents = self._run_makemessages(domain="djangojs")
self.assertMsgId(
"Static content inside app should be included.", po_contents
)
self.assertNotMsgId(
"Content from STATIC_ROOT should not be included", po_contents
)
@override_settings(STATIC_ROOT=None, MEDIA_ROOT="")
def test_default_root_settings(self):
"""
Regression test for #23717.
"""
_, po_contents = self._run_makemessages(domain="djangojs")
self.assertMsgId("Static content inside app should be included.", po_contents)
def test_i18n_catalog_ignored_when_invoked_for_django(self):
# Create target file so it exists in the filesystem and can be ignored.
# "invoked_for_django" is True when "conf/locale" folder exists.
os.makedirs(os.path.join("conf", "locale"))
i18n_catalog_js_dir = os.path.join(os.path.curdir, "views", "templates")
os.makedirs(i18n_catalog_js_dir)
open(os.path.join(i18n_catalog_js_dir, "i18n_catalog.js"), "w").close()
out, _ = self._run_makemessages(domain="djangojs")
self.assertIn(f"ignoring file i18n_catalog.js in {i18n_catalog_js_dir}", out)
def test_i18n_catalog_not_ignored_when_not_invoked_for_django(self):
# Create target file so it exists in the filesystem but is NOT ignored.
# "invoked_for_django" is False when "conf/locale" folder does not
# exist.
self.assertIs(os.path.exists(os.path.join("conf", "locale")), False)
i18n_catalog_js = os.path.join("views", "templates", "i18n_catalog.js")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | true |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/models.py | tests/i18n/models.py | from datetime import datetime
from django.db import models
from django.utils.translation import gettext_lazy as _
class TestModel(models.Model):
text = models.CharField(max_length=10, default=_("Anything"))
class Company(models.Model):
name = models.CharField(max_length=50)
date_added = models.DateTimeField(default=datetime(1799, 1, 31, 23, 59, 59, 0))
cents_paid = models.DecimalField(max_digits=4, decimal_places=2)
products_delivered = models.IntegerField()
class Meta:
verbose_name = _("Company")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/urls_default_unprefixed.py | tests/i18n/urls_default_unprefixed.py | from django.conf.urls.i18n import i18n_patterns
from django.http import HttpResponse
from django.urls import path, re_path
from django.utils.translation import gettext_lazy as _
urlpatterns = i18n_patterns(
re_path(r"^(?P<arg>[\w-]+)-page", lambda request, **arg: HttpResponse(_("Yes"))),
path("simple/", lambda r: HttpResponse(_("Yes"))),
re_path(r"^(.+)/(.+)/$", lambda *args: HttpResponse()),
re_path(_(r"^users/$"), lambda *args: HttpResponse(), name="users"),
prefix_default_language=False,
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/test_management.py | tests/i18n/test_management.py | import 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 test_eq(self):
dirpath = "dir"
file_name = "example"
trans_file = TranslatableFile(
dirpath=dirpath, file_name=file_name, locale_dir=None
)
trans_file_eq = TranslatableFile(
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)
self.assertNotEqual(trans_file, trans_file_not_eq)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/utils.py | tests/i18n/utils.py | import os
import re
import shutil
import tempfile
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(
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, haystack, 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 created by tempfile.mkdtemp() that contains a
clean copy of the relevant test code.
Test classes using this mixin need to define a `work_subdir` attribute
which designates the subdir under `tests/i18n/` that will be copied to the
temporary tree from which its test cases will run.
The setUp() method sets the current working dir to the temporary tree.
It'll be removed when cleaning up.
"""
def setUp(self):
self._cwd = os.getcwd()
self.work_dir = tempfile.mkdtemp(prefix="i18n_")
# Resolve symlinks, if any, in test directory paths.
self.test_dir = os.path.realpath(os.path.join(self.work_dir, self.work_subdir))
copytree(os.path.join(source_code_dir, self.work_subdir), self.test_dir)
# Step out of the temporary working tree before removing it to avoid
# deletion problems on Windows. Cleanup actions registered with
# addCleanup() are called in reverse so preserve this ordering.
self.addCleanup(self._rmrf, self.test_dir)
self.addCleanup(os.chdir, self._cwd)
os.chdir(self.test_dir)
def _rmrf(self, dname):
if (
os.path.commonprefix([self.test_dir, os.path.abspath(dname)])
!= self.test_dir
):
return
shutil.rmtree(dname)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/test_compilation.py | tests/i18n/test_compilation.py | import gettext as gettext_module
import os
import re
import stat
import unittest
from io import StringIO
from pathlib import Path
from subprocess import run
from unittest import mock
from django.core.management import CommandError, call_command, execute_from_command_line
from django.core.management.utils import find_command, popen_wrapper
from django.test import SimpleTestCase, override_settings
from django.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 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()
with self.assertRaisesMessage(
CommandError, "compilemessages generated one or more errors."
):
call_command(
"compilemessages", locale=[self.LOCALE], verbosity=0, stderr=stderr
)
self.assertIn("file has a BOM (Byte Order Mark)", stderr.getvalue())
self.assertFalse(os.path.exists(self.MO_FILE))
def test_no_write_access(self):
mo_file_en = Path(self.MO_FILE_EN)
err_buffer = StringIO()
# Put parent directory in read-only mode.
old_mode = mo_file_en.parent.stat().st_mode
mo_file_en.parent.chmod(stat.S_IRUSR | stat.S_IXUSR)
# Ensure .po file is more recent than .mo file.
mo_file_en.with_suffix(".po").touch()
try:
with self.assertRaisesMessage(
CommandError, "compilemessages generated one or more errors."
):
call_command(
"compilemessages", locale=["en"], stderr=err_buffer, verbosity=0
)
self.assertIn("not writable location", err_buffer.getvalue())
finally:
mo_file_en.parent.chmod(old_mode)
def test_no_compile_when_unneeded(self):
mo_file_en = Path(self.MO_FILE_EN)
mo_file_en.touch()
stdout = StringIO()
call_command("compilemessages", locale=["en"], stdout=stdout, verbosity=1)
msg = "%s” is already compiled and up to date." % mo_file_en.with_suffix(".po")
self.assertIn(msg, stdout.getvalue())
class PoFileContentsTests(MessageCompilationTests):
# Ticket #11240
LOCALE = "fr"
MO_FILE = "locale/%s/LC_MESSAGES/django.mo" % LOCALE
def test_percent_symbol_in_po_file(self):
call_command("compilemessages", locale=[self.LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.MO_FILE))
class MultipleLocaleCompilationTests(MessageCompilationTests):
MO_FILE_HR = None
MO_FILE_FR = None
def setUp(self):
super().setUp()
localedir = os.path.join(self.test_dir, "locale")
self.MO_FILE_HR = os.path.join(localedir, "hr/LC_MESSAGES/django.mo")
self.MO_FILE_FR = os.path.join(localedir, "fr/LC_MESSAGES/django.mo")
def test_one_locale(self):
with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, "locale")]):
call_command("compilemessages", locale=["hr"], verbosity=0)
self.assertTrue(os.path.exists(self.MO_FILE_HR))
def test_multiple_locales(self):
with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, "locale")]):
call_command("compilemessages", locale=["hr", "fr"], verbosity=0)
self.assertTrue(os.path.exists(self.MO_FILE_HR))
self.assertTrue(os.path.exists(self.MO_FILE_FR))
class ExcludedLocaleCompilationTests(MessageCompilationTests):
work_subdir = "exclude"
MO_FILE = "locale/%s/LC_MESSAGES/django.mo"
def setUp(self):
super().setUp()
copytree("canned_locale", "locale")
def test_command_help(self):
with captured_stdout(), captured_stderr():
# `call_command` bypasses the parser; by calling
# `execute_from_command_line` with the help subcommand we
# ensure that there are no issues with the parser itself.
execute_from_command_line(["django-admin", "help", "compilemessages"])
def test_one_locale_excluded(self):
call_command("compilemessages", exclude=["it"], verbosity=0)
self.assertTrue(os.path.exists(self.MO_FILE % "en"))
self.assertTrue(os.path.exists(self.MO_FILE % "fr"))
self.assertFalse(os.path.exists(self.MO_FILE % "it"))
def test_multiple_locales_excluded(self):
call_command("compilemessages", exclude=["it", "fr"], verbosity=0)
self.assertTrue(os.path.exists(self.MO_FILE % "en"))
self.assertFalse(os.path.exists(self.MO_FILE % "fr"))
self.assertFalse(os.path.exists(self.MO_FILE % "it"))
def test_one_locale_excluded_with_locale(self):
call_command(
"compilemessages", locale=["en", "fr"], exclude=["fr"], verbosity=0
)
self.assertTrue(os.path.exists(self.MO_FILE % "en"))
self.assertFalse(os.path.exists(self.MO_FILE % "fr"))
self.assertFalse(os.path.exists(self.MO_FILE % "it"))
def test_multiple_locales_excluded_with_locale(self):
call_command(
"compilemessages",
locale=["en", "fr", "it"],
exclude=["fr", "it"],
verbosity=0,
)
self.assertTrue(os.path.exists(self.MO_FILE % "en"))
self.assertFalse(os.path.exists(self.MO_FILE % "fr"))
self.assertFalse(os.path.exists(self.MO_FILE % "it"))
class IgnoreDirectoryCompilationTests(MessageCompilationTests):
# Reuse the exclude directory since it contains some locale fixtures.
work_subdir = "exclude"
MO_FILE = "%s/%s/LC_MESSAGES/django.mo"
CACHE_DIR = Path("cache") / "locale"
NESTED_DIR = Path("outdated") / "v1" / "locale"
def setUp(self):
super().setUp()
copytree("canned_locale", "locale")
copytree("canned_locale", self.CACHE_DIR)
copytree("canned_locale", self.NESTED_DIR)
def assertAllExist(self, dir, langs):
self.assertTrue(
all(Path(self.MO_FILE % (dir, lang)).exists() for lang in langs)
)
def assertNoneExist(self, dir, langs):
self.assertTrue(
all(Path(self.MO_FILE % (dir, lang)).exists() is False for lang in langs)
)
def test_one_locale_dir_ignored(self):
call_command("compilemessages", ignore=["cache"], verbosity=0)
self.assertAllExist("locale", ["en", "fr", "it"])
self.assertNoneExist(self.CACHE_DIR, ["en", "fr", "it"])
self.assertAllExist(self.NESTED_DIR, ["en", "fr", "it"])
def test_multiple_locale_dirs_ignored(self):
call_command(
"compilemessages", ignore=["cache/locale", "outdated"], verbosity=0
)
self.assertAllExist("locale", ["en", "fr", "it"])
self.assertNoneExist(self.CACHE_DIR, ["en", "fr", "it"])
self.assertNoneExist(self.NESTED_DIR, ["en", "fr", "it"])
def test_ignores_based_on_pattern(self):
call_command("compilemessages", ignore=["*/locale"], verbosity=0)
self.assertAllExist("locale", ["en", "fr", "it"])
self.assertNoneExist(self.CACHE_DIR, ["en", "fr", "it"])
self.assertNoneExist(self.NESTED_DIR, ["en", "fr", "it"])
def test_no_dirs_accidentally_skipped(self):
os_walk_results = [
# To discover .po filepaths, compilemessages uses with a starting
# list of basedirs to inspect, which in this scenario are:
# ["conf/locale", "locale"]
# Then os.walk is used to discover other locale dirs, ignoring dirs
# matching `ignore_patterns`. Mock the results to place an ignored
# directory directly before and after a directory named "locale".
[("somedir", ["ignore", "locale", "ignore"], [])],
# This will result in three basedirs discovered:
# ["conf/locale", "locale", "somedir/locale"]
# os.walk is called for each locale in each basedir looking for .po
# files. In this scenario, we need to mock os.walk results for
# "en", "fr", and "it" locales for each basedir:
[("exclude/locale/LC_MESSAGES", [], ["en.po"])],
[("exclude/locale/LC_MESSAGES", [], ["fr.po"])],
[("exclude/locale/LC_MESSAGES", [], ["it.po"])],
[("exclude/conf/locale/LC_MESSAGES", [], ["en.po"])],
[("exclude/conf/locale/LC_MESSAGES", [], ["fr.po"])],
[("exclude/conf/locale/LC_MESSAGES", [], ["it.po"])],
[("exclude/somedir/locale/LC_MESSAGES", [], ["en.po"])],
[("exclude/somedir/locale/LC_MESSAGES", [], ["fr.po"])],
[("exclude/somedir/locale/LC_MESSAGES", [], ["it.po"])],
]
module_path = "django.core.management.commands.compilemessages"
with mock.patch(f"{module_path}.os.walk", side_effect=os_walk_results):
with mock.patch(f"{module_path}.os.path.isdir", return_value=True):
with mock.patch(
f"{module_path}.Command.compile_messages"
) as mock_compile_messages:
call_command("compilemessages", ignore=["ignore"], verbosity=4)
expected = [
(
[
("exclude/locale/LC_MESSAGES", "en.po"),
("exclude/locale/LC_MESSAGES", "fr.po"),
("exclude/locale/LC_MESSAGES", "it.po"),
],
),
(
[
("exclude/conf/locale/LC_MESSAGES", "en.po"),
("exclude/conf/locale/LC_MESSAGES", "fr.po"),
("exclude/conf/locale/LC_MESSAGES", "it.po"),
],
),
(
[
("exclude/somedir/locale/LC_MESSAGES", "en.po"),
("exclude/somedir/locale/LC_MESSAGES", "fr.po"),
("exclude/somedir/locale/LC_MESSAGES", "it.po"),
],
),
]
self.assertEqual([c.args for c in mock_compile_messages.mock_calls], expected)
class CompilationErrorHandling(MessageCompilationTests):
@cached_property
def msgfmt_version(self):
# Note that msgfmt is installed via GNU gettext tools, hence the msgfmt
# version should align to gettext.
out, err, status = popen_wrapper(
["msgfmt", "--version"],
stdout_encoding=DEFAULT_LOCALE_ENCODING,
)
m = re.search(r"(\d+)\.(\d+)\.?(\d+)?", out)
return tuple(int(d) for d in m.groups() if d is not None)
def test_error_reported_by_msgfmt(self):
# po file contains wrong po formatting.
with self.assertRaises(CommandError):
call_command("compilemessages", locale=["ja"], verbosity=0)
# It should still fail a second time.
with self.assertRaises(CommandError):
call_command("compilemessages", locale=["ja"], verbosity=0)
def test_msgfmt_error_including_non_ascii(self):
# po file contains invalid msgstr content (triggers non-ascii error
# content). Make sure the output of msgfmt is unaffected by the current
# locale.
env = os.environ.copy()
env.update({"LC_ALL": "C"})
with mock.patch(
"django.core.management.utils.run",
lambda *args, **kwargs: run(*args, env=env, **kwargs),
):
stderr = StringIO()
with self.assertRaisesMessage(
CommandError, "compilemessages generated one or more errors"
):
call_command(
"compilemessages", locale=["ko"], stdout=StringIO(), stderr=stderr
)
if self.msgfmt_version < (0, 25):
error_msg = "' cannot start a field name"
else:
error_msg = (
"a field name starts with a character that is not alphanumerical "
"or underscore"
)
self.assertIn(error_msg, stderr.getvalue())
class ProjectAndAppTests(MessageCompilationTests):
LOCALE = "ru"
PROJECT_MO_FILE = "locale/%s/LC_MESSAGES/django.mo" % LOCALE
APP_MO_FILE = "app_with_locale/locale/%s/LC_MESSAGES/django.mo" % LOCALE
class FuzzyTranslationTest(ProjectAndAppTests):
def setUp(self):
super().setUp()
gettext_module._translations = {} # flush cache or test will be useless
def test_nofuzzy_compiling(self):
with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, "locale")]):
call_command("compilemessages", locale=[self.LOCALE], verbosity=0)
with translation.override(self.LOCALE):
self.assertEqual(gettext("Lenin"), "Ленин")
self.assertEqual(gettext("Vodka"), "Vodka")
def test_fuzzy_compiling(self):
with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, "locale")]):
call_command(
"compilemessages", locale=[self.LOCALE], fuzzy=True, verbosity=0
)
with translation.override(self.LOCALE):
self.assertEqual(gettext("Lenin"), "Ленин")
self.assertEqual(gettext("Vodka"), "Водка")
class AppCompilationTest(ProjectAndAppTests):
def test_app_locale_compiled(self):
call_command("compilemessages", locale=[self.LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PROJECT_MO_FILE))
self.assertTrue(os.path.exists(self.APP_MO_FILE))
class PathLibLocaleCompilationTests(MessageCompilationTests):
work_subdir = "exclude"
def test_locale_paths_pathlib(self):
with override_settings(LOCALE_PATHS=[Path(self.test_dir) / "canned_locale"]):
call_command("compilemessages", locale=["fr"], verbosity=0)
self.assertTrue(os.path.exists("canned_locale/fr/LC_MESSAGES/django.mo"))
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/__init__.py | tests/i18n/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/tests.py | tests/i18n/tests.py | import datetime
import decimal
import gettext as gettext_module
import os
import pickle
import re
import tempfile
from contextlib import contextmanager
from importlib import import_module
from pathlib import Path
from unittest import mock, skipUnless
from asgiref.local import Local
from django import forms
from django.apps import AppConfig
from django.conf import settings
from django.conf.locale import LANG_INFO
from django.conf.urls.i18n import i18n_patterns
from django.core.management.utils import find_command, popen_wrapper
from django.template import Context, Template
from django.test import RequestFactory, SimpleTestCase, TestCase, override_settings
from django.utils import translation
from django.utils.formats import (
date_format,
get_format,
iter_format_modules,
localize,
localize_input,
reset_format_cache,
sanitize_separators,
sanitize_strftime_format,
time_format,
)
from django.utils.numberformat import format as nformat
from django.utils.safestring import SafeString, mark_safe
from django.utils.translation import (
activate,
check_for_language,
deactivate,
get_language,
get_language_bidi,
get_language_from_request,
get_language_info,
gettext,
gettext_lazy,
ngettext,
ngettext_lazy,
npgettext,
npgettext_lazy,
pgettext,
round_away_from_one,
to_language,
to_locale,
trans_null,
trans_real,
)
from django.utils.translation.reloader import (
translation_file_changed,
watch_for_translation_changes,
)
from django.utils.translation.trans_real import LANGUAGE_CODE_MAX_LENGTH
from .forms import CompanyForm, I18nForm, SelectDateForm
from .models import Company, TestModel
here = os.path.dirname(os.path.abspath(__file__))
extended_locale_paths = settings.LOCALE_PATHS + [
os.path.join(here, "other", "locale"),
]
class AppModuleStub:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
@contextmanager
def patch_formats(lang, **settings):
from django.utils.formats import _format_cache
# Populate _format_cache with temporary values
for key, value in settings.items():
_format_cache[(key, lang)] = value
try:
yield
finally:
reset_format_cache()
class TranslationTests(SimpleTestCase):
@translation.override("fr")
def test_plural(self):
"""
Test plurals with ngettext. French differs from English in that 0 is
singular.
"""
self.assertEqual(
ngettext("%(num)d year", "%(num)d years", 0) % {"num": 0},
"0 année",
)
self.assertEqual(
ngettext("%(num)d year", "%(num)d years", 2) % {"num": 2},
"2 ans",
)
self.assertEqual(
ngettext("%(size)d byte", "%(size)d bytes", 0) % {"size": 0}, "0 octet"
)
self.assertEqual(
ngettext("%(size)d byte", "%(size)d bytes", 2) % {"size": 2}, "2 octets"
)
def test_plural_null(self):
g = trans_null.ngettext
self.assertEqual(g("%(num)d year", "%(num)d years", 0) % {"num": 0}, "0 years")
self.assertEqual(g("%(num)d year", "%(num)d years", 1) % {"num": 1}, "1 year")
self.assertEqual(g("%(num)d year", "%(num)d years", 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 singular", "%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 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 mandatory for this test")
def test_multiple_plurals_merge(self):
def _create_translation_from_string(content):
with tempfile.TemporaryDirectory() as dirname:
po_path = Path(dirname).joinpath("fr", "LC_MESSAGES", "django.po")
po_path.parent.mkdir(parents=True)
po_path.write_text(content)
errors = popen_wrapper(
["msgfmt", "-o", po_path.with_suffix(".mo"), po_path]
)[1]
if errors:
self.fail(f"msgfmt compilation error: {errors}")
return gettext_module.translation(
domain="django",
localedir=dirname,
languages=["fr"],
)
french = trans_real.catalog()
# Merge a new translation file with different plural forms.
catalog1 = _create_translation_from_string(
'msgid ""\n'
'msgstr ""\n'
'"Content-Type: text/plain; charset=UTF-8\\n"\n'
'"Plural-Forms: nplurals=3; plural=(n==1 ? 0 : n==0 ? 1 : 2);\\n"\n'
'msgid "I win"\n'
'msgstr "Je perds"\n'
)
french.merge(catalog1)
# Merge a second translation file with plural forms from django.conf.
catalog2 = _create_translation_from_string(
'msgid ""\n'
'msgstr ""\n'
'"Content-Type: text/plain; charset=UTF-8\\n"\n'
'"Plural-Forms: Plural-Forms: nplurals=2; plural=(n > 1);\\n"\n'
'msgid "I win"\n'
'msgstr "Je gagne"\n'
)
french.merge(catalog2)
# Translations from this last one are supposed to win.
self.assertEqual(french.gettext("I win"), "Je gagne")
def test_override(self):
activate("de")
try:
with translation.override("pl"):
self.assertEqual(get_language(), "pl")
self.assertEqual(get_language(), "de")
with translation.override(None):
self.assertIsNone(get_language())
with translation.override("pl"):
pass
self.assertIsNone(get_language())
self.assertEqual(get_language(), "de")
finally:
deactivate()
def test_override_decorator(self):
@translation.override("pl")
def func_pl():
self.assertEqual(get_language(), "pl")
@translation.override(None)
def func_none():
self.assertIsNone(get_language())
try:
activate("de")
func_pl()
self.assertEqual(get_language(), "de")
func_none()
self.assertEqual(get_language(), "de")
finally:
deactivate()
def test_override_exit(self):
"""
The language restored is the one used when the function was
called, not the one used when the decorator was initialized (#23381).
"""
activate("fr")
@translation.override("pl")
def func_pl():
pass
deactivate()
try:
activate("en")
func_pl()
self.assertEqual(get_language(), "en")
finally:
deactivate()
def test_lazy_objects(self):
"""
Format string interpolation should work with *_lazy objects.
"""
s = gettext_lazy("Add %(name)s")
d = {"name": "Ringo"}
self.assertEqual("Add Ringo", s % d)
with translation.override("de", deactivate=True):
self.assertEqual("Ringo hinzuf\xfcgen", s % d)
with translation.override("pl"):
self.assertEqual("Dodaj Ringo", s % d)
# It should be possible to compare *_lazy objects.
s1 = gettext_lazy("Add %(name)s")
self.assertEqual(s, s1)
s2 = gettext_lazy("Add %(name)s")
s3 = gettext_lazy("Add %(name)s")
self.assertEqual(s2, s3)
self.assertEqual(s, s2)
s4 = gettext_lazy("Some other string")
self.assertNotEqual(s, s4)
def test_lazy_pickle(self):
s1 = gettext_lazy("test")
self.assertEqual(str(s1), "test")
s2 = pickle.loads(pickle.dumps(s1))
self.assertEqual(str(s2), "test")
@override_settings(LOCALE_PATHS=extended_locale_paths)
def test_ngettext_lazy(self):
simple_with_format = ngettext_lazy("%d good result", "%d good results")
simple_context_with_format = npgettext_lazy(
"Exclamation", "%d good result", "%d good results"
)
simple_without_format = ngettext_lazy("good result", "good results")
with translation.override("de"):
self.assertEqual(simple_with_format % 1, "1 gutes Resultat")
self.assertEqual(simple_with_format % 4, "4 guten Resultate")
self.assertEqual(simple_context_with_format % 1, "1 gutes Resultat!")
self.assertEqual(simple_context_with_format % 4, "4 guten Resultate!")
self.assertEqual(simple_without_format % 1, "gutes Resultat")
self.assertEqual(simple_without_format % 4, "guten Resultate")
complex_nonlazy = ngettext_lazy(
"Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", 4
)
complex_deferred = ngettext_lazy(
"Hi %(name)s, %(num)d good result",
"Hi %(name)s, %(num)d good results",
"num",
)
complex_context_nonlazy = npgettext_lazy(
"Greeting",
"Hi %(name)s, %(num)d good result",
"Hi %(name)s, %(num)d good results",
4,
)
complex_context_deferred = npgettext_lazy(
"Greeting",
"Hi %(name)s, %(num)d good result",
"Hi %(name)s, %(num)d good results",
"num",
)
with translation.override("de"):
self.assertEqual(
complex_nonlazy % {"num": 4, "name": "Jim"},
"Hallo Jim, 4 guten Resultate",
)
self.assertEqual(
complex_deferred % {"name": "Jim", "num": 1},
"Hallo Jim, 1 gutes Resultat",
)
self.assertEqual(
complex_deferred % {"name": "Jim", "num": 5},
"Hallo Jim, 5 guten Resultate",
)
with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"):
complex_deferred % {"name": "Jim"}
self.assertEqual(
complex_context_nonlazy % {"num": 4, "name": "Jim"},
"Willkommen Jim, 4 guten Resultate",
)
self.assertEqual(
complex_context_deferred % {"name": "Jim", "num": 1},
"Willkommen Jim, 1 gutes Resultat",
)
self.assertEqual(
complex_context_deferred % {"name": "Jim", "num": 5},
"Willkommen Jim, 5 guten Resultate",
)
with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"):
complex_context_deferred % {"name": "Jim"}
@override_settings(LOCALE_PATHS=extended_locale_paths)
def test_ngettext_lazy_format_style(self):
simple_with_format = ngettext_lazy("{} good result", "{} good results")
simple_context_with_format = npgettext_lazy(
"Exclamation", "{} good result", "{} good results"
)
with translation.override("de"):
self.assertEqual(simple_with_format.format(1), "1 gutes Resultat")
self.assertEqual(simple_with_format.format(4), "4 guten Resultate")
self.assertEqual(simple_context_with_format.format(1), "1 gutes Resultat!")
self.assertEqual(simple_context_with_format.format(4), "4 guten Resultate!")
complex_nonlazy = ngettext_lazy(
"Hi {name}, {num} good result", "Hi {name}, {num} good results", 4
)
complex_deferred = ngettext_lazy(
"Hi {name}, {num} good result", "Hi {name}, {num} good results", "num"
)
complex_context_nonlazy = npgettext_lazy(
"Greeting",
"Hi {name}, {num} good result",
"Hi {name}, {num} good results",
4,
)
complex_context_deferred = npgettext_lazy(
"Greeting",
"Hi {name}, {num} good result",
"Hi {name}, {num} good results",
"num",
)
with translation.override("de"):
self.assertEqual(
complex_nonlazy.format(num=4, name="Jim"),
"Hallo Jim, 4 guten Resultate",
)
self.assertEqual(
complex_deferred.format(name="Jim", num=1),
"Hallo Jim, 1 gutes Resultat",
)
self.assertEqual(
complex_deferred.format(name="Jim", num=5),
"Hallo Jim, 5 guten Resultate",
)
with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"):
complex_deferred.format(name="Jim")
self.assertEqual(
complex_context_nonlazy.format(num=4, name="Jim"),
"Willkommen Jim, 4 guten Resultate",
)
self.assertEqual(
complex_context_deferred.format(name="Jim", num=1),
"Willkommen Jim, 1 gutes Resultat",
)
self.assertEqual(
complex_context_deferred.format(name="Jim", num=5),
"Willkommen Jim, 5 guten Resultate",
)
with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"):
complex_context_deferred.format(name="Jim")
def test_ngettext_lazy_bool(self):
self.assertTrue(ngettext_lazy("%d good result", "%d good results"))
self.assertFalse(ngettext_lazy("", ""))
def test_ngettext_lazy_pickle(self):
s1 = ngettext_lazy("%d good result", "%d good results")
self.assertEqual(s1 % 1, "1 good result")
self.assertEqual(s1 % 8, "8 good results")
s2 = pickle.loads(pickle.dumps(s1))
self.assertEqual(s2 % 1, "1 good result")
self.assertEqual(s2 % 8, "8 good results")
@override_settings(LOCALE_PATHS=extended_locale_paths)
def test_pgettext(self):
trans_real._active = Local()
trans_real._translations = {}
with translation.override("de"):
self.assertEqual(pgettext("unexisting", "May"), "May")
self.assertEqual(pgettext("month name", "May"), "Mai")
self.assertEqual(pgettext("verb", "May"), "Kann")
self.assertEqual(
npgettext("search", "%d result", "%d results", 4) % 4, "4 Resultate"
)
def test_empty_value(self):
"""Empty value must stay empty after being translated (#23196)."""
with translation.override("de"):
self.assertEqual("", gettext(""))
s = mark_safe("")
self.assertEqual(s, gettext(s))
@override_settings(LOCALE_PATHS=extended_locale_paths)
def test_safe_status(self):
"""
Translating a string requiring no auto-escaping with gettext or
pgettext shouldn't change the "safe" status.
"""
trans_real._active = Local()
trans_real._translations = {}
s1 = mark_safe("Password")
s2 = mark_safe("May")
with translation.override("de", deactivate=True):
self.assertIs(type(gettext(s1)), SafeString)
self.assertIs(type(pgettext("month name", s2)), SafeString)
self.assertEqual("aPassword", SafeString("a") + s1)
self.assertEqual("Passworda", s1 + SafeString("a"))
self.assertEqual("Passworda", s1 + mark_safe("a"))
self.assertEqual("aPassword", mark_safe("a") + s1)
self.assertEqual("as", mark_safe("a") + mark_safe("s"))
def test_maclines(self):
"""
Translations on files with Mac or DOS end of lines will be converted
to unix EOF in .po catalogs.
"""
ca_translation = trans_real.translation("ca")
ca_translation._catalog["Mac\nEOF\n"] = "Catalan Mac\nEOF\n"
ca_translation._catalog["Win\nEOF\n"] = "Catalan Win\nEOF\n"
with translation.override("ca", deactivate=True):
self.assertEqual("Catalan Mac\nEOF\n", gettext("Mac\rEOF\r"))
self.assertEqual("Catalan Win\nEOF\n", gettext("Win\r\nEOF\r\n"))
def test_to_locale(self):
tests = (
("en", "en"),
("EN", "en"),
("en-us", "en_US"),
("EN-US", "en_US"),
("en_US", "en_US"),
# With > 2 characters after the dash.
("sr-latn", "sr_Latn"),
("sr-LATN", "sr_Latn"),
("sr_Latn", "sr_Latn"),
# 3-char language codes.
("ber-MA", "ber_MA"),
("BER-MA", "ber_MA"),
("BER_MA", "ber_MA"),
("ber_MA", "ber_MA"),
# With private use subtag (x-informal).
("nl-nl-x-informal", "nl_NL-x-informal"),
("NL-NL-X-INFORMAL", "nl_NL-x-informal"),
("sr-latn-x-informal", "sr_Latn-x-informal"),
("SR-LATN-X-INFORMAL", "sr_Latn-x-informal"),
)
for lang, locale in tests:
with self.subTest(lang=lang):
self.assertEqual(to_locale(lang), locale)
def test_to_language(self):
self.assertEqual(to_language("en_US"), "en-us")
self.assertEqual(to_language("sr_Lat"), "sr-lat")
def test_language_bidi(self):
self.assertIs(get_language_bidi(), False)
with translation.override(None):
self.assertIs(get_language_bidi(), False)
def test_language_bidi_null(self):
self.assertIs(trans_null.get_language_bidi(), False)
with override_settings(LANGUAGE_CODE="he"):
self.assertIs(get_language_bidi(), True)
class TranslationLoadingTests(SimpleTestCase):
def setUp(self):
"""Clear translation state."""
self._old_language = get_language()
self._old_translations = trans_real._translations
deactivate()
trans_real._translations = {}
def tearDown(self):
trans_real._translations = self._old_translations
activate(self._old_language)
@override_settings(
USE_I18N=True,
LANGUAGE_CODE="en",
LANGUAGES=[
("en", "English"),
("en-ca", "English (Canada)"),
("en-nz", "English (New Zealand)"),
("en-au", "English (Australia)"),
],
LOCALE_PATHS=[os.path.join(here, "loading")],
INSTALLED_APPS=["i18n.loading_app"],
)
def test_translation_loading(self):
"""
"loading_app" does not have translations for all languages provided by
"loading". Catalogs are merged correctly.
"""
tests = [
("en", "local country person"),
("en_AU", "aussie"),
("en_NZ", "kiwi"),
("en_CA", "canuck"),
]
# Load all relevant translations.
for language, _ in tests:
activate(language)
# Catalogs are merged correctly.
for language, nickname in tests:
with self.subTest(language=language):
activate(language)
self.assertEqual(gettext("local country person"), nickname)
class TranslationThreadSafetyTests(SimpleTestCase):
def setUp(self):
self._old_language = get_language()
self._translations = trans_real._translations
# here we rely on .split() being called inside the _fetch()
# in trans_real.translation()
class sideeffect_str(str):
def split(self, *args, **kwargs):
res = str.split(self, *args, **kwargs)
trans_real._translations["en-YY"] = None
return res
trans_real._translations = {sideeffect_str("en-XX"): None}
def tearDown(self):
trans_real._translations = self._translations
activate(self._old_language)
def test_bug14894_translation_activate_thread_safety(self):
translation_count = len(trans_real._translations)
# May raise RuntimeError if translation.activate() isn't thread-safe.
translation.activate("pl")
# make sure sideeffect_str actually added a new translation
self.assertLess(translation_count, len(trans_real._translations))
class FormattingTests(SimpleTestCase):
def setUp(self):
super().setUp()
self.n = decimal.Decimal("66666.666")
self.f = 99999.999
self.d = datetime.date(2009, 12, 31)
self.dt = datetime.datetime(2009, 12, 31, 20, 50)
self.t = datetime.time(10, 15, 48)
self.long = 10000
self.ctxt = Context(
{
"n": self.n,
"t": self.t,
"d": self.d,
"dt": self.dt,
"f": self.f,
"l": self.long,
}
)
def test_all_format_strings(self):
all_locales = LANG_INFO.keys()
some_date = datetime.date(2017, 10, 14)
some_datetime = datetime.datetime(2017, 10, 14, 10, 23)
for locale in all_locales:
with self.subTest(locale=locale), translation.override(locale):
self.assertIn(
"2017", date_format(some_date)
) # Uses DATE_FORMAT by default
self.assertIn(
"23", time_format(some_datetime)
) # Uses TIME_FORMAT by default
self.assertIn("2017", date_format(some_datetime, "DATETIME_FORMAT"))
self.assertIn("2017", date_format(some_date, "YEAR_MONTH_FORMAT"))
self.assertIn("14", date_format(some_date, "MONTH_DAY_FORMAT"))
self.assertIn("2017", date_format(some_date, "SHORT_DATE_FORMAT"))
self.assertIn(
"2017",
date_format(some_datetime, "SHORT_DATETIME_FORMAT"),
)
def test_locale_independent(self):
"""
Localization of numbers
"""
with self.settings(USE_THOUSAND_SEPARATOR=False):
self.assertEqual(
"66666.66",
nformat(
self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep=","
),
)
self.assertEqual(
"66666A6",
nformat(
self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B"
),
)
self.assertEqual(
"66666",
nformat(
self.n, decimal_sep="X", decimal_pos=0, grouping=1, thousand_sep="Y"
),
)
with self.settings(USE_THOUSAND_SEPARATOR=True):
self.assertEqual(
"66,666.66",
nformat(
self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep=","
),
)
self.assertEqual(
"6B6B6B6B6A6",
nformat(
self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B"
),
)
self.assertEqual(
"-66666.6", nformat(-66666.666, decimal_sep=".", decimal_pos=1)
)
self.assertEqual(
"-66666.0", nformat(int("-66666"), decimal_sep=".", decimal_pos=1)
)
self.assertEqual(
"10000.0", nformat(self.long, decimal_sep=".", decimal_pos=1)
)
self.assertEqual(
"10,00,00,000.00",
nformat(
100000000.00,
decimal_sep=".",
decimal_pos=2,
grouping=(3, 2, 0),
thousand_sep=",",
),
)
self.assertEqual(
"1,0,00,000,0000.00",
nformat(
10000000000.00,
decimal_sep=".",
decimal_pos=2,
grouping=(4, 3, 2, 1, 0),
thousand_sep=",",
),
)
self.assertEqual(
"10000,00,000.00",
nformat(
1000000000.00,
decimal_sep=".",
decimal_pos=2,
grouping=(3, 2, -1),
thousand_sep=",",
),
)
# This unusual grouping/force_grouping combination may be triggered
# by the intcomma filter.
self.assertEqual(
"10000",
nformat(
self.long,
decimal_sep=".",
decimal_pos=0,
grouping=0,
force_grouping=True,
),
)
# date filter
self.assertEqual(
"31.12.2009 в 20:50",
Template('{{ dt|date:"d.m.Y в H:i" }}').render(self.ctxt),
)
self.assertEqual(
"⌚ 10:15", Template('{{ t|time:"⌚ H:i" }}').render(self.ctxt)
)
def test_false_like_locale_formats(self):
"""
The active locale's formats take precedence over the default settings
even if they would be interpreted as False in a conditional test
(e.g. 0 or empty string) (#16938).
"""
with translation.override("fr"):
with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="!"):
self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR"))
# Even a second time (after the format has been cached)...
self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR"))
with self.settings(FIRST_DAY_OF_WEEK=0):
self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK"))
# Even a second time (after the format has been cached)...
self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK"))
def test_l10n_enabled(self):
self.maxDiff = 3000
# Catalan locale
with translation.override("ca", deactivate=True):
self.assertEqual(r"j E \d\e Y", get_format("DATE_FORMAT"))
self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK"))
self.assertEqual(",", get_format("DECIMAL_SEPARATOR"))
self.assertEqual("10:15", time_format(self.t))
self.assertEqual("31 desembre de 2009", date_format(self.d))
self.assertEqual("1 abril de 2009", date_format(datetime.date(2009, 4, 1)))
self.assertEqual(
"desembre del 2009", date_format(self.d, "YEAR_MONTH_FORMAT")
)
self.assertEqual(
"31/12/2009 20:50", date_format(self.dt, "SHORT_DATETIME_FORMAT")
)
self.assertEqual("No localizable", localize("No localizable"))
with self.settings(USE_THOUSAND_SEPARATOR=True):
self.assertEqual("66.666,666", localize(self.n))
self.assertEqual("99.999,999", localize(self.f))
self.assertEqual("10.000", localize(self.long))
self.assertEqual("True", localize(True))
with self.settings(USE_THOUSAND_SEPARATOR=False):
self.assertEqual("66666,666", localize(self.n))
self.assertEqual("99999,999", localize(self.f))
self.assertEqual("10000", localize(self.long))
self.assertEqual("31 desembre de 2009", localize(self.d))
self.assertEqual("31 desembre de 2009 a les 20:50", localize(self.dt))
with self.settings(USE_THOUSAND_SEPARATOR=True):
self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt))
self.assertEqual("99.999,999", Template("{{ f }}").render(self.ctxt))
self.assertEqual("10.000", Template("{{ l }}").render(self.ctxt))
with self.settings(USE_THOUSAND_SEPARATOR=True):
form3 = I18nForm(
{
"decimal_field": "66.666,666",
"float_field": "99.999,999",
"date_field": "31/12/2009",
"datetime_field": "31/12/2009 20:50",
"time_field": "20:50",
"integer_field": "1.234",
}
)
self.assertTrue(form3.is_valid())
self.assertEqual(
decimal.Decimal("66666.666"), form3.cleaned_data["decimal_field"]
)
self.assertEqual(99999.999, form3.cleaned_data["float_field"])
self.assertEqual(
datetime.date(2009, 12, 31), form3.cleaned_data["date_field"]
)
self.assertEqual(
datetime.datetime(2009, 12, 31, 20, 50),
form3.cleaned_data["datetime_field"],
)
self.assertEqual(
datetime.time(20, 50), form3.cleaned_data["time_field"]
)
self.assertEqual(1234, form3.cleaned_data["integer_field"])
with self.settings(USE_THOUSAND_SEPARATOR=False):
self.assertEqual("66666,666", Template("{{ n }}").render(self.ctxt))
self.assertEqual("99999,999", Template("{{ f }}").render(self.ctxt))
self.assertEqual(
"31 desembre de 2009", Template("{{ d }}").render(self.ctxt)
)
self.assertEqual(
"31 desembre de 2009 a les 20:50",
Template("{{ dt }}").render(self.ctxt),
)
self.assertEqual(
"66666,67", Template("{{ n|floatformat:2 }}").render(self.ctxt)
)
self.assertEqual(
"100000,0", Template("{{ f|floatformat }}").render(self.ctxt)
)
self.assertEqual(
"66.666,67",
Template('{{ n|floatformat:"2g" }}').render(self.ctxt),
)
self.assertEqual(
"100.000,0",
Template('{{ f|floatformat:"g" }}').render(self.ctxt),
)
self.assertEqual(
"10:15", Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt)
)
self.assertEqual(
"31/12/2009",
Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt),
)
self.assertEqual(
"31/12/2009 20:50",
Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt),
)
self.assertEqual(
date_format(datetime.datetime.now()),
Template('{% now "DATE_FORMAT" %}').render(self.ctxt),
)
with self.settings(USE_THOUSAND_SEPARATOR=False):
form4 = I18nForm(
{
"decimal_field": "66666,666",
"float_field": "99999,999",
"date_field": "31/12/2009",
"datetime_field": "31/12/2009 20:50",
"time_field": "20:50",
"integer_field": "1234",
}
)
self.assertTrue(form4.is_valid())
self.assertEqual(
decimal.Decimal("66666.666"), form4.cleaned_data["decimal_field"]
)
self.assertEqual(99999.999, form4.cleaned_data["float_field"])
self.assertEqual(
datetime.date(2009, 12, 31), form4.cleaned_data["date_field"]
)
self.assertEqual(
datetime.datetime(2009, 12, 31, 20, 50),
form4.cleaned_data["datetime_field"],
)
self.assertEqual(
datetime.time(20, 50), form4.cleaned_data["time_field"]
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | true |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/forms.py | tests/i18n/forms.py | from django 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.ModelForm):
cents_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__"
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/test_percents.py | tests/i18n/test_percents.py | import os
from django.template import Context, Template
from django.test import SimpleTestCase, override_settings
from django.utils.translation import activate, get_language, trans_real
from .utils import 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._translations = trans_real._translations
activate("fr")
def tearDown(self):
trans_real._translations = self._translations
activate(self._language)
class ExtractingStringsWithPercentSigns(POFileAssertionMixin, 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 persist through to a rendered template.
"""
def setUp(self):
super().setUp()
with open(self.PO_FILE) as fp:
self.po_contents = fp.read()
def test_trans_tag_with_percent_symbol_at_the_end(self):
self.assertMsgId(
"Literal with a percent symbol at the end %%", self.po_contents
)
def test_trans_tag_with_percent_symbol_in_the_middle(self):
self.assertMsgId(
"Literal with a percent %% symbol in the middle", self.po_contents
)
self.assertMsgId("It is 100%%", self.po_contents)
def test_trans_tag_with_string_that_look_like_fmt_spec(self):
self.assertMsgId(
"Looks like a str fmt spec %%s but should not be interpreted as such",
self.po_contents,
)
self.assertMsgId(
"Looks like a str fmt spec %% o but should not be interpreted as such",
self.po_contents,
)
def test_adds_python_format_to_all_percent_signs(self):
self.assertMsgId(
"1 percent sign %%, 2 percent signs %%%%, 3 percent signs %%%%%%",
self.po_contents,
)
self.assertMsgId(
"%(name)s says: 1 percent sign %%, 2 percent signs %%%%", self.po_contents
)
class RenderingTemplatesWithPercentSigns(FrenchTestCase):
"""
Test rendering of templates that use percent signs.
Ensures both translate and blocktranslate tags behave consistently.
Refs #11240, #11966, #24257
"""
def test_translates_with_a_percent_symbol_at_the_end(self):
expected = "Littérale avec un symbole de pour cent à la fin %"
trans_tpl = Template(
"{% load i18n %}"
'{% translate "Literal with a percent symbol at the end %" %}'
)
self.assertEqual(trans_tpl.render(Context({})), expected)
block_tpl = Template(
"{% load i18n %}{% blocktranslate %}Literal with a percent symbol at "
"the end %{% endblocktranslate %}"
)
self.assertEqual(block_tpl.render(Context({})), expected)
def test_translates_with_percent_symbol_in_the_middle(self):
expected = "Pour cent littérale % avec un symbole au milieu"
trans_tpl = Template(
"{% load i18n %}"
'{% translate "Literal with a percent % symbol in the middle" %}'
)
self.assertEqual(trans_tpl.render(Context({})), expected)
block_tpl = Template(
"{% load i18n %}{% blocktranslate %}Literal with a percent % symbol "
"in the middle{% endblocktranslate %}"
)
self.assertEqual(block_tpl.render(Context({})), expected)
def test_translates_with_percent_symbol_using_context(self):
trans_tpl = Template('{% load i18n %}{% translate "It is 100%" %}')
self.assertEqual(trans_tpl.render(Context({})), "Il est de 100%")
trans_tpl = Template(
'{% load i18n %}{% translate "It is 100%" context "female" %}'
)
self.assertEqual(trans_tpl.render(Context({})), "Elle est de 100%")
block_tpl = Template(
"{% load i18n %}{% blocktranslate %}It is 100%{% endblocktranslate %}"
)
self.assertEqual(block_tpl.render(Context({})), "Il est de 100%")
block_tpl = Template(
"{% load i18n %}"
'{% blocktranslate context "female" %}It is 100%{% endblocktranslate %}'
)
self.assertEqual(block_tpl.render(Context({})), "Elle est de 100%")
def test_translates_with_string_that_look_like_fmt_spec_with_trans(self):
# tests "%s"
expected = (
"On dirait un spec str fmt %s mais ne devrait pas être interprété comme "
"plus disponible"
)
trans_tpl = Template(
'{% load i18n %}{% translate "Looks like a str fmt spec %s but '
'should not be interpreted as such" %}'
)
self.assertEqual(trans_tpl.render(Context({})), expected)
block_tpl = Template(
"{% load i18n %}{% blocktranslate %}Looks like a str fmt spec %s but "
"should not be interpreted as such{% endblocktranslate %}"
)
self.assertEqual(block_tpl.render(Context({})), expected)
# tests "% o"
expected = (
"On dirait un spec str fmt % o mais ne devrait pas être interprété comme "
"plus disponible"
)
trans_tpl = Template(
"{% load i18n %}"
'{% translate "Looks like a str fmt spec % o but should not be '
'interpreted as such" %}'
)
self.assertEqual(trans_tpl.render(Context({})), expected)
block_tpl = Template(
"{% load i18n %}"
"{% blocktranslate %}Looks like a str fmt spec % o but should not be "
"interpreted as such{% endblocktranslate %}"
)
self.assertEqual(block_tpl.render(Context({})), expected)
def test_translates_multiple_percent_signs(self):
expected = (
"1 % signe pour cent, signes %% 2 pour cent, trois signes de pourcentage "
"%%%"
)
trans_tpl = Template(
'{% load i18n %}{% translate "1 percent sign %, 2 percent signs %%, '
'3 percent signs %%%" %}'
)
self.assertEqual(trans_tpl.render(Context({})), expected)
block_tpl = Template(
"{% load i18n %}{% blocktranslate %}1 percent sign %, 2 percent signs "
"%%, 3 percent signs %%%{% endblocktranslate %}"
)
self.assertEqual(block_tpl.render(Context({})), expected)
block_tpl = Template(
"{% load i18n %}{% blocktranslate %}{{name}} says: 1 percent sign %, "
"2 percent signs %%{% endblocktranslate %}"
)
self.assertEqual(
block_tpl.render(Context({"name": "Django"})),
"Django dit: 1 pour cent signe %, deux signes de pourcentage %%",
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/urls.py | tests/i18n/urls.py | from django.conf.urls.i18n import i18n_patterns
from django.http import HttpResponse, StreamingHttpResponse
from django.urls import path
from django.utils.translation import gettext_lazy as _
urlpatterns = i18n_patterns(
path("simple/", lambda r: HttpResponse()),
path("streaming/", lambda r: StreamingHttpResponse([_("Yes"), "/", _("No")])),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/loading_app/__init__.py | tests/i18n/loading_app/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/loading_app/apps.py | tests/i18n/loading_app/apps.py | from django.apps import AppConfig
class LoadingAppConfig(AppConfig):
name = "i18n.loading_app"
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/other2/__init__.py | tests/i18n/other2/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/other2/locale/__init__.py | tests/i18n/other2/locale/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/other2/locale/de/formats.py | tests/i18n/other2/locale/de/formats.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/other2/locale/de/__init__.py | tests/i18n/other2/locale/de/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/commands/__init__.py | tests/i18n/commands/__init__.py | from django.utils.translation import gettext as _
from django.utils.translation import ngettext
# Translators: This comment should be extracted
dummy1 = _("This is a translatable string.")
# This comment should not be extracted
dummy2 = _("This is another translatable string.")
# This file has a literal with plural forms. When processed first, makemessages
# shouldn't create a .po file with duplicate `Plural-Forms` headers
number = 3
dummy3 = ngettext("%(number)s Foo", "%(number)s Foos", number) % {"number": number}
dummy4 = _("Size")
# This string is intentionally duplicated in test.html
dummy5 = _("This literal should be included.")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/commands/app_with_locale/some_file.py | tests/i18n/commands/app_with_locale/some_file.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/obsolete_translations/__init__.py | tests/i18n/obsolete_translations/__init__.py | from django.utils.translation import gettext as _
string1 = _("This is a translatable string.")
# Obsolete string.
# string2 = _("Obsolete string.")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/patterns/__init__.py | tests/i18n/patterns/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/patterns/tests.py | tests/i18n/patterns/tests.py | import os
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponse, HttpResponsePermanentRedirect
from django.middleware.locale import LocaleMiddleware
from django.template import Context, Template
from django.test import SimpleTestCase, override_settings
from django.test.client import RequestFactory
from django.test.utils import override_script_prefix
from django.urls import clear_url_caches, resolve, reverse, translate_url
from django.utils import translation
class PermanentRedirectLocaleMiddleWare(LocaleMiddleware):
response_redirect_class = HttpResponsePermanentRedirect
@override_settings(
USE_I18N=True,
LOCALE_PATHS=[
os.path.join(os.path.dirname(__file__), "locale"),
],
LANGUAGE_CODE="en-us",
LANGUAGES=[
("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_processors": [
"django.template.context_processors.i18n",
],
},
}
],
)
class URLTestCaseBase(SimpleTestCase):
"""
TestCase base-class for the URL tests.
"""
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(URLTestCaseBase):
"""
Tests if the `i18n_patterns` is adding the prefix correctly.
"""
def test_not_prefixed(self):
with translation.override("en"):
self.assertEqual(reverse("not-prefixed"), "/not-prefixed/")
self.assertEqual(
reverse("not-prefixed-included-url"), "/not-prefixed-include/foo/"
)
with translation.override("nl"):
self.assertEqual(reverse("not-prefixed"), "/not-prefixed/")
self.assertEqual(
reverse("not-prefixed-included-url"), "/not-prefixed-include/foo/"
)
def test_prefixed(self):
with translation.override("en"):
self.assertEqual(reverse("prefixed"), "/en/prefixed/")
with translation.override("nl"):
self.assertEqual(reverse("prefixed"), "/nl/prefixed/")
with translation.override(None):
self.assertEqual(
reverse("prefixed"), "/%s/prefixed/" % settings.LANGUAGE_CODE
)
@override_settings(ROOT_URLCONF="i18n.patterns.urls.wrong")
def test_invalid_prefix_use(self):
msg = "Using i18n_patterns in an included URLconf is not allowed."
with self.assertRaisesMessage(ImproperlyConfigured, msg):
reverse("account:register")
@override_settings(ROOT_URLCONF="i18n.patterns.urls.disabled")
class URLDisabledTests(URLTestCaseBase):
@override_settings(USE_I18N=False)
def test_prefixed_i18n_disabled(self):
with translation.override("en"):
self.assertEqual(reverse("prefixed"), "/prefixed/")
with translation.override("nl"):
self.assertEqual(reverse("prefixed"), "/prefixed/")
class RequestURLConfTests(SimpleTestCase):
@override_settings(ROOT_URLCONF="i18n.patterns.urls.path_unused")
def test_request_urlconf_considered(self):
request = RequestFactory().get("/nl/")
request.urlconf = "i18n.patterns.urls.default"
middleware = LocaleMiddleware(lambda req: HttpResponse())
with translation.override("nl"):
middleware.process_request(request)
self.assertEqual(request.LANGUAGE_CODE, "nl")
@override_settings(ROOT_URLCONF="i18n.patterns.urls.path_unused")
class PathUnusedTests(URLTestCaseBase):
"""
If no i18n_patterns is used in root URLconfs, then no language activation
activation happens based on url prefix.
"""
def test_no_lang_activate(self):
response = self.client.get("/nl/foo/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers["content-language"], "en")
self.assertEqual(response.context["LANGUAGE_CODE"], "en")
class URLTranslationTests(URLTestCaseBase):
"""
Tests if the pattern-strings are translated correctly (within the
`i18n_patterns` and the normal `patterns` function).
"""
def test_no_prefix_translated(self):
with translation.override("en"):
self.assertEqual(reverse("no-prefix-translated"), "/translated/")
self.assertEqual(
reverse("no-prefix-translated-regex"), "/translated-regex/"
)
self.assertEqual(
reverse("no-prefix-translated-slug", kwargs={"slug": "yeah"}),
"/translated/yeah/",
)
with translation.override("nl"):
self.assertEqual(reverse("no-prefix-translated"), "/vertaald/")
self.assertEqual(reverse("no-prefix-translated-regex"), "/vertaald-regex/")
self.assertEqual(
reverse("no-prefix-translated-slug", kwargs={"slug": "yeah"}),
"/vertaald/yeah/",
)
with translation.override("pt-br"):
self.assertEqual(reverse("no-prefix-translated"), "/traduzidos/")
self.assertEqual(
reverse("no-prefix-translated-regex"), "/traduzidos-regex/"
)
self.assertEqual(
reverse("no-prefix-translated-slug", kwargs={"slug": "yeah"}),
"/traduzidos/yeah/",
)
def test_users_url(self):
with translation.override("en"):
self.assertEqual(reverse("users"), "/en/users/")
with translation.override("nl"):
self.assertEqual(reverse("users"), "/nl/gebruikers/")
self.assertEqual(reverse("prefixed_xml"), "/nl/prefixed.xml")
with translation.override("pt-br"):
self.assertEqual(reverse("users"), "/pt-br/usuarios/")
def test_translate_url_utility(self):
with translation.override("en"):
self.assertEqual(
translate_url("/en/nonexistent/", "nl"), "/en/nonexistent/"
)
self.assertEqual(translate_url("/en/users/", "nl"), "/nl/gebruikers/")
# Namespaced URL
self.assertEqual(
translate_url("/en/account/register/", "nl"), "/nl/profiel/registreren/"
)
# path() URL pattern
self.assertEqual(
translate_url("/en/account/register-as-path/", "nl"),
"/nl/profiel/registreren-als-pad/",
)
self.assertEqual(translation.get_language(), "en")
# re_path() URL with parameters.
self.assertEqual(
translate_url("/en/with-arguments/regular-argument/", "nl"),
"/nl/with-arguments/regular-argument/",
)
self.assertEqual(
translate_url(
"/en/with-arguments/regular-argument/optional.html", "nl"
),
"/nl/with-arguments/regular-argument/optional.html",
)
# path() URL with parameter.
self.assertEqual(
translate_url("/en/path-with-arguments/regular-argument/", "nl"),
"/nl/path-with-arguments/regular-argument/",
)
with translation.override("nl"):
self.assertEqual(translate_url("/nl/gebruikers/", "en"), "/en/users/")
self.assertEqual(translation.get_language(), "nl")
def test_reverse_translated_with_captured_kwargs(self):
with translation.override("en"):
match = resolve("/translated/apo/")
# Links to the same page in other languages.
tests = [
("nl", "/vertaald/apo/"),
("pt-br", "/traduzidos/apo/"),
]
for lang, expected_link in tests:
with translation.override(lang):
self.assertEqual(
reverse(
match.url_name, args=match.args, kwargs=match.captured_kwargs
),
expected_link,
)
def test_locale_not_interepreted_as_regex(self):
with translation.override("e("):
# Would previously error:
# re.error: missing ), unterminated subpattern at position 1
reverse("users")
class URLNamespaceTests(URLTestCaseBase):
"""
Tests if the translations are still working within namespaces.
"""
def test_account_register(self):
with translation.override("en"):
self.assertEqual(reverse("account:register"), "/en/account/register/")
self.assertEqual(
reverse("account:register-as-path"), "/en/account/register-as-path/"
)
with translation.override("nl"):
self.assertEqual(reverse("account:register"), "/nl/profiel/registreren/")
self.assertEqual(
reverse("account:register-as-path"), "/nl/profiel/registreren-als-pad/"
)
class URLRedirectTests(URLTestCaseBase):
"""
Tests if the user gets redirected to the right URL when there is no
language-prefix in the request URL.
"""
def test_no_prefix_response(self):
response = self.client.get("/not-prefixed/")
self.assertEqual(response.status_code, 200)
def test_en_redirect(self):
response = self.client.get(
"/account/register/", headers={"accept-language": "en"}
)
self.assertRedirects(response, "/en/account/register/")
response = self.client.get(response.headers["location"])
self.assertEqual(response.status_code, 200)
def test_en_redirect_wrong_url(self):
response = self.client.get(
"/profiel/registreren/", headers={"accept-language": "en"}
)
self.assertEqual(response.status_code, 404)
def test_nl_redirect(self):
response = self.client.get(
"/profiel/registreren/", headers={"accept-language": "nl"}
)
self.assertRedirects(response, "/nl/profiel/registreren/")
response = self.client.get(response.headers["location"])
self.assertEqual(response.status_code, 200)
def test_nl_redirect_wrong_url(self):
response = self.client.get(
"/account/register/", headers={"accept-language": "nl"}
)
self.assertEqual(response.status_code, 404)
def test_pt_br_redirect(self):
response = self.client.get(
"/conta/registre-se/", headers={"accept-language": "pt-br"}
)
self.assertRedirects(response, "/pt-br/conta/registre-se/")
response = self.client.get(response.headers["location"])
self.assertEqual(response.status_code, 200)
def test_pl_pl_redirect(self):
# language from outside of the supported LANGUAGES list
response = self.client.get(
"/account/register/", headers={"accept-language": "pl-pl"}
)
self.assertRedirects(response, "/en/account/register/")
response = self.client.get(response.headers["location"])
self.assertEqual(response.status_code, 200)
@override_settings(
MIDDLEWARE=[
"i18n.patterns.tests.PermanentRedirectLocaleMiddleWare",
"django.middleware.common.CommonMiddleware",
],
)
def test_custom_redirect_class(self):
response = self.client.get(
"/account/register/", headers={"accept-language": "en"}
)
self.assertRedirects(response, "/en/account/register/", 301)
class URLVaryAcceptLanguageTests(URLTestCaseBase):
"""
'Accept-Language' is not added to the Vary header when using prefixed URLs.
"""
def test_no_prefix_response(self):
response = self.client.get("/not-prefixed/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get("Vary"), "Accept-Language")
def test_en_redirect(self):
"""
The redirect to a prefixed URL depends on 'Accept-Language' and
'Cookie', but once prefixed no header is set.
"""
response = self.client.get(
"/account/register/", headers={"accept-language": "en"}
)
self.assertRedirects(response, "/en/account/register/")
self.assertEqual(response.get("Vary"), "Accept-Language, Cookie")
response = self.client.get(response.headers["location"])
self.assertEqual(response.status_code, 200)
self.assertFalse(response.get("Vary"))
class URLRedirectWithoutTrailingSlashTests(URLTestCaseBase):
"""
Tests the redirect when the requested URL doesn't end with a slash
(`settings.APPEND_SLASH=True`).
"""
def test_not_prefixed_redirect(self):
response = self.client.get("/not-prefixed", headers={"accept-language": "en"})
self.assertRedirects(response, "/not-prefixed/", 301)
def test_en_redirect(self):
response = self.client.get(
"/account/register", headers={"accept-language": "en"}, follow=True
)
# We only want one redirect, bypassing CommonMiddleware
self.assertEqual(response.redirect_chain, [("/en/account/register/", 302)])
self.assertRedirects(response, "/en/account/register/", 302)
response = self.client.get(
"/prefixed.xml", headers={"accept-language": "en"}, follow=True
)
self.assertRedirects(response, "/en/prefixed.xml", 302)
class URLRedirectWithoutTrailingSlashSettingTests(URLTestCaseBase):
"""
Tests the redirect when the requested URL doesn't end with a slash
(`settings.APPEND_SLASH=False`).
"""
@override_settings(APPEND_SLASH=False)
def test_not_prefixed_redirect(self):
response = self.client.get("/not-prefixed", headers={"accept-language": "en"})
self.assertEqual(response.status_code, 404)
@override_settings(APPEND_SLASH=False)
def test_en_redirect(self):
response = self.client.get(
"/account/register-without-slash", headers={"accept-language": "en"}
)
self.assertRedirects(response, "/en/account/register-without-slash", 302)
response = self.client.get(response.headers["location"])
self.assertEqual(response.status_code, 200)
class URLResponseTests(URLTestCaseBase):
"""Tests if the response has the correct language code."""
def test_not_prefixed_with_prefix(self):
response = self.client.get("/en/not-prefixed/")
self.assertEqual(response.status_code, 404)
def test_en_url(self):
response = self.client.get("/en/account/register/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers["content-language"], "en")
self.assertEqual(response.context["LANGUAGE_CODE"], "en")
def test_nl_url(self):
response = self.client.get("/nl/profiel/registreren/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers["content-language"], "nl")
self.assertEqual(response.context["LANGUAGE_CODE"], "nl")
def test_wrong_en_prefix(self):
response = self.client.get("/en/profiel/registreren/")
self.assertEqual(response.status_code, 404)
def test_wrong_nl_prefix(self):
response = self.client.get("/nl/account/register/")
self.assertEqual(response.status_code, 404)
def test_pt_br_url(self):
response = self.client.get("/pt-br/conta/registre-se/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers["content-language"], "pt-br")
self.assertEqual(response.context["LANGUAGE_CODE"], "pt-br")
def test_en_path(self):
response = self.client.get("/en/account/register-as-path/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers["content-language"], "en")
self.assertEqual(response.context["LANGUAGE_CODE"], "en")
def test_nl_path(self):
response = self.client.get("/nl/profiel/registreren-als-pad/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers["content-language"], "nl")
self.assertEqual(response.context["LANGUAGE_CODE"], "nl")
@override_settings(ROOT_URLCONF="i18n.urls_default_unprefixed", LANGUAGE_CODE="nl")
class URLPrefixedFalseTranslatedTests(URLTestCaseBase):
def test_translated_path_unprefixed_language_other_than_accepted_header(self):
response = self.client.get("/gebruikers/", headers={"accept-language": "en"})
self.assertEqual(response.status_code, 200)
def test_translated_path_unprefixed_language_other_than_cookie_language(self):
self.client.cookies.load({settings.LANGUAGE_COOKIE_NAME: "en"})
response = self.client.get("/gebruikers/")
self.assertEqual(response.status_code, 200)
def test_translated_path_prefixed_language_other_than_accepted_header(self):
response = self.client.get("/en/users/", headers={"accept-language": "nl"})
self.assertEqual(response.status_code, 200)
def test_translated_path_prefixed_language_other_than_cookie_language(self):
self.client.cookies.load({settings.LANGUAGE_COOKIE_NAME: "nl"})
response = self.client.get("/en/users/")
self.assertEqual(response.status_code, 200)
class URLRedirectWithScriptAliasTests(URLTestCaseBase):
"""
#21579 - LocaleMiddleware should respect the script prefix.
"""
def test_language_prefix_with_script_prefix(self):
prefix = "/script_prefix"
with override_script_prefix(prefix):
response = self.client.get(
"/prefixed/", headers={"accept-language": "en"}, SCRIPT_NAME=prefix
)
self.assertRedirects(
response, "%s/en/prefixed/" % prefix, target_status_code=404
)
class URLTagTests(URLTestCaseBase):
"""
Test if the language tag works.
"""
def test_strings_only(self):
t = Template(
"""{% load i18n %}
{% language 'nl' %}{% url 'no-prefix-translated' %}{% endlanguage %}
{% language 'pt-br' %}{% url 'no-prefix-translated' %}{% endlanguage %}"""
)
self.assertEqual(
t.render(Context({})).strip().split(), ["/vertaald/", "/traduzidos/"]
)
def test_context(self):
ctx = Context({"lang1": "nl", "lang2": "pt-br"})
tpl = Template(
"""{% load i18n %}
{% language lang1 %}{% url 'no-prefix-translated' %}{% endlanguage %}
{% language lang2 %}{% url 'no-prefix-translated' %}{% endlanguage %}"""
)
self.assertEqual(
tpl.render(ctx).strip().split(), ["/vertaald/", "/traduzidos/"]
)
def test_args(self):
tpl = Template(
"""
{% load i18n %}
{% language 'nl' %}
{% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %}
{% language 'pt-br' %}
{% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %}
"""
)
self.assertEqual(
tpl.render(Context({})).strip().split(),
["/vertaald/apo/", "/traduzidos/apo/"],
)
def test_kwargs(self):
tpl = Template(
"""
{% load i18n %}
{% language 'nl' %}
{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}
{% language 'pt-br' %}
{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}
"""
)
self.assertEqual(
tpl.render(Context({})).strip().split(),
["/vertaald/apo/", "/traduzidos/apo/"],
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/patterns/urls/wrong_namespace.py | tests/i18n/patterns/urls/wrong_namespace.py | from django.conf.urls.i18n import i18n_patterns
from django.urls import re_path
from django.utils.translation import gettext_lazy as _
from django.views.generic import TemplateView
view = TemplateView.as_view(template_name="dummy.html")
app_name = "account"
urlpatterns = i18n_patterns(
re_path(_(r"^register/$"), view, name="register"),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/patterns/urls/wrong.py | tests/i18n/patterns/urls/wrong.py | from django.conf.urls.i18n import i18n_patterns
from django.urls import include, re_path
from django.utils.translation import gettext_lazy as _
urlpatterns = i18n_patterns(
re_path(
_(r"^account/"),
include("i18n.patterns.urls.wrong_namespace", namespace="account"),
),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/patterns/urls/default.py | tests/i18n/patterns/urls/default.py | from django.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-translated-regex"),
re_path(
_(r"^translated/(?P<slug>[\w-]+)/$"),
view,
{"slug": "default-slug"},
name="no-prefix-translated-slug",
),
]
urlpatterns += i18n_patterns(
path("prefixed/", 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-with-arguments/<str:argument>/"),
view,
name="path-with-arguments",
),
re_path(_(r"^users/$"), view, name="users"),
re_path(
_(r"^account/"), include("i18n.patterns.urls.namespace", namespace="account")
),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/patterns/urls/disabled.py | tests/i18n/patterns/urls/disabled.py | from django.conf.urls.i18n import i18n_patterns
from django.urls import path
from django.views.generic import TemplateView
view = TemplateView.as_view(template_name="dummy.html")
urlpatterns = i18n_patterns(
path("prefixed/", view, name="prefixed"),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/patterns/urls/included.py | tests/i18n/patterns/urls/included.py | from django.urls import path
from django.views.generic import TemplateView
view = TemplateView.as_view(template_name="dummy.html")
urlpatterns = [
path("foo/", view, name="not-prefixed-included-url"),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/patterns/urls/namespace.py | tests/i18n/patterns/urls/namespace.py | from django.urls import 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")
app_name = "account"
urlpatterns = [
re_path(_(r"^register/$"), view, name="register"),
re_path(_(r"^register-without-slash$"), view, name="register-without-slash"),
path(_("register-as-path/"), view, name="register-as-path"),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/patterns/urls/__init__.py | tests/i18n/patterns/urls/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/patterns/urls/path_unused.py | tests/i18n/patterns/urls/path_unused.py | from django.urls import re_path
from django.views.generic import TemplateView
view = TemplateView.as_view(template_name="dummy.html")
urlpatterns = [
re_path("^nl/foo/", view, name="not-translated"),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/territorial_fallback/__init__.py | tests/i18n/territorial_fallback/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/exclude/__init__.py | tests/i18n/exclude/__init__.py | # This package is used to test the --exclude option of
# the makemessages and compilemessages management commands.
# The locale directory for this app is generated automatically
# by the test cases.
from django.utils.translation import gettext as _
# Translators: This comment should be extracted
dummy1 = _("This is a translatable string.")
# This comment should not be extracted
dummy2 = _("This is another translatable string.")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/contenttypes/__init__.py | tests/i18n/contenttypes/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/contenttypes/tests.py | tests/i18n/contenttypes/tests.py | import os
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase, override_settings
from django.utils import translation
@override_settings(
USE_I18N=True,
LOCALE_PATHS=[
os.path.join(os.path.dirname(__file__), "locale"),
],
LANGUAGE_CODE="en",
LANGUAGES=[
("en", "English"),
("fr", "French"),
],
)
class ContentTypeTests(TestCase):
def test_verbose_name(self):
company_type = ContentType.objects.get(app_label="i18n", model="company")
with translation.override("en"):
self.assertEqual(str(company_type), "I18N | Company")
with translation.override("fr"):
self.assertEqual(str(company_type), "I18N | Société")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/unchanged/__init__.py | tests/i18n/unchanged/__init__.py | from django.utils.translation import gettext as _
string1 = _("This is a translatable string.")
string2 = _("This is another translatable string.")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/sampleproject/manage.py | tests/i18n/sampleproject/manage.py | #!/usr/bin/env python
import os
import sys
sys.path.append(os.path.abspath(os.path.join("..", "..", "..")))
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sampleproject.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/sampleproject/update_catalogs.py | tests/i18n/sampleproject/update_catalogs.py | #!/usr/bin/env python
"""
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 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
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__))
sys.path.append(os.path.abspath(os.path.join(proj_dir, "..", "..", "..")))
def update_translation_catalogs():
"""Run makemessages and compilemessages in sampleproject."""
from django.core.management import call_command
prev_cwd = os.getcwd()
os.chdir(proj_dir)
call_command("makemessages")
call_command("compilemessages")
# keep the diff friendly - remove 'POT-Creation-Date'
pofile = os.path.join(proj_dir, "locale", "fr", "LC_MESSAGES", "django.po")
with open(pofile) as f:
content = f.read()
content = re.sub(r'^"POT-Creation-Date.+$\s', "", content, flags=re.MULTILINE)
with open(pofile, "w") as f:
f.write(content)
os.chdir(prev_cwd)
if __name__ == "__main__":
update_translation_catalogs()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/sampleproject/sampleproject/settings.py | tests/i18n/sampleproject/sampleproject/settings.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/sampleproject/sampleproject/__init__.py | tests/i18n/sampleproject/sampleproject/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/i18n/project_dir/__init__.py | tests/i18n/project_dir/__init__.py | # Sample project used by test_extraction.CustomLayoutExtractionTests
from django.utils.translation import gettext as _
string = _("This is a project-level string")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.