This commit is contained in:
Sachi Jain 2025-11-17 00:59:12 +05:30 committed by GitHub
commit 9a9239ce64
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 102 additions and 152 deletions

View file

@ -202,24 +202,26 @@ class UserAttributeSimilarityValidatorTest(TestCase):
self.assertEqual(cm.exception.messages, [expected_error % "username"])
self.assertEqual(cm.exception.error_list[0].code, "password_too_similar")
with self.assertRaises(ValidationError) as cm:
msg = expected_error % "email address"
with self.assertRaisesMessage(ValidationError, msg):
UserAttributeSimilarityValidator().validate("example.com", user=user)
self.assertEqual(cm.exception.messages, [expected_error % "email address"])
with self.assertRaises(ValidationError) as cm:
msg = expected_error % "first name"
with self.assertRaisesMessage(ValidationError, msg):
UserAttributeSimilarityValidator(
user_attributes=["first_name"],
max_similarity=0.3,
).validate("testclient", user=user)
self.assertEqual(cm.exception.messages, [expected_error % "first name"])
# max_similarity=1 doesn't allow passwords that are identical to the
# attribute's value.
with self.assertRaises(ValidationError) as cm:
msg = expected_error % "first name"
with self.assertRaisesMessage(ValidationError, msg):
UserAttributeSimilarityValidator(
user_attributes=["first_name"],
max_similarity=1,
).validate(user.first_name, user=user)
self.assertEqual(cm.exception.messages, [expected_error % "first name"])
# Very low max_similarity is rejected.
msg = "max_similarity must be at least 0.1"
with self.assertRaisesMessage(ValueError, msg):
@ -240,11 +242,9 @@ class UserAttributeSimilarityValidatorTest(TestCase):
def username(self):
return "foobar"
with self.assertRaises(ValidationError) as cm:
msg = "The password is too similar to the username."
with self.assertRaisesMessage(ValidationError, msg):
UserAttributeSimilarityValidator().validate("foobar", user=TestUser())
self.assertEqual(
cm.exception.messages, ["The password is too similar to the username."]
)
def test_help_text(self):
self.assertEqual(
@ -294,18 +294,16 @@ class CommonPasswordValidatorTest(SimpleTestCase):
expected_error = "This password is too common."
self.assertIsNone(CommonPasswordValidator().validate("a-safe-password"))
with self.assertRaises(ValidationError) as cm:
with self.assertRaisesMessage(ValidationError, expected_error):
CommonPasswordValidator().validate("godzilla")
self.assertEqual(cm.exception.messages, [expected_error])
def test_common_hexed_codes(self):
expected_error = "This password is too common."
common_hexed_passwords = ["asdfjkl:", "&#2336:"]
for password in common_hexed_passwords:
with self.subTest(password=password):
with self.assertRaises(ValidationError) as cm:
with self.assertRaisesMessage(ValidationError, expected_error):
CommonPasswordValidator().validate(password)
self.assertEqual(cm.exception.messages, [expected_error])
def test_validate_custom_list(self):
path = os.path.join(

View file

@ -1087,12 +1087,9 @@ class TestValidation(PostgreSQLSimpleTestCase):
def test_with_size(self):
field = ArrayField(models.IntegerField(), size=3)
field.clean([1, 2, 3], None)
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "List contains 4 items, it should contain no more than 3."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean([1, 2, 3, 4], None)
self.assertEqual(
cm.exception.messages[0],
"List contains 4 items, it should contain no more than 3.",
)
def test_with_size_singular(self):
field = ArrayField(models.IntegerField(), size=1)
@ -1156,21 +1153,15 @@ class TestSimpleFormField(PostgreSQLSimpleTestCase):
def test_to_python_fail(self):
field = SimpleArrayField(forms.IntegerField())
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "Item 1 in the array did not validate: Enter a whole number."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean("a,b,9")
self.assertEqual(
cm.exception.messages[0],
"Item 1 in the array did not validate: Enter a whole number.",
)
def test_validate_fail(self):
field = SimpleArrayField(forms.CharField(required=True))
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "Item 3 in the array did not validate: This field is required."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean("a,b,")
self.assertEqual(
cm.exception.messages[0],
"Item 3 in the array did not validate: This field is required.",
)
def test_validate_fail_base_field_error_params(self):
field = SimpleArrayField(forms.CharField(max_length=2))
@ -1203,12 +1194,9 @@ class TestSimpleFormField(PostgreSQLSimpleTestCase):
def test_validators_fail(self):
field = SimpleArrayField(forms.RegexField("[a-e]{2}"))
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "Item 1 in the array did not validate: Enter a valid value."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean("a,bc,de")
self.assertEqual(
cm.exception.messages[0],
"Item 1 in the array did not validate: Enter a valid value.",
)
def test_delimiter(self):
field = SimpleArrayField(forms.CharField(), delimiter="|")
@ -1227,21 +1215,15 @@ class TestSimpleFormField(PostgreSQLSimpleTestCase):
def test_max_length(self):
field = SimpleArrayField(forms.CharField(), max_length=2)
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "List contains 3 items, it should contain no more than 2."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean("a,b,c")
self.assertEqual(
cm.exception.messages[0],
"List contains 3 items, it should contain no more than 2.",
)
def test_min_length(self):
field = SimpleArrayField(forms.CharField(), min_length=4)
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "List contains 3 items, it should contain no fewer than 4."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean("a,b,c")
self.assertEqual(
cm.exception.messages[0],
"List contains 3 items, it should contain no fewer than 4.",
)
def test_min_length_singular(self):
field = SimpleArrayField(forms.IntegerField(), min_length=2)
@ -1252,9 +1234,9 @@ class TestSimpleFormField(PostgreSQLSimpleTestCase):
def test_required(self):
field = SimpleArrayField(forms.CharField(), required=True)
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "This field is required."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean("")
self.assertEqual(cm.exception.messages[0], "This field is required.")
def test_model_field_formfield(self):
model_field = ArrayField(models.CharField(max_length=27))

View file

@ -823,21 +823,21 @@ class TestFormField(PostgreSQLSimpleTestCase):
def test_integer_invalid_lower(self):
field = pg_forms.IntegerRangeField()
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "Enter a whole number."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean(["a", "2"])
self.assertEqual(cm.exception.messages[0], "Enter a whole number.")
def test_integer_invalid_upper(self):
field = pg_forms.IntegerRangeField()
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "Enter a whole number."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean(["1", "b"])
self.assertEqual(cm.exception.messages[0], "Enter a whole number.")
def test_integer_required(self):
field = pg_forms.IntegerRangeField(required=True)
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "This field is required."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean(["", ""])
self.assertEqual(cm.exception.messages[0], "This field is required.")
value = field.clean([1, ""])
self.assertEqual(value, NumericRange(1, None))
@ -865,21 +865,21 @@ class TestFormField(PostgreSQLSimpleTestCase):
def test_decimal_invalid_lower(self):
field = pg_forms.DecimalRangeField()
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "Enter a number."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean(["a", "3.1415926"])
self.assertEqual(cm.exception.messages[0], "Enter a number.")
def test_decimal_invalid_upper(self):
field = pg_forms.DecimalRangeField()
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "Enter a number."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean(["1.61803399", "b"])
self.assertEqual(cm.exception.messages[0], "Enter a number.")
def test_decimal_required(self):
field = pg_forms.DecimalRangeField(required=True)
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "This field is required."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean(["", ""])
self.assertEqual(cm.exception.messages[0], "This field is required.")
value = field.clean(["1.61803399", ""])
self.assertEqual(value, NumericRange(Decimal("1.61803399"), None))
@ -907,21 +907,21 @@ class TestFormField(PostgreSQLSimpleTestCase):
def test_date_invalid_lower(self):
field = pg_forms.DateRangeField()
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "Enter a valid date."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean(["a", "2013-04-09"])
self.assertEqual(cm.exception.messages[0], "Enter a valid date.")
def test_date_invalid_upper(self):
field = pg_forms.DateRangeField()
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "Enter a valid date."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean(["2013-04-09", "b"])
self.assertEqual(cm.exception.messages[0], "Enter a valid date.")
def test_date_required(self):
field = pg_forms.DateRangeField(required=True)
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "This field is required."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean(["", ""])
self.assertEqual(cm.exception.messages[0], "This field is required.")
value = field.clean(["1976-04-16", ""])
self.assertEqual(value, DateRange(datetime.date(1976, 4, 16), None))
@ -967,21 +967,21 @@ class TestFormField(PostgreSQLSimpleTestCase):
def test_datetime_invalid_lower(self):
field = pg_forms.DateTimeRangeField()
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "Enter a valid date/time."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean(["45", "2013-04-09 11:45"])
self.assertEqual(cm.exception.messages[0], "Enter a valid date/time.")
def test_datetime_invalid_upper(self):
field = pg_forms.DateTimeRangeField()
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "Enter a valid date/time."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean(["2013-04-09 11:45", "sweet pickles"])
self.assertEqual(cm.exception.messages[0], "Enter a valid date/time.")
def test_datetime_required(self):
field = pg_forms.DateTimeRangeField(required=True)
with self.assertRaises(exceptions.ValidationError) as cm:
msg = "This field is required."
with self.assertRaisesMessage(exceptions.ValidationError, msg):
field.clean(["", ""])
self.assertEqual(cm.exception.messages[0], "This field is required.")
value = field.clean(["2013-04-09 11:45", ""])
self.assertEqual(
value, DateTimeTZRange(datetime.datetime(2013, 4, 9, 11, 45), None)

View file

@ -309,15 +309,13 @@ class AssertTemplateUsedTests(TestDataMixin, TestCase):
# The no template case doesn't mess with the template assertions
self.assertTemplateNotUsed(response, "GET Template")
try:
msg = "No templates used to render the response"
with self.assertRaisesMessage(AssertionError, msg):
self.assertTemplateUsed(response, "GET Template")
except AssertionError as e:
self.assertIn("No templates used to render the response", str(e))
try:
msg = "No templates used to render the response"
with self.assertRaisesMessage(AssertionError, msg):
self.assertTemplateUsed(response, "GET Template", msg_prefix="abc")
except AssertionError as e:
self.assertIn("abc: No templates used to render the response", str(e))
msg = "No templates used to render the response"
with self.assertRaisesMessage(AssertionError, msg):
@ -400,23 +398,19 @@ class AssertRedirectsTests(ExtraAssertMixin, SimpleTestCase):
"""
# This page will redirect with code 301, not 302
response = self.client.get("/permanent_redirect_view/")
try:
msg = (
"Response didn't redirect as expected: Response code was 301 "
"(expected 302)"
)
with self.assertRaisesMessage(AssertionError, msg):
self.assertRedirects(response, "/get_view/")
except AssertionError as e:
self.assertIn(
"Response didn't redirect as expected: Response code was 301 "
"(expected 302)",
str(e),
)
try:
msg = (
"abc: Response didn't redirect as expected: Response code was 301 "
"(expected 302)"
)
with self.assertRaisesMessage(AssertionError, msg):
self.assertRedirects(response, "/get_view/", msg_prefix="abc")
except AssertionError as e:
self.assertIn(
"abc: Response didn't redirect as expected: Response code was 301 "
"(expected 302)",
str(e),
)
def test_followed_redirect_unexpected_initial_status_code(self):
response = self.client.get("/permanent_redirect_view/", follow=True)
@ -452,35 +446,25 @@ class AssertRedirectsTests(ExtraAssertMixin, SimpleTestCase):
parameters.
"""
response = self.client.get("/redirect_view/", {"var": "value"})
try:
msg = "Response redirected to '/get_view/?var=value', expected '/get_view/'"
with self.assertRaisesMessage(AssertionError, msg):
self.assertRedirects(response, "/get_view/")
except AssertionError as e:
self.assertIn(
"Response redirected to '/get_view/?var=value', expected '/get_view/'",
str(e),
)
try:
msg = (
"abc: Response redirected to '/get_view/?var=value', expected '/get_view/'"
)
with self.assertRaisesMessage(AssertionError, msg):
self.assertRedirects(response, "/get_view/", msg_prefix="abc")
except AssertionError as e:
self.assertIn(
"abc: Response redirected to '/get_view/?var=value', expected "
"'/get_view/'",
str(e),
)
def test_incorrect_target(self):
"An assertion is raised if the response redirects to another target"
response = self.client.get("/permanent_redirect_view/")
try:
msg = (
"Response didn't redirect as expected: Response code was 301 (expected 302)"
)
with self.assertRaisesMessage(AssertionError, msg):
# Should redirect to get_view
self.assertRedirects(response, "/some_view/")
except AssertionError as e:
self.assertIn(
"Response didn't redirect as expected: Response code was 301 "
"(expected 302)",
str(e),
)
def test_target_page(self):
"""
@ -488,27 +472,23 @@ class AssertRedirectsTests(ExtraAssertMixin, SimpleTestCase):
retrieved as expected.
"""
response = self.client.get("/double_redirect_view/")
try:
msg = (
"Couldn't retrieve redirection page '/permanent_redirect_view/': "
"response code was 301 (expected 200)"
)
with self.assertRaisesMessage(AssertionError, msg):
# The redirect target responds with a 301 code, not 200
self.assertRedirects(response, "http://testserver/permanent_redirect_view/")
except AssertionError as e:
self.assertIn(
"Couldn't retrieve redirection page '/permanent_redirect_view/': "
"response code was 301 (expected 200)",
str(e),
)
try:
msg = (
"abc: Couldn't retrieve redirection page '/permanent_redirect_view/': "
"response code was 301 (expected 200)"
)
with self.assertRaisesMessage(AssertionError, msg):
# The redirect target responds with a 301 code, not 200
self.assertRedirects(
response, "http://testserver/permanent_redirect_view/", msg_prefix="abc"
)
except AssertionError as e:
self.assertIn(
"abc: Couldn't retrieve redirection page '/permanent_redirect_view/': "
"response code was 301 (expected 200)",
str(e),
)
def test_redirect_chain(self):
"You can follow a redirect chain of multiple redirects"
@ -632,23 +612,18 @@ class AssertRedirectsTests(ExtraAssertMixin, SimpleTestCase):
"""
# This page will redirect with code 301, not 302
response = self.client.get("/get_view/", follow=True)
try:
msg = (
"Response didn't redirect as expected: Response code was 200 (expected 302)"
)
with self.assertRaisesMessage(AssertionError, msg):
self.assertRedirects(response, "/get_view/")
except AssertionError as e:
self.assertIn(
"Response didn't redirect as expected: Response code was 200 "
"(expected 302)",
str(e),
)
try:
msg = (
"abc: Response didn't redirect as expected: Response code was 200 "
"(expected 302)"
)
with self.assertRaisesMessage(AssertionError, msg):
self.assertRedirects(response, "/get_view/", msg_prefix="abc")
except AssertionError as e:
self.assertIn(
"abc: Response didn't redirect as expected: Response code was 200 "
"(expected 302)",
str(e),
)
def test_redirect_on_non_redirect_page(self):
"""
@ -657,23 +632,18 @@ class AssertRedirectsTests(ExtraAssertMixin, SimpleTestCase):
"""
# This page will redirect with code 301, not 302
response = self.client.get("/get_view/")
try:
msg = (
"Response didn't redirect as expected: Response code was 200 (expected 302)"
)
with self.assertRaisesMessage(AssertionError, msg):
self.assertRedirects(response, "/get_view/")
except AssertionError as e:
self.assertIn(
"Response didn't redirect as expected: Response code was 200 "
"(expected 302)",
str(e),
)
try:
msg = (
"abc: Response didn't redirect as expected: Response code was 200 "
"(expected 302)"
)
with self.assertRaisesMessage(AssertionError, msg):
self.assertRedirects(response, "/get_view/", msg_prefix="abc")
except AssertionError as e:
self.assertIn(
"abc: Response didn't redirect as expected: Response code was 200 "
"(expected 302)",
str(e),
)
def test_redirect_scheme(self):
"""