Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #17194 -- Made sure the auth form tests work if a language othe…

…r than English is activated by moving the error message translation strings into class level dictionaries. Many thanks to Claude Paroz, rabio and Bas Peschier for their initial work on this.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@17204 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 5df31c0164e9477a3ebb6b1bbde8604e06fbefd4 1 parent e7b5e22
Jannis Leidel authored December 15, 2011
58  django/contrib/auth/forms.py
@@ -15,6 +15,7 @@
15 15
 
16 16
 mask_password = lambda p: "%s%s" % (p[:UNMASKED_DIGITS_TO_SHOW], "*" * max(len(p) - UNMASKED_DIGITS_TO_SHOW, 0))
17 17
 
  18
+
18 19
 class ReadOnlyPasswordHashWidget(forms.Widget):
19 20
     def render(self, name, value, attrs):
20 21
         if not value:
@@ -39,6 +40,7 @@ def render(self, name, value, attrs):
39 40
                     "masked": masked,
40 41
                 })
41 42
 
  43
+
42 44
 class ReadOnlyPasswordHashField(forms.Field):
43 45
     widget = ReadOnlyPasswordHashWidget
44 46
 
@@ -46,10 +48,15 @@ def __init__(self, *args, **kwargs):
46 48
         kwargs.setdefault("required", False)
47 49
         super(ReadOnlyPasswordHashField, self).__init__(*args, **kwargs)
48 50
 
  51
+
49 52
 class UserCreationForm(forms.ModelForm):
50 53
     """
51 54
     A form that creates a user, with no privileges, from the given username and password.
52 55
     """
  56
+    error_messages = {
  57
+        'duplicate_username': _("A user with that username already exists."),
  58
+        'password_mismatch': _("The two password fields didn't match."),
  59
+    }
53 60
     username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$',
54 61
         help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
55 62
         error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
@@ -67,13 +74,13 @@ def clean_username(self):
67 74
             User.objects.get(username=username)
68 75
         except User.DoesNotExist:
69 76
             return username
70  
-        raise forms.ValidationError(_("A user with that username already exists."))
  77
+        raise forms.ValidationError(self.error_messages['duplicate_username'])
71 78
 
72 79
     def clean_password2(self):
73 80
         password1 = self.cleaned_data.get("password1", "")
74 81
         password2 = self.cleaned_data["password2"]
75 82
         if password1 != password2:
76  
-            raise forms.ValidationError(_("The two password fields didn't match."))
  83
+            raise forms.ValidationError(self.error_messages['password_mismatch'])
77 84
         return password2
78 85
 
79 86
     def save(self, commit=True):
@@ -83,6 +90,7 @@ def save(self, commit=True):
83 90
             user.save()
84 91
         return user
85 92
 
  93
+
86 94
 class UserChangeForm(forms.ModelForm):
87 95
     username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$',
88 96
         help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
@@ -101,6 +109,7 @@ def __init__(self, *args, **kwargs):
101 109
         if f is not None:
102 110
             f.queryset = f.queryset.select_related('content_type')
103 111
 
  112
+
104 113
 class AuthenticationForm(forms.Form):
105 114
     """
106 115
     Base class for authenticating users. Extend this to get a form that accepts
@@ -109,6 +118,14 @@ class AuthenticationForm(forms.Form):
109 118
     username = forms.CharField(label=_("Username"), max_length=30)
110 119
     password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
111 120
 
  121
+    error_messages = {
  122
+        'invalid_login': _("Please enter a correct username and password. "
  123
+                           "Note that both fields are case-sensitive."),
  124
+        'no_cookies': _("Your Web browser doesn't appear to have cookies "
  125
+                        "enabled. Cookies are required for logging in."),
  126
+        'inactive': _("This account is inactive."),
  127
+    }
  128
+
112 129
     def __init__(self, request=None, *args, **kwargs):
113 130
         """
114 131
         If request is passed in, the form will validate that cookies are
@@ -127,17 +144,15 @@ def clean(self):
127 144
         if username and password:
128 145
             self.user_cache = authenticate(username=username, password=password)
129 146
             if self.user_cache is None:
130  
-                raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
  147
+                raise forms.ValidationError(self.error_messages['invalid_login'])
131 148
             elif not self.user_cache.is_active:
132  
-                raise forms.ValidationError(_("This account is inactive."))
  149
+                raise forms.ValidationError(self.error_messages['inactive'])
133 150
         self.check_for_test_cookie()
134 151
         return self.cleaned_data
135 152
 
136 153
     def check_for_test_cookie(self):
137 154
         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."))
  155
+            raise forms.ValidationError(self.error_messages['no_cookies'])
141 156
 
142 157
     def get_user_id(self):
143 158
         if self.user_cache:
@@ -147,7 +162,14 @@ def get_user_id(self):
147 162
     def get_user(self):
148 163
         return self.user_cache
149 164
 
  165
+
150 166
 class PasswordResetForm(forms.Form):
  167
+    error_messages = {
  168
+        'unknown': _("That e-mail address doesn't have an associated "
  169
+                     "user account. Are you sure you've registered?"),
  170
+        'unusable': _("The user account associated with this e-mail "
  171
+                      "address cannot reset the password."),
  172
+    }
151 173
     email = forms.EmailField(label=_("E-mail"), max_length=75)
152 174
 
153 175
     def clean_email(self):
@@ -159,9 +181,9 @@ def clean_email(self):
159 181
                                 email__iexact=email,
160 182
                                 is_active=True)
161 183
         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?"))
  184
+            raise forms.ValidationError(self.error_messages['unknown'])
163 185
         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."))
  186
+            raise forms.ValidationError(self.error_messages['unusable'])
165 187
         return email
166 188
 
167 189
     def save(self, domain_override=None,
@@ -195,11 +217,15 @@ def save(self, domain_override=None,
195 217
             email = loader.render_to_string(email_template_name, c)
196 218
             send_mail(subject, email, from_email, [user.email])
197 219
 
  220
+
198 221
 class SetPasswordForm(forms.Form):
199 222
     """
200 223
     A form that lets a user change set his/her password without
201 224
     entering the old password
202 225
     """
  226
+    error_messages = {
  227
+        'password_mismatch': _("The two password fields didn't match."),
  228
+    }
203 229
     new_password1 = forms.CharField(label=_("New password"), widget=forms.PasswordInput)
204 230
     new_password2 = forms.CharField(label=_("New password confirmation"), widget=forms.PasswordInput)
205 231
 
@@ -212,7 +238,7 @@ def clean_new_password2(self):
212 238
         password2 = self.cleaned_data.get('new_password2')
213 239
         if password1 and password2:
214 240
             if password1 != password2:
215  
-                raise forms.ValidationError(_("The two password fields didn't match."))
  241
+                raise forms.ValidationError(self.error_messages['password_mismatch'])
216 242
         return password2
217 243
 
218 244
     def save(self, commit=True):
@@ -221,11 +247,15 @@ def save(self, commit=True):
221 247
             self.user.save()
222 248
         return self.user
223 249
 
  250
+
224 251
 class PasswordChangeForm(SetPasswordForm):
225 252
     """
226 253
     A form that lets a user change his/her password by entering
227 254
     their old password.
228 255
     """
  256
+    error_messages = dict(SetPasswordForm.error_messages, **{
  257
+        'password_incorrect': _("Your old password was entered incorrectly. Please enter it again."),
  258
+    })
229 259
     old_password = forms.CharField(label=_("Old password"), widget=forms.PasswordInput)
230 260
 
231 261
     def clean_old_password(self):
@@ -234,14 +264,18 @@ def clean_old_password(self):
234 264
         """
235 265
         old_password = self.cleaned_data["old_password"]
236 266
         if not self.user.check_password(old_password):
237  
-            raise forms.ValidationError(_("Your old password was entered incorrectly. Please enter it again."))
  267
+            raise forms.ValidationError(self.error_messages['password_incorrect'])
238 268
         return old_password
239 269
 PasswordChangeForm.base_fields.keyOrder = ['old_password', 'new_password1', 'new_password2']
240 270
 
  271
+
241 272
 class AdminPasswordChangeForm(forms.Form):
242 273
     """
243 274
     A form used to change the password of a user in the admin interface.
244 275
     """
  276
+    error_messages = {
  277
+        'password_mismatch': _("The two password fields didn't match."),
  278
+    }
245 279
     password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
246 280
     password2 = forms.CharField(label=_("Password (again)"), widget=forms.PasswordInput)
247 281
 
@@ -254,7 +288,7 @@ def clean_password2(self):
254 288
         password2 = self.cleaned_data.get('password2')
255 289
         if password1 and password2:
256 290
             if password1 != password2:
257  
-                raise forms.ValidationError(_("The two password fields didn't match."))
  291
+                raise forms.ValidationError(self.error_messages['password_mismatch'])
258 292
         return password2
259 293
 
260 294
     def save(self, commit=True):
60  django/contrib/auth/tests/forms.py
... ...
@@ -1,9 +1,12 @@
1 1
 from __future__ import with_statement
2 2
 import os
3 3
 from django.core import mail
  4
+from django.forms.fields import Field, EmailField
4 5
 from django.contrib.auth.models import User
5 6
 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm,  PasswordChangeForm, SetPasswordForm, UserChangeForm, PasswordResetForm
6 7
 from django.test import TestCase
  8
+from django.utils.encoding import force_unicode
  9
+from django.utils import translation
7 10
 
8 11
 
9 12
 class UserCreationFormTest(TestCase):
@@ -19,7 +22,7 @@ def test_user_already_exists(self):
19 22
         form = UserCreationForm(data)
20 23
         self.assertFalse(form.is_valid())
21 24
         self.assertEqual(form["username"].errors,
22  
-                         [u'A user with that username already exists.'])
  25
+                         [force_unicode(form.error_messages['duplicate_username'])])
23 26
 
24 27
     def test_invalid_data(self):
25 28
         data = {
@@ -30,8 +33,7 @@ def test_invalid_data(self):
30 33
         form = UserCreationForm(data)
31 34
         self.assertFalse(form.is_valid())
32 35
         self.assertEqual(form["username"].errors,
33  
-                         [u'This value may contain only letters, numbers and @/./+/-/_ characters.'])
34  
-
  36
+                         [force_unicode(form.fields['username'].error_messages['invalid'])])
35 37
 
36 38
     def test_password_verification(self):
37 39
         # The verification password is incorrect.
@@ -43,25 +45,21 @@ def test_password_verification(self):
43 45
         form = UserCreationForm(data)
44 46
         self.assertFalse(form.is_valid())
45 47
         self.assertEqual(form["password2"].errors,
46  
-                         [u"The two password fields didn't match."])
47  
-
  48
+                         [force_unicode(form.error_messages['password_mismatch'])])
48 49
 
49 50
     def test_both_passwords(self):
50 51
         # One (or both) passwords weren't given
51 52
         data = {'username': 'jsmith'}
52 53
         form = UserCreationForm(data)
  54
+        required_error = [force_unicode(Field.default_error_messages['required'])]
53 55
         self.assertFalse(form.is_valid())
54  
-        self.assertEqual(form['password1'].errors,
55  
-                         [u'This field is required.'])
56  
-        self.assertEqual(form['password2'].errors,
57  
-                         [u'This field is required.'])
58  
-
  56
+        self.assertEqual(form['password1'].errors, required_error)
  57
+        self.assertEqual(form['password2'].errors, required_error)
59 58
 
60 59
         data['password2'] = 'test123'
61 60
         form = UserCreationForm(data)
62 61
         self.assertFalse(form.is_valid())
63  
-        self.assertEqual(form['password1'].errors,
64  
-                         [u'This field is required.'])
  62
+        self.assertEqual(form['password1'].errors, required_error)
65 63
 
66 64
     def test_success(self):
67 65
         # The success case.
@@ -91,7 +89,7 @@ def test_invalid_username(self):
91 89
         form = AuthenticationForm(None, data)
92 90
         self.assertFalse(form.is_valid())
93 91
         self.assertEqual(form.non_field_errors(),
94  
-                         [u'Please enter a correct username and password. Note that both fields are case-sensitive.'])
  92
+                         [force_unicode(form.error_messages['invalid_login'])])
95 93
 
96 94
     def test_inactive_user(self):
97 95
         # The user is inactive.
@@ -102,8 +100,20 @@ def test_inactive_user(self):
102 100
         form = AuthenticationForm(None, data)
103 101
         self.assertFalse(form.is_valid())
104 102
         self.assertEqual(form.non_field_errors(),
105  
-                         [u'This account is inactive.'])
106  
-
  103
+                         [force_unicode(form.error_messages['inactive'])])
  104
+
  105
+    def test_inactive_user_i18n(self):
  106
+        with self.settings(USE_I18N=True):
  107
+            with translation.override('pt-br', deactivate=True):
  108
+                # The user is inactive.
  109
+                data = {
  110
+                    'username': 'inactive',
  111
+                    'password': 'password',
  112
+                    }
  113
+                form = AuthenticationForm(None, data)
  114
+                self.assertFalse(form.is_valid())
  115
+                self.assertEqual(form.non_field_errors(),
  116
+                                 [force_unicode(form.error_messages['inactive'])])
107 117
 
108 118
     def test_success(self):
109 119
         # The success case
@@ -130,7 +140,7 @@ def test_password_verification(self):
130 140
         form = SetPasswordForm(user, data)
131 141
         self.assertFalse(form.is_valid())
132 142
         self.assertEqual(form["new_password2"].errors,
133  
-                         [u"The two password fields didn't match."])
  143
+                         [force_unicode(form.error_messages['password_mismatch'])])
134 144
 
135 145
     def test_success(self):
136 146
         user = User.objects.get(username='testclient')
@@ -156,8 +166,7 @@ def test_incorrect_password(self):
156 166
         form = PasswordChangeForm(user, data)
157 167
         self.assertFalse(form.is_valid())
158 168
         self.assertEqual(form["old_password"].errors,
159  
-                         [u'Your old password was entered incorrectly. Please enter it again.'])
160  
-
  169
+                         [force_unicode(form.error_messages['password_incorrect'])])
161 170
 
162 171
     def test_password_verification(self):
163 172
         # The two new passwords do not match.
@@ -170,8 +179,7 @@ def test_password_verification(self):
170 179
         form = PasswordChangeForm(user, data)
171 180
         self.assertFalse(form.is_valid())
172 181
         self.assertEqual(form["new_password2"].errors,
173  
-                         [u"The two password fields didn't match."])
174  
-
  182
+                         [force_unicode(form.error_messages['password_mismatch'])])
175 183
 
176 184
     def test_success(self):
177 185
         # The success case.
@@ -190,6 +198,7 @@ def test_field_order(self):
190 198
         self.assertEqual(PasswordChangeForm(user, {}).fields.keys(),
191 199
                          ['old_password', 'new_password1', 'new_password2'])
192 200
 
  201
+
193 202
 class UserChangeFormTest(TestCase):
194 203
 
195 204
     fixtures = ['authtestdata.json']
@@ -200,7 +209,7 @@ def test_username_validity(self):
200 209
         form = UserChangeForm(data, instance=user)
201 210
         self.assertFalse(form.is_valid())
202 211
         self.assertEqual(form['username'].errors,
203  
-                         [u'This value may contain only letters, numbers and @/./+/-/_ characters.'])
  212
+                         [force_unicode(form.fields['username'].error_messages['invalid'])])
204 213
 
205 214
     def test_bug_14242(self):
206 215
         # A regression test, introduce by adding an optimization for the
@@ -232,19 +241,19 @@ def create_dummy_user(self):
232 241
         return (user, username, email)
233 242
 
234 243
     def test_invalid_email(self):
235  
-        data = {'email':'not valid'}
  244
+        data = {'email': 'not valid'}
236 245
         form = PasswordResetForm(data)
237 246
         self.assertFalse(form.is_valid())
238 247
         self.assertEqual(form['email'].errors,
239  
-                         [u'Enter a valid e-mail address.'])
  248
+                         [force_unicode(EmailField.default_error_messages['invalid'])])
240 249
 
241 250
     def test_nonexistant_email(self):
242 251
         # Test nonexistant email address
243  
-        data = {'email':'foo@bar.com'}
  252
+        data = {'email': 'foo@bar.com'}
244 253
         form = PasswordResetForm(data)
245 254
         self.assertFalse(form.is_valid())
246 255
         self.assertEqual(form.errors,
247  
-                         {'email': [u"That e-mail address doesn't have an associated user account. Are you sure you've registered?"]})
  256
+                         {'email': [force_unicode(form.error_messages['unknown'])]})
248 257
 
249 258
     def test_cleaned_data(self):
250 259
         # Regression test
@@ -284,7 +293,6 @@ def test_inactive_user(self):
284 293
         form = PasswordResetForm({'email': email})
285 294
         self.assertFalse(form.is_valid())
286 295
 
287  
-
288 296
     def test_unusable_password(self):
289 297
         user = User.objects.create_user('testuser', 'test@example.com', 'test')
290 298
         data = {"email": "test@example.com"}
88  django/contrib/auth/tests/views.py
@@ -4,15 +4,18 @@
4 4
 import urllib
5 5
 
6 6
 from django.conf import settings
7  
-from django.contrib.auth import SESSION_KEY, REDIRECT_FIELD_NAME
8  
-from django.contrib.auth.forms import AuthenticationForm
9 7
 from django.contrib.sites.models import Site, RequestSite
10 8
 from django.contrib.auth.models import User
11  
-from django.core.urlresolvers import NoReverseMatch
12  
-from django.test import TestCase
13 9
 from django.core import mail
14  
-from django.core.urlresolvers import reverse
  10
+from django.core.urlresolvers import reverse, NoReverseMatch
15 11
 from django.http import QueryDict
  12
+from django.utils.encoding import force_unicode
  13
+from django.utils.html import escape
  14
+from django.test import TestCase
  15
+
  16
+from django.contrib.auth import SESSION_KEY, REDIRECT_FIELD_NAME
  17
+from django.contrib.auth.forms import (AuthenticationForm, PasswordChangeForm,
  18
+                SetPasswordForm, PasswordResetForm)
16 19
 
17 20
 
18 21
 class AuthViewsTestCase(TestCase):
@@ -40,13 +43,15 @@ def tearDown(self):
40 43
     def login(self, password='password'):
41 44
         response = self.client.post('/login/', {
42 45
             'username': 'testclient',
43  
-            'password': password
44  
-            }
45  
-        )
  46
+            'password': password,
  47
+            })
46 48
         self.assertEqual(response.status_code, 302)
47 49
         self.assertTrue(response['Location'].endswith(settings.LOGIN_REDIRECT_URL))
48 50
         self.assertTrue(SESSION_KEY in self.client.session)
49 51
 
  52
+    def assertContainsEscaped(self, response, text, **kwargs):
  53
+        return self.assertContains(response, escape(force_unicode(text)), **kwargs)
  54
+
50 55
 
51 56
 class AuthViewNamedURLTests(AuthViewsTestCase):
52 57
     urls = 'django.contrib.auth.urls'
@@ -80,7 +85,7 @@ def test_email_not_found(self):
80 85
         response = self.client.get('/password_reset/')
81 86
         self.assertEqual(response.status_code, 200)
82 87
         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")
  88
+        self.assertContainsEscaped(response, PasswordResetForm.error_messages['unknown'])
84 89
         self.assertEqual(len(mail.outbox), 0)
85 90
 
86 91
     def test_email_found(self):
@@ -121,7 +126,7 @@ def test_confirm_invalid(self):
121 126
         url, path = self._test_confirm_start()
122 127
         # Let's munge the token in the path, but keep the same length,
123 128
         # in case the URLconf will reject a different length.
124  
-        path = path[:-5] + ("0"*4) + path[-1]
  129
+        path = path[:-5] + ("0" * 4) + path[-1]
125 130
 
126 131
         response = self.client.get(path)
127 132
         self.assertEqual(response.status_code, 200)
@@ -143,10 +148,12 @@ def test_confirm_invalid_post(self):
143 148
         # Same as test_confirm_invalid, but trying
144 149
         # to do a POST instead.
145 150
         url, path = self._test_confirm_start()
146  
-        path = path[:-5] + ("0"*4) + path[-1]
  151
+        path = path[:-5] + ("0" * 4) + path[-1]
147 152
 
148  
-        response = self.client.post(path, {'new_password1': 'anewpassword',
149  
-                                           'new_password2':' anewpassword'})
  153
+        self.client.post(path, {
  154
+            'new_password1': 'anewpassword',
  155
+            'new_password2': ' anewpassword',
  156
+        })
150 157
         # Check the password has not been changed
151 158
         u = User.objects.get(email='staffmember@example.com')
152 159
         self.assertTrue(not u.check_password("anewpassword"))
@@ -169,20 +176,20 @@ def test_confirm_complete(self):
169 176
     def test_confirm_different_passwords(self):
170 177
         url, path = self._test_confirm_start()
171 178
         response = self.client.post(path, {'new_password1': 'anewpassword',
172  
-                                           'new_password2':' x'})
  179
+                                           'new_password2': 'x'})
173 180
         self.assertEqual(response.status_code, 200)
174  
-        self.assertTrue("The two password fields didn't match" in response.content)
  181
+        self.assertContainsEscaped(response, SetPasswordForm.error_messages['password_mismatch'])
  182
+
175 183
 
176 184
 class ChangePasswordTest(AuthViewsTestCase):
177 185
 
178 186
     def fail_login(self, password='password'):
179 187
         response = self.client.post('/login/', {
180 188
             'username': 'testclient',
181  
-            'password': password
182  
-            }
183  
-        )
  189
+            'password': password,
  190
+        })
184 191
         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)
  192
+        self.assertContainsEscaped(response, AuthenticationForm.error_messages['invalid_login'])
186 193
 
187 194
     def logout(self):
188 195
         response = self.client.get('/logout/')
@@ -193,10 +200,9 @@ def test_password_change_fails_with_invalid_old_password(self):
193 200
             'old_password': 'donuts',
194 201
             'new_password1': 'password1',
195 202
             'new_password2': 'password1',
196  
-            }
197  
-        )
  203
+        })
198 204
         self.assertEqual(response.status_code, 200)
199  
-        self.assertTrue("Your old password was entered incorrectly. Please enter it again." in response.content)
  205
+        self.assertContainsEscaped(response, PasswordChangeForm.error_messages['password_incorrect'])
200 206
 
201 207
     def test_password_change_fails_with_mismatched_passwords(self):
202 208
         self.login()
@@ -204,10 +210,9 @@ def test_password_change_fails_with_mismatched_passwords(self):
204 210
             'old_password': 'password',
205 211
             'new_password1': 'password1',
206 212
             'new_password2': 'donuts',
207  
-            }
208  
-        )
  213
+        })
209 214
         self.assertEqual(response.status_code, 200)
210  
-        self.assertTrue("The two password fields didn't match." in response.content)
  215
+        self.assertContainsEscaped(response, SetPasswordForm.error_messages['password_mismatch'])
211 216
 
212 217
     def test_password_change_succeeds(self):
213 218
         self.login()
@@ -215,8 +220,7 @@ def test_password_change_succeeds(self):
215 220
             'old_password': 'password',
216 221
             'new_password1': 'password1',
217 222
             'new_password2': 'password1',
218  
-            }
219  
-        )
  223
+        })
220 224
         self.assertEqual(response.status_code, 302)
221 225
         self.assertTrue(response['Location'].endswith('/password_change/done/'))
222 226
         self.fail_login()
@@ -228,8 +232,7 @@ def test_password_change_done_succeeds(self):
228 232
             'old_password': 'password',
229 233
             'new_password1': 'password1',
230 234
             'new_password2': 'password1',
231  
-            }
232  
-        )
  235
+        })
233 236
         self.assertEqual(response.status_code, 302)
234 237
         self.assertTrue(response['Location'].endswith('/password_change/done/'))
235 238
 
@@ -266,13 +269,12 @@ def test_security_check(self, password='password'):
266 269
             nasty_url = '%(url)s?%(next)s=%(bad_url)s' % {
267 270
                 'url': login_url,
268 271
                 'next': REDIRECT_FIELD_NAME,
269  
-                'bad_url': urllib.quote(bad_url)
  272
+                'bad_url': urllib.quote(bad_url),
270 273
             }
271 274
             response = self.client.post(nasty_url, {
272 275
                 'username': 'testclient',
273 276
                 'password': password,
274  
-                }
275  
-            )
  277
+            })
276 278
             self.assertEqual(response.status_code, 302)
277 279
             self.assertFalse(bad_url in response['Location'],
278 280
                              "%s should be blocked" % bad_url)
@@ -284,18 +286,16 @@ def test_security_check(self, password='password'):
284 286
                          'view/?param=//example.com',
285 287
                          'https:///',
286 288
                          '//testserver/',
287  
-                         '/url%20with%20spaces/', # see ticket #12534
288  
-                         ):
  289
+                         '/url%20with%20spaces/'):  # see ticket #12534
289 290
             safe_url = '%(url)s?%(next)s=%(good_url)s' % {
290 291
                 'url': login_url,
291 292
                 'next': REDIRECT_FIELD_NAME,
292  
-                'good_url': urllib.quote(good_url)
  293
+                'good_url': urllib.quote(good_url),
293 294
             }
294 295
             response = self.client.post(safe_url, {
295 296
                     'username': 'testclient',
296 297
                     'password': password,
297  
-                }
298  
-            )
  298
+            })
299 299
             self.assertEqual(response.status_code, 302)
300 300
             self.assertTrue(good_url in response['Location'],
301 301
                             "%s should be allowed" % good_url)
@@ -322,8 +322,8 @@ def test_standard_login_url(self):
322 322
         login_required_url = self.get_login_required_url(login_url)
323 323
         querystring = QueryDict('', mutable=True)
324 324
         querystring['next'] = '/login_required/'
325  
-        self.assertEqual(login_required_url,
326  
-             'http://testserver%s?%s' % (login_url, querystring.urlencode('/')))
  325
+        self.assertEqual(login_required_url, 'http://testserver%s?%s' %
  326
+                         (login_url, querystring.urlencode('/')))
327 327
 
328 328
     def test_remote_login_url(self):
329 329
         login_url = 'http://remote.example.com/login'
@@ -422,12 +422,11 @@ def test_security_check(self, password='password'):
422 422
         for bad_url in ('http://example.com',
423 423
                         'https://example.com',
424 424
                         'ftp://exampel.com',
425  
-                        '//example.com'
426  
-                        ):
  425
+                        '//example.com'):
427 426
             nasty_url = '%(url)s?%(next)s=%(bad_url)s' % {
428 427
                 'url': logout_url,
429 428
                 'next': REDIRECT_FIELD_NAME,
430  
-                'bad_url': urllib.quote(bad_url)
  429
+                'bad_url': urllib.quote(bad_url),
431 430
             }
432 431
             self.login()
433 432
             response = self.client.get(nasty_url)
@@ -443,12 +442,11 @@ def test_security_check(self, password='password'):
443 442
                          'view/?param=//example.com',
444 443
                          'https:///',
445 444
                          '//testserver/',
446  
-                         '/url%20with%20spaces/', # see ticket #12534
447  
-                         ):
  445
+                         '/url%20with%20spaces/'):  # see ticket #12534
448 446
             safe_url = '%(url)s?%(next)s=%(good_url)s' % {
449 447
                 'url': logout_url,
450 448
                 'next': REDIRECT_FIELD_NAME,
451  
-                'good_url': urllib.quote(good_url)
  449
+                'good_url': urllib.quote(good_url),
452 450
             }
453 451
             self.login()
454 452
             response = self.client.get(safe_url)

0 notes on commit 5df31c0

Please sign in to comment.
Something went wrong with that request. Please try again.