test_user_changeemail_api.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from django.contrib.auth import get_user_model
  2. from django.core import mail
  3. from ..testutils import AuthenticatedUserTestCase
  4. class UserChangeEmailTests(AuthenticatedUserTestCase):
  5. """
  6. tests for user change email RPC (/api/users/1/change-email/)
  7. """
  8. def setUp(self):
  9. super(UserChangeEmailTests, self).setUp()
  10. self.link = '/api/users/%s/change-email/' % self.user.pk
  11. def test_unsupported_methods(self):
  12. """api isn't supporting GET"""
  13. response = self.client.get(self.link)
  14. self.assertEqual(response.status_code, 405)
  15. def test_change_email(self):
  16. """api allows users to change their e-mail addresses"""
  17. response = self.client.post(self.link, data={
  18. 'new_email': 'new@email.com',
  19. 'password': self.USER_PASSWORD
  20. })
  21. self.assertEqual(response.status_code, 200)
  22. self.assertIn('Confirm e-mail change', mail.outbox[0].subject)
  23. for line in [l.strip() for l in mail.outbox[0].body.splitlines()]:
  24. if line.startswith('http://'):
  25. token = line.rstrip('/').split('/')[-1]
  26. break
  27. else:
  28. self.fail("E-mail sent didn't contain confirmation url")
  29. def test_invalid_password(self):
  30. """api errors correctly for invalid password"""
  31. response = self.client.post(self.link, data={
  32. 'new_email': 'new@email.com',
  33. 'password': 'Lor3mIpsum'
  34. })
  35. self.assertContains(response, 'password is invalid', status_code=400)
  36. def test_invalid_input(self):
  37. """api errors correctly for invalid input"""
  38. response = self.client.post(self.link, data={
  39. 'new_email': '',
  40. 'password': self.USER_PASSWORD
  41. })
  42. self.assertContains(response, 'new_email":["This field is required', status_code=400)
  43. response = self.client.post(self.link, data={
  44. 'new_email': 'newmail',
  45. 'password': self.USER_PASSWORD
  46. })
  47. self.assertContains(response, 'valid email address', status_code=400)
  48. def test_email_taken(self):
  49. """api validates email usage"""
  50. User = get_user_model()
  51. User.objects.create_user('BobBoberson', 'new@email.com', 'Pass.123')
  52. response = self.client.post(self.link, data={
  53. 'new_email': 'new@email.com',
  54. 'password': self.USER_PASSWORD
  55. })
  56. self.assertContains(response, 'not available', status_code=400)