PageRenderTime 68ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/django-1.2/django/contrib/auth/tests/views.py

https://github.com/theosp/google_appengine
Python | 295 lines | 235 code | 41 blank | 19 comment | 4 complexity | c4bbf70b10064f510afbaa99717bc092 MD5 | raw file
  1. import os
  2. import re
  3. import urllib
  4. from django.conf import settings
  5. from django.contrib.auth import SESSION_KEY, REDIRECT_FIELD_NAME
  6. from django.contrib.auth.forms import AuthenticationForm
  7. from django.contrib.sites.models import Site, RequestSite
  8. from django.contrib.auth.models import User
  9. from django.test import TestCase
  10. from django.core import mail
  11. from django.core.urlresolvers import reverse
  12. class AuthViewsTestCase(TestCase):
  13. """
  14. Helper base class for all the follow test cases.
  15. """
  16. fixtures = ['authtestdata.json']
  17. urls = 'django.contrib.auth.tests.urls'
  18. def setUp(self):
  19. self.old_LANGUAGES = settings.LANGUAGES
  20. self.old_LANGUAGE_CODE = settings.LANGUAGE_CODE
  21. settings.LANGUAGES = (('en', 'English'),)
  22. settings.LANGUAGE_CODE = 'en'
  23. self.old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS
  24. settings.TEMPLATE_DIRS = (
  25. os.path.join(
  26. os.path.dirname(__file__),
  27. 'templates'
  28. )
  29. ,)
  30. def tearDown(self):
  31. settings.LANGUAGES = self.old_LANGUAGES
  32. settings.LANGUAGE_CODE = self.old_LANGUAGE_CODE
  33. settings.TEMPLATE_DIRS = self.old_TEMPLATE_DIRS
  34. class PasswordResetTest(AuthViewsTestCase):
  35. def test_email_not_found(self):
  36. "Error is raised if the provided email address isn't currently registered"
  37. response = self.client.get('/password_reset/')
  38. self.assertEquals(response.status_code, 200)
  39. response = self.client.post('/password_reset/', {'email': 'not_a_real_email@email.com'})
  40. self.assertContains(response, "That e-mail address doesn't have an associated user account")
  41. self.assertEquals(len(mail.outbox), 0)
  42. def test_email_found(self):
  43. "Email is sent if a valid email address is provided for password reset"
  44. response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
  45. self.assertEquals(response.status_code, 302)
  46. self.assertEquals(len(mail.outbox), 1)
  47. self.assert_("http://" in mail.outbox[0].body)
  48. def _test_confirm_start(self):
  49. # Start by creating the email
  50. response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
  51. self.assertEquals(response.status_code, 302)
  52. self.assertEquals(len(mail.outbox), 1)
  53. return self._read_signup_email(mail.outbox[0])
  54. def _read_signup_email(self, email):
  55. urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body)
  56. self.assert_(urlmatch is not None, "No URL found in sent email")
  57. return urlmatch.group(), urlmatch.groups()[0]
  58. def test_confirm_valid(self):
  59. url, path = self._test_confirm_start()
  60. response = self.client.get(path)
  61. # redirect to a 'complete' page:
  62. self.assertEquals(response.status_code, 200)
  63. self.assert_("Please enter your new password" in response.content)
  64. def test_confirm_invalid(self):
  65. url, path = self._test_confirm_start()
  66. # Let's munge the token in the path, but keep the same length,
  67. # in case the URLconf will reject a different length.
  68. path = path[:-5] + ("0"*4) + path[-1]
  69. response = self.client.get(path)
  70. self.assertEquals(response.status_code, 200)
  71. self.assert_("The password reset link was invalid" in response.content)
  72. def test_confirm_invalid_user(self):
  73. # Ensure that we get a 200 response for a non-existant user, not a 404
  74. response = self.client.get('/reset/123456-1-1/')
  75. self.assertEquals(response.status_code, 200)
  76. self.assert_("The password reset link was invalid" in response.content)
  77. def test_confirm_overflow_user(self):
  78. # Ensure that we get a 200 response for a base36 user id that overflows int
  79. response = self.client.get('/reset/zzzzzzzzzzzzz-1-1/')
  80. self.assertEquals(response.status_code, 200)
  81. self.assert_("The password reset link was invalid" in response.content)
  82. def test_confirm_invalid_post(self):
  83. # Same as test_confirm_invalid, but trying
  84. # to do a POST instead.
  85. url, path = self._test_confirm_start()
  86. path = path[:-5] + ("0"*4) + path[-1]
  87. response = self.client.post(path, {'new_password1': 'anewpassword',
  88. 'new_password2':' anewpassword'})
  89. # Check the password has not been changed
  90. u = User.objects.get(email='staffmember@example.com')
  91. self.assert_(not u.check_password("anewpassword"))
  92. def test_confirm_complete(self):
  93. url, path = self._test_confirm_start()
  94. response = self.client.post(path, {'new_password1': 'anewpassword',
  95. 'new_password2': 'anewpassword'})
  96. # It redirects us to a 'complete' page:
  97. self.assertEquals(response.status_code, 302)
  98. # Check the password has been changed
  99. u = User.objects.get(email='staffmember@example.com')
  100. self.assert_(u.check_password("anewpassword"))
  101. # Check we can't use the link again
  102. response = self.client.get(path)
  103. self.assertEquals(response.status_code, 200)
  104. self.assert_("The password reset link was invalid" in response.content)
  105. def test_confirm_different_passwords(self):
  106. url, path = self._test_confirm_start()
  107. response = self.client.post(path, {'new_password1': 'anewpassword',
  108. 'new_password2':' x'})
  109. self.assertEquals(response.status_code, 200)
  110. self.assert_("The two password fields didn't match" in response.content)
  111. class ChangePasswordTest(AuthViewsTestCase):
  112. def login(self, password='password'):
  113. response = self.client.post('/login/', {
  114. 'username': 'testclient',
  115. 'password': password
  116. }
  117. )
  118. self.assertEquals(response.status_code, 302)
  119. self.assert_(response['Location'].endswith(settings.LOGIN_REDIRECT_URL))
  120. def fail_login(self, password='password'):
  121. response = self.client.post('/login/', {
  122. 'username': 'testclient',
  123. 'password': password
  124. }
  125. )
  126. self.assertEquals(response.status_code, 200)
  127. self.assert_("Please enter a correct username and password. Note that both fields are case-sensitive." in response.content)
  128. def logout(self):
  129. response = self.client.get('/logout/')
  130. def test_password_change_fails_with_invalid_old_password(self):
  131. self.login()
  132. response = self.client.post('/password_change/', {
  133. 'old_password': 'donuts',
  134. 'new_password1': 'password1',
  135. 'new_password2': 'password1',
  136. }
  137. )
  138. self.assertEquals(response.status_code, 200)
  139. self.assert_("Your old password was entered incorrectly. Please enter it again." in response.content)
  140. def test_password_change_fails_with_mismatched_passwords(self):
  141. self.login()
  142. response = self.client.post('/password_change/', {
  143. 'old_password': 'password',
  144. 'new_password1': 'password1',
  145. 'new_password2': 'donuts',
  146. }
  147. )
  148. self.assertEquals(response.status_code, 200)
  149. self.assert_("The two password fields didn't match." in response.content)
  150. def test_password_change_succeeds(self):
  151. self.login()
  152. response = self.client.post('/password_change/', {
  153. 'old_password': 'password',
  154. 'new_password1': 'password1',
  155. 'new_password2': 'password1',
  156. }
  157. )
  158. self.assertEquals(response.status_code, 302)
  159. self.assert_(response['Location'].endswith('/password_change/done/'))
  160. self.fail_login()
  161. self.login(password='password1')
  162. class LoginTest(AuthViewsTestCase):
  163. def test_current_site_in_context_after_login(self):
  164. response = self.client.get(reverse('django.contrib.auth.views.login'))
  165. self.assertEquals(response.status_code, 200)
  166. if Site._meta.installed:
  167. site = Site.objects.get_current()
  168. self.assertEquals(response.context['site'], site)
  169. self.assertEquals(response.context['site_name'], site.name)
  170. else:
  171. self.assertTrue(isinstance(response.context['site'], RequestSite))
  172. self.assert_(isinstance(response.context['form'], AuthenticationForm),
  173. 'Login form is not an AuthenticationForm')
  174. def test_security_check(self, password='password'):
  175. login_url = reverse('django.contrib.auth.views.login')
  176. # Those URLs should not pass the security check
  177. for bad_url in ('http://example.com',
  178. 'https://example.com',
  179. 'ftp://exampel.com',
  180. '//example.com'):
  181. nasty_url = '%(url)s?%(next)s=%(bad_url)s' % {
  182. 'url': login_url,
  183. 'next': REDIRECT_FIELD_NAME,
  184. 'bad_url': urllib.quote(bad_url)
  185. }
  186. response = self.client.post(nasty_url, {
  187. 'username': 'testclient',
  188. 'password': password,
  189. }
  190. )
  191. self.assertEquals(response.status_code, 302)
  192. self.assertFalse(bad_url in response['Location'], "%s should be blocked" % bad_url)
  193. # Now, these URLs have an other URL as a GET parameter and therefore
  194. # should be allowed
  195. for url_ in ('http://example.com', 'https://example.com',
  196. 'ftp://exampel.com', '//example.com'):
  197. safe_url = '%(url)s?%(next)s=/view/?param=%(safe_param)s' % {
  198. 'url': login_url,
  199. 'next': REDIRECT_FIELD_NAME,
  200. 'safe_param': urllib.quote(url_)
  201. }
  202. response = self.client.post(safe_url, {
  203. 'username': 'testclient',
  204. 'password': password,
  205. }
  206. )
  207. self.assertEquals(response.status_code, 302)
  208. self.assertTrue('/view/?param=%s' % url_ in response['Location'], "/view/?param=%s should be allowed" % url_)
  209. class LogoutTest(AuthViewsTestCase):
  210. urls = 'django.contrib.auth.tests.urls'
  211. def login(self, password='password'):
  212. response = self.client.post('/login/', {
  213. 'username': 'testclient',
  214. 'password': password
  215. }
  216. )
  217. self.assertEquals(response.status_code, 302)
  218. self.assert_(response['Location'].endswith(settings.LOGIN_REDIRECT_URL))
  219. self.assert_(SESSION_KEY in self.client.session)
  220. def confirm_logged_out(self):
  221. self.assert_(SESSION_KEY not in self.client.session)
  222. def test_logout_default(self):
  223. "Logout without next_page option renders the default template"
  224. self.login()
  225. response = self.client.get('/logout/')
  226. self.assertEquals(200, response.status_code)
  227. self.assert_('Logged out' in response.content)
  228. self.confirm_logged_out()
  229. def test_14377(self):
  230. # Bug 14377
  231. self.login()
  232. response = self.client.get('/logout/')
  233. self.assertTrue('site' in response.context)
  234. def test_logout_with_next_page_specified(self):
  235. "Logout with next_page option given redirects to specified resource"
  236. self.login()
  237. response = self.client.get('/logout/next_page/')
  238. self.assertEqual(response.status_code, 302)
  239. self.assert_(response['Location'].endswith('/somewhere/'))
  240. self.confirm_logged_out()
  241. def test_logout_with_redirect_argument(self):
  242. "Logout with query string redirects to specified resource"
  243. self.login()
  244. response = self.client.get('/logout/?next=/login/')
  245. self.assertEqual(response.status_code, 302)
  246. self.assert_(response['Location'].endswith('/login/'))
  247. self.confirm_logged_out()
  248. def test_logout_with_custom_redirect_argument(self):
  249. "Logout with custom query string redirects to specified resource"
  250. self.login()
  251. response = self.client.get('/logout/custom_query/?follow=/somewhere/')
  252. self.assertEqual(response.status_code, 302)
  253. self.assert_(response['Location'].endswith('/somewhere/'))
  254. self.confirm_logged_out()