Ticket #17194: django-17194-localise-auth-tests.patch

File django-17194-localise-auth-tests.patch, 15.8 KB (added by Bas Peschier, 13 years ago)
  • django/contrib/auth/forms.py

    diff -r b33d4705456a django/contrib/auth/forms.py
    a b  
    5252    """
    5353    username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$',
    5454        help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
    55         error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
     55        error_messages = {
     56            'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters."),
     57            'duplicate': _("A user with that username already exists."),
     58        })
    5659    password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
    5760    password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput,
    58         help_text = _("Enter the same password as above, for verification."))
     61        help_text = _("Enter the same password as above, for verification."),
     62        error_messages = {'mismatch': _("The two password fields didn't match.")})
    5963
    6064    class Meta:
    6165        model = User
     
    6771            User.objects.get(username=username)
    6872        except User.DoesNotExist:
    6973            return username
    70         raise forms.ValidationError(_("A user with that username already exists."))
     74        raise forms.ValidationError(self.fields['username'].error_messages['duplicate'])
    7175
    7276    def clean_password2(self):
    7377        password1 = self.cleaned_data.get("password1", "")
    7478        password2 = self.cleaned_data["password2"]
    7579        if password1 != password2:
    76             raise forms.ValidationError(_("The two password fields didn't match."))
     80            raise forms.ValidationError(self.fields['password2'].error_messages['mismatch'])
    7781        return password2
    7882
    7983    def save(self, commit=True):
     
    109113    username = forms.CharField(label=_("Username"), max_length=30)
    110114    password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
    111115
     116    error_messages = {
     117        'invalid_login': _("Please enter a correct username and password. Note that both fields are case-sensitive."),
     118        'inactive': _("This account is inactive."),
     119        'nocookies': _("Your Web browser doesn't appear to have cookies enabled. "
     120                      "Cookies are required for logging in."),
     121    }
     122
    112123    def __init__(self, request=None, *args, **kwargs):
    113124        """
    114125        If request is passed in, the form will validate that cookies are
     
    127138        if username and password:
    128139            self.user_cache = authenticate(username=username, password=password)
    129140            if self.user_cache is None:
    130                 raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
     141                raise forms.ValidationError(self.error_messages['invalid_login'])
    131142            elif not self.user_cache.is_active:
    132                 raise forms.ValidationError(_("This account is inactive."))
     143                raise forms.ValidationError(self.error_messages['inactive'])
    133144        self.check_for_test_cookie()
    134145        return self.cleaned_data
    135146
    136147    def check_for_test_cookie(self):
    137148        if self.request and not self.request.session.test_cookie_worked():
    138             raise forms.ValidationError(
    139                 _("Your Web browser doesn't appear to have cookies enabled. "
    140                   "Cookies are required for logging in."))
     149            raise forms.ValidationError(self.error_messages['nocookies'])
    141150
    142151    def get_user_id(self):
    143152        if self.user_cache:
     
    148157        return self.user_cache
    149158
    150159class PasswordResetForm(forms.Form):
    151     email = forms.EmailField(label=_("E-mail"), max_length=75)
     160    email = forms.EmailField(label=_("E-mail"), max_length=75,
     161                error_messages={
     162                    'unknown': _("That e-mail address doesn't have an associated user account. "
     163                                 "Are you sure you've registered?"),
     164                    'unusable': _("The user account associated with this e-mail address cannot reset the password."),
     165                })
    152166
    153167    def clean_email(self):
    154168        """
     
    159173                                email__iexact=email,
    160174                                is_active=True)
    161175        if not len(self.users_cache):
    162             raise forms.ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've registered?"))
     176            raise forms.ValidationError(self.fields['email'].error_messages['unknown'])
    163177        if any((user.password == UNUSABLE_PASSWORD) for user in self.users_cache):
    164             raise forms.ValidationError(_("The user account associated with this e-mail address cannot reset the password."))
     178            raise forms.ValidationError(self.fields['email'].error_messages['unusable'])
    165179        return email
    166180
    167181    def save(self, domain_override=None,
     
    201215    entering the old password
    202216    """
    203217    new_password1 = forms.CharField(label=_("New password"), widget=forms.PasswordInput)
    204     new_password2 = forms.CharField(label=_("New password confirmation"), widget=forms.PasswordInput)
     218    new_password2 = forms.CharField(label=_("New password confirmation"),
     219        widget=forms.PasswordInput,
     220        error_messages={'mismatch': _("The two password fields didn't match."), })
    205221
    206222    def __init__(self, user, *args, **kwargs):
    207223        self.user = user
     
    212228        password2 = self.cleaned_data.get('new_password2')
    213229        if password1 and password2:
    214230            if password1 != password2:
    215                 raise forms.ValidationError(_("The two password fields didn't match."))
     231                raise forms.ValidationError(self.fields['new_password2'].error_messages['mismatch'])
    216232        return password2
    217233
    218234    def save(self, commit=True):
     
    226242    A form that lets a user change his/her password by entering
    227243    their old password.
    228244    """
    229     old_password = forms.CharField(label=_("Old password"), widget=forms.PasswordInput)
     245    old_password = forms.CharField(label=_("Old password"), widget=forms.PasswordInput,
     246        error_messages={'incorrect': _("Your old password was entered incorrectly. Please enter it again.")})
    230247
    231248    def clean_old_password(self):
    232249        """
     
    234251        """
    235252        old_password = self.cleaned_data["old_password"]
    236253        if not self.user.check_password(old_password):
    237             raise forms.ValidationError(_("Your old password was entered incorrectly. Please enter it again."))
     254            raise forms.ValidationError(self.fields['old_password'].error_messages['incorrect'])
    238255        return old_password
    239256PasswordChangeForm.base_fields.keyOrder = ['old_password', 'new_password1', 'new_password2']
    240257
  • django/contrib/auth/tests/forms.py

    diff -r b33d4705456a django/contrib/auth/tests/forms.py
    a b  
    11from __future__ import with_statement
    22import os
    33from django.core import mail
     4from django.forms.fields import Field, EmailField
    45from django.contrib.auth.models import User
    56from django.contrib.auth.forms import UserCreationForm, AuthenticationForm,  PasswordChangeForm, SetPasswordForm, UserChangeForm, PasswordResetForm
     7from django.utils.encoding import force_unicode
    68from django.test import TestCase
    79
    810
     
    1921        form = UserCreationForm(data)
    2022        self.assertFalse(form.is_valid())
    2123        self.assertEqual(form["username"].errors,
    22                          [u'A user with that username already exists.'])
     24            [force_unicode(form.fields['username'].error_messages['duplicate']),])
    2325
    2426    def test_invalid_data(self):
    2527        data = {
     
    3032        form = UserCreationForm(data)
    3133        self.assertFalse(form.is_valid())
    3234        self.assertEqual(form["username"].errors,
    33                          [u'This value may contain only letters, numbers and @/./+/-/_ characters.'])
    34 
     35            [force_unicode(form.fields['username'].error_messages['invalid']),])
    3536
    3637    def test_password_verification(self):
    3738        # The verification password is incorrect.
     
    4344        form = UserCreationForm(data)
    4445        self.assertFalse(form.is_valid())
    4546        self.assertEqual(form["password2"].errors,
    46                          [u"The two password fields didn't match."])
    47 
     47            [force_unicode(form.fields['password2'].error_messages['mismatch']),])
    4848
    4949    def test_both_passwords(self):
    5050        # One (or both) passwords weren't given
     
    5252        form = UserCreationForm(data)
    5353        self.assertFalse(form.is_valid())
    5454        self.assertEqual(form['password1'].errors,
    55                          [u'This field is required.'])
     55            [force_unicode(Field.default_error_messages['required']),])
    5656        self.assertEqual(form['password2'].errors,
    57                          [u'This field is required.'])
    58 
     57            [force_unicode(Field.default_error_messages['required']),])
    5958
    6059        data['password2'] = 'test123'
    6160        form = UserCreationForm(data)
    6261        self.assertFalse(form.is_valid())
    6362        self.assertEqual(form['password1'].errors,
    64                          [u'This field is required.'])
     63            [force_unicode(Field.default_error_messages['required']),])
    6564
    6665    def test_success(self):
    6766        # The success case.
     
    9190        form = AuthenticationForm(None, data)
    9291        self.assertFalse(form.is_valid())
    9392        self.assertEqual(form.non_field_errors(),
    94                          [u'Please enter a correct username and password. Note that both fields are case-sensitive.'])
     93            [force_unicode(form.error_messages['invalid_login']),])
    9594
    9695    def test_inactive_user(self):
    9796        # The user is inactive.
     
    102101        form = AuthenticationForm(None, data)
    103102        self.assertFalse(form.is_valid())
    104103        self.assertEqual(form.non_field_errors(),
    105                          [u'This account is inactive.'])
    106 
     104            [force_unicode(form.error_messages['inactive']),])
    107105
    108106    def test_success(self):
    109107        # The success case
     
    130128        form = SetPasswordForm(user, data)
    131129        self.assertFalse(form.is_valid())
    132130        self.assertEqual(form["new_password2"].errors,
    133                          [u"The two password fields didn't match."])
     131            [force_unicode(form.fields['new_password2'].error_messages['mismatch']),])
    134132
    135133    def test_success(self):
    136134        user = User.objects.get(username='testclient')
     
    156154        form = PasswordChangeForm(user, data)
    157155        self.assertFalse(form.is_valid())
    158156        self.assertEqual(form["old_password"].errors,
    159                          [u'Your old password was entered incorrectly. Please enter it again.'])
    160 
     157            [force_unicode(form.fields['old_password'].error_messages['incorrect']),])
    161158
    162159    def test_password_verification(self):
    163160        # The two new passwords do not match.
     
    170167        form = PasswordChangeForm(user, data)
    171168        self.assertFalse(form.is_valid())
    172169        self.assertEqual(form["new_password2"].errors,
    173                          [u"The two password fields didn't match."])
    174 
     170            [force_unicode(form.fields['new_password2'].error_messages['mismatch']),])
    175171
    176172    def test_success(self):
    177173        # The success case.
     
    200196        form = UserChangeForm(data, instance=user)
    201197        self.assertFalse(form.is_valid())
    202198        self.assertEqual(form['username'].errors,
    203                          [u'This value may contain only letters, numbers and @/./+/-/_ characters.'])
     199            [force_unicode(form.fields['username'].error_messages['invalid']),])
    204200
    205201    def test_bug_14242(self):
    206202        # A regression test, introduce by adding an optimization for the
     
    236232        form = PasswordResetForm(data)
    237233        self.assertFalse(form.is_valid())
    238234        self.assertEqual(form['email'].errors,
    239                          [u'Enter a valid e-mail address.'])
     235            [force_unicode(EmailField.default_error_messages['invalid']),])
    240236
    241237    def test_nonexistant_email(self):
    242238        # Test nonexistant email address
     
    244240        form = PasswordResetForm(data)
    245241        self.assertFalse(form.is_valid())
    246242        self.assertEqual(form.errors,
    247                          {'email': [u"That e-mail address doesn't have an associated user account. Are you sure you've registered?"]})
     243            {'email': [force_unicode(form.fields['email'].error_messages['unknown']),]})
    248244
    249245    def test_cleaned_data(self):
    250246        # Regression test
  • django/contrib/auth/tests/views.py

    diff -r b33d4705456a django/contrib/auth/tests/views.py
    a b  
    55
    66from django.conf import settings
    77from django.contrib.auth import SESSION_KEY, REDIRECT_FIELD_NAME
    8 from django.contrib.auth.forms import AuthenticationForm
     8from django.contrib.auth.forms import (AuthenticationForm, PasswordChangeForm,
     9                SetPasswordForm, AuthenticationForm, PasswordResetForm, )
    910from django.contrib.sites.models import Site, RequestSite
    1011from django.contrib.auth.models import User
    1112from django.core.urlresolvers import NoReverseMatch
     13from django.utils.html import escape
     14from django.utils.encoding import force_unicode
    1215from django.test import TestCase
    1316from django.core import mail
    1417from django.core.urlresolvers import reverse
    1518from django.http import QueryDict
    1619
     20def _escape(proxy):
     21    """Force proxy to unicode and escape"""
     22    return escape(force_unicode(proxy))
    1723
    1824class AuthViewsTestCase(TestCase):
    1925    """
     
    8086        response = self.client.get('/password_reset/')
    8187        self.assertEqual(response.status_code, 200)
    8288        response = self.client.post('/password_reset/', {'email': 'not_a_real_email@email.com'})
    83         self.assertContains(response, "That e-mail address doesn't have an associated user account")
     89        self.assertContains(response, _escape(PasswordResetForm.base_fields['email'].error_messages['unknown']))
    8490        self.assertEqual(len(mail.outbox), 0)
    8591
    8692    def test_email_found(self):
     
    171177        response = self.client.post(path, {'new_password1': 'anewpassword',
    172178                                           'new_password2':' x'})
    173179        self.assertEqual(response.status_code, 200)
    174         self.assertTrue("The two password fields didn't match" in response.content)
     180        self.assertTrue(_escape(SetPasswordForm.base_fields['new_password2'].error_messages['mismatch']) in response.content)
    175181
    176182class ChangePasswordTest(AuthViewsTestCase):
    177183
     
    182188            }
    183189        )
    184190        self.assertEqual(response.status_code, 200)
    185         self.assertTrue("Please enter a correct username and password. Note that both fields are case-sensitive." in response.content)
     191        self.assertTrue(_escape(AuthenticationForm.error_messages['invalid_login']) in response.content)
    186192
    187193    def logout(self):
    188194        response = self.client.get('/logout/')
     
    196202            }
    197203        )
    198204        self.assertEqual(response.status_code, 200)
    199         self.assertTrue("Your old password was entered incorrectly. Please enter it again." in response.content)
     205        self.assertTrue(_escape(PasswordChangeForm.base_fields['old_password'].error_messages['incorrect']) in response.content)
    200206
    201207    def test_password_change_fails_with_mismatched_passwords(self):
    202208        self.login()
     
    207213            }
    208214        )
    209215        self.assertEqual(response.status_code, 200)
    210         self.assertTrue("The two password fields didn't match." in response.content)
     216        self.assertTrue(_escape(SetPasswordForm.base_fields['new_password2'].error_messages['mismatch']) in response.content)
    211217
    212218    def test_password_change_succeeds(self):
    213219        self.login()
Back to Top