diff options
| author | Loic Bistuer <loic.bistuer@gmail.com> | 2014-03-23 01:08:04 +0700 |
|---|---|---|
| committer | Tim Graham <timograham@gmail.com> | 2014-03-24 07:21:32 -0400 |
| commit | 7ac8380799eedb374621317b62ccf026d86ea245 (patch) | |
| tree | 45f289c8ed60df14ce6ca2312f6ad5232b85480e /tests | |
| parent | 3f7615cddc69235d466fb680fb05869f2a80d1e4 (diff) | |
Fixed #22318 -- Added Form.has_error() to easily check if a given error has happened.
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/forms_tests/tests/test_forms.py | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py index c05c79a68e..6b90390159 100644 --- a/tests/forms_tests/tests/test_forms.py +++ b/tests/forms_tests/tests/test_forms.py @@ -6,6 +6,7 @@ import datetime import json import warnings +from django.core.exceptions import NON_FIELD_ERRORS from django.core.files.uploadedfile import SimpleUploadedFile from django.core.validators import RegexValidator from django.forms import ( @@ -739,6 +740,39 @@ class FormsTestCase(TestCase): with six.assertRaisesRegex(self, ValueError, "has no field named"): f.add_error('missing_field', 'Some error.') + def test_has_error(self): + class UserRegistration(Form): + username = CharField(max_length=10) + password1 = CharField(widget=PasswordInput, min_length=5) + password2 = CharField(widget=PasswordInput) + + def clean(self): + if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') + and self.cleaned_data['password1'] != self.cleaned_data['password2']): + raise ValidationError( + 'Please make sure your passwords match.', + code='password_mismatch', + ) + + f = UserRegistration(data={}) + self.assertTrue(f.has_error('password1')) + self.assertTrue(f.has_error('password1', 'required')) + self.assertFalse(f.has_error('password1', 'anything')) + + f = UserRegistration(data={'password1': 'Hi', 'password2': 'Hi'}) + self.assertTrue(f.has_error('password1')) + self.assertTrue(f.has_error('password1', 'min_length')) + self.assertFalse(f.has_error('password1', 'anything')) + self.assertFalse(f.has_error('password2')) + self.assertFalse(f.has_error('password2', 'anything')) + + f = UserRegistration(data={'password1': 'Bonjour', 'password2': 'Hello'}) + self.assertFalse(f.has_error('password1')) + self.assertFalse(f.has_error('password1', 'required')) + self.assertTrue(f.has_error(NON_FIELD_ERRORS)) + self.assertTrue(f.has_error(NON_FIELD_ERRORS, 'password_mismatch')) + self.assertFalse(f.has_error(NON_FIELD_ERRORS, 'anything')) + def test_dynamic_construction(self): # It's possible to construct a Form dynamically by adding to the self.fields # dictionary in __init__(). Don't forget to call Form.__init__() within the |
