PageRenderTime 56ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/auth_tests/test_forms.py

https://bitbucket.org/karossas/django
Python | 792 lines | 693 code | 55 blank | 44 comment | 4 complexity | dfa2af0986c2139eb468d00a30535b4f MD5 | raw file
Possible License(s): BSD-3-Clause
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import datetime
  4. import re
  5. from unittest import skipIf
  6. from django import forms
  7. from django.contrib.auth.forms import (
  8. AdminPasswordChangeForm, AuthenticationForm, PasswordChangeForm,
  9. PasswordResetForm, ReadOnlyPasswordHashField, ReadOnlyPasswordHashWidget,
  10. SetPasswordForm, UserChangeForm, UserCreationForm,
  11. )
  12. from django.contrib.auth.models import User
  13. from django.contrib.sites.models import Site
  14. from django.core import mail
  15. from django.core.mail import EmailMultiAlternatives
  16. from django.forms.fields import CharField, Field
  17. from django.test import SimpleTestCase, TestCase, mock, override_settings
  18. from django.utils import six, translation
  19. from django.utils.encoding import force_text
  20. from django.utils.text import capfirst
  21. from django.utils.translation import ugettext as _
  22. from .models.custom_user import CustomUser, ExtensionUser
  23. from .settings import AUTH_TEMPLATES
  24. class TestDataMixin(object):
  25. @classmethod
  26. def setUpTestData(cls):
  27. cls.u1 = User.objects.create_user(username='testclient', password='password', email='testclient@example.com')
  28. cls.u2 = User.objects.create_user(username='inactive', password='password', is_active=False)
  29. cls.u3 = User.objects.create_user(username='staff', password='password')
  30. cls.u4 = User.objects.create(username='empty_password', password='')
  31. cls.u5 = User.objects.create(username='unmanageable_password', password='$')
  32. cls.u6 = User.objects.create(username='unknown_password', password='foo$bar')
  33. class UserCreationFormTest(TestDataMixin, TestCase):
  34. def test_user_already_exists(self):
  35. data = {
  36. 'username': 'testclient',
  37. 'password1': 'test123',
  38. 'password2': 'test123',
  39. }
  40. form = UserCreationForm(data)
  41. self.assertFalse(form.is_valid())
  42. self.assertEqual(form["username"].errors,
  43. [force_text(User._meta.get_field('username').error_messages['unique'])])
  44. def test_invalid_data(self):
  45. data = {
  46. 'username': 'jsmith!',
  47. 'password1': 'test123',
  48. 'password2': 'test123',
  49. }
  50. form = UserCreationForm(data)
  51. self.assertFalse(form.is_valid())
  52. validator = next(v for v in User._meta.get_field('username').validators if v.code == 'invalid')
  53. self.assertEqual(form["username"].errors, [force_text(validator.message)])
  54. def test_password_verification(self):
  55. # The verification password is incorrect.
  56. data = {
  57. 'username': 'jsmith',
  58. 'password1': 'test123',
  59. 'password2': 'test',
  60. }
  61. form = UserCreationForm(data)
  62. self.assertFalse(form.is_valid())
  63. self.assertEqual(form["password2"].errors,
  64. [force_text(form.error_messages['password_mismatch'])])
  65. def test_both_passwords(self):
  66. # One (or both) passwords weren't given
  67. data = {'username': 'jsmith'}
  68. form = UserCreationForm(data)
  69. required_error = [force_text(Field.default_error_messages['required'])]
  70. self.assertFalse(form.is_valid())
  71. self.assertEqual(form['password1'].errors, required_error)
  72. self.assertEqual(form['password2'].errors, required_error)
  73. data['password2'] = 'test123'
  74. form = UserCreationForm(data)
  75. self.assertFalse(form.is_valid())
  76. self.assertEqual(form['password1'].errors, required_error)
  77. self.assertEqual(form['password2'].errors, [])
  78. @mock.patch('django.contrib.auth.password_validation.password_changed')
  79. def test_success(self, password_changed):
  80. # The success case.
  81. data = {
  82. 'username': 'jsmith@example.com',
  83. 'password1': 'test123',
  84. 'password2': 'test123',
  85. }
  86. form = UserCreationForm(data)
  87. self.assertTrue(form.is_valid())
  88. form.save(commit=False)
  89. self.assertEqual(password_changed.call_count, 0)
  90. u = form.save()
  91. self.assertEqual(password_changed.call_count, 1)
  92. self.assertEqual(repr(u), '<User: jsmith@example.com>')
  93. def test_unicode_username(self):
  94. data = {
  95. 'username': '宝',
  96. 'password1': 'test123',
  97. 'password2': 'test123',
  98. }
  99. form = UserCreationForm(data)
  100. if six.PY3:
  101. self.assertTrue(form.is_valid())
  102. u = form.save()
  103. self.assertEqual(u.username, '宝')
  104. else:
  105. self.assertFalse(form.is_valid())
  106. @skipIf(six.PY2, "Python 2 doesn't support unicode usernames by default.")
  107. def test_normalize_username(self):
  108. # The normalization happens in AbstractBaseUser.clean() and ModelForm
  109. # validation calls Model.clean().
  110. ohm_username = 'testΩ' # U+2126 OHM SIGN
  111. data = {
  112. 'username': ohm_username,
  113. 'password1': 'pwd2',
  114. 'password2': 'pwd2',
  115. }
  116. form = UserCreationForm(data)
  117. self.assertTrue(form.is_valid())
  118. user = form.save()
  119. self.assertNotEqual(user.username, ohm_username)
  120. self.assertEqual(user.username, 'testΩ') # U+03A9 GREEK CAPITAL LETTER OMEGA
  121. @skipIf(six.PY2, "Python 2 doesn't support unicode usernames by default.")
  122. def test_duplicate_normalized_unicode(self):
  123. """
  124. To prevent almost identical usernames, visually identical but differing
  125. by their unicode code points only, Unicode NFKC normalization should
  126. make appear them equal to Django.
  127. """
  128. omega_username = 'iamtheΩ' # U+03A9 GREEK CAPITAL LETTER OMEGA
  129. ohm_username = 'iamtheΩ' # U+2126 OHM SIGN
  130. self.assertNotEqual(omega_username, ohm_username)
  131. User.objects.create_user(username=omega_username, password='pwd')
  132. data = {
  133. 'username': ohm_username,
  134. 'password1': 'pwd2',
  135. 'password2': 'pwd2',
  136. }
  137. form = UserCreationForm(data)
  138. self.assertFalse(form.is_valid())
  139. self.assertEqual(
  140. form.errors['username'], ["A user with that username already exists."]
  141. )
  142. @override_settings(AUTH_PASSWORD_VALIDATORS=[
  143. {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
  144. {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': {
  145. 'min_length': 12,
  146. }},
  147. ])
  148. def test_validates_password(self):
  149. data = {
  150. 'username': 'testclient',
  151. 'password1': 'testclient',
  152. 'password2': 'testclient',
  153. }
  154. form = UserCreationForm(data)
  155. self.assertFalse(form.is_valid())
  156. self.assertEqual(len(form['password2'].errors), 2)
  157. self.assertIn('The password is too similar to the username.', form['password2'].errors)
  158. self.assertIn(
  159. 'This password is too short. It must contain at least 12 characters.',
  160. form['password2'].errors
  161. )
  162. def test_custom_form(self):
  163. class CustomUserCreationForm(UserCreationForm):
  164. class Meta(UserCreationForm.Meta):
  165. model = ExtensionUser
  166. fields = UserCreationForm.Meta.fields + ('date_of_birth',)
  167. data = {
  168. 'username': 'testclient',
  169. 'password1': 'testclient',
  170. 'password2': 'testclient',
  171. 'date_of_birth': '1988-02-24',
  172. }
  173. form = CustomUserCreationForm(data)
  174. self.assertTrue(form.is_valid())
  175. def test_custom_form_with_different_username_field(self):
  176. class CustomUserCreationForm(UserCreationForm):
  177. class Meta(UserCreationForm.Meta):
  178. model = CustomUser
  179. fields = ('email', 'date_of_birth')
  180. data = {
  181. 'email': 'test@client222.com',
  182. 'password1': 'testclient',
  183. 'password2': 'testclient',
  184. 'date_of_birth': '1988-02-24',
  185. }
  186. form = CustomUserCreationForm(data)
  187. self.assertTrue(form.is_valid())
  188. def test_password_whitespace_not_stripped(self):
  189. data = {
  190. 'username': 'testuser',
  191. 'password1': ' testpassword ',
  192. 'password2': ' testpassword ',
  193. }
  194. form = UserCreationForm(data)
  195. self.assertTrue(form.is_valid())
  196. self.assertEqual(form.cleaned_data['password1'], data['password1'])
  197. self.assertEqual(form.cleaned_data['password2'], data['password2'])
  198. # To verify that the login form rejects inactive users, use an authentication
  199. # backend that allows them.
  200. @override_settings(AUTHENTICATION_BACKENDS=['django.contrib.auth.backends.AllowAllUsersModelBackend'])
  201. class AuthenticationFormTest(TestDataMixin, TestCase):
  202. def test_invalid_username(self):
  203. # The user submits an invalid username.
  204. data = {
  205. 'username': 'jsmith_does_not_exist',
  206. 'password': 'test123',
  207. }
  208. form = AuthenticationForm(None, data)
  209. self.assertFalse(form.is_valid())
  210. self.assertEqual(
  211. form.non_field_errors(), [
  212. force_text(form.error_messages['invalid_login'] % {
  213. 'username': User._meta.get_field('username').verbose_name
  214. })
  215. ]
  216. )
  217. def test_inactive_user(self):
  218. # The user is inactive.
  219. data = {
  220. 'username': 'inactive',
  221. 'password': 'password',
  222. }
  223. form = AuthenticationForm(None, data)
  224. self.assertFalse(form.is_valid())
  225. self.assertEqual(form.non_field_errors(), [force_text(form.error_messages['inactive'])])
  226. def test_inactive_user_i18n(self):
  227. with self.settings(USE_I18N=True), translation.override('pt-br', deactivate=True):
  228. # The user is inactive.
  229. data = {
  230. 'username': 'inactive',
  231. 'password': 'password',
  232. }
  233. form = AuthenticationForm(None, data)
  234. self.assertFalse(form.is_valid())
  235. self.assertEqual(form.non_field_errors(), [force_text(form.error_messages['inactive'])])
  236. def test_custom_login_allowed_policy(self):
  237. # The user is inactive, but our custom form policy allows them to log in.
  238. data = {
  239. 'username': 'inactive',
  240. 'password': 'password',
  241. }
  242. class AuthenticationFormWithInactiveUsersOkay(AuthenticationForm):
  243. def confirm_login_allowed(self, user):
  244. pass
  245. form = AuthenticationFormWithInactiveUsersOkay(None, data)
  246. self.assertTrue(form.is_valid())
  247. # If we want to disallow some logins according to custom logic,
  248. # we should raise a django.forms.ValidationError in the form.
  249. class PickyAuthenticationForm(AuthenticationForm):
  250. def confirm_login_allowed(self, user):
  251. if user.username == "inactive":
  252. raise forms.ValidationError("This user is disallowed.")
  253. raise forms.ValidationError("Sorry, nobody's allowed in.")
  254. form = PickyAuthenticationForm(None, data)
  255. self.assertFalse(form.is_valid())
  256. self.assertEqual(form.non_field_errors(), ['This user is disallowed.'])
  257. data = {
  258. 'username': 'testclient',
  259. 'password': 'password',
  260. }
  261. form = PickyAuthenticationForm(None, data)
  262. self.assertFalse(form.is_valid())
  263. self.assertEqual(form.non_field_errors(), ["Sorry, nobody's allowed in."])
  264. def test_success(self):
  265. # The success case
  266. data = {
  267. 'username': 'testclient',
  268. 'password': 'password',
  269. }
  270. form = AuthenticationForm(None, data)
  271. self.assertTrue(form.is_valid())
  272. self.assertEqual(form.non_field_errors(), [])
  273. def test_unicode_username(self):
  274. User.objects.create_user(username='Σαρα', password='pwd')
  275. data = {
  276. 'username': 'Σαρα',
  277. 'password': 'pwd',
  278. }
  279. form = AuthenticationForm(None, data)
  280. self.assertTrue(form.is_valid())
  281. self.assertEqual(form.non_field_errors(), [])
  282. def test_username_field_label(self):
  283. class CustomAuthenticationForm(AuthenticationForm):
  284. username = CharField(label="Name", max_length=75)
  285. form = CustomAuthenticationForm()
  286. self.assertEqual(form['username'].label, "Name")
  287. def test_username_field_label_not_set(self):
  288. class CustomAuthenticationForm(AuthenticationForm):
  289. username = CharField()
  290. form = CustomAuthenticationForm()
  291. username_field = User._meta.get_field(User.USERNAME_FIELD)
  292. self.assertEqual(form.fields['username'].label, capfirst(username_field.verbose_name))
  293. def test_username_field_label_empty_string(self):
  294. class CustomAuthenticationForm(AuthenticationForm):
  295. username = CharField(label='')
  296. form = CustomAuthenticationForm()
  297. self.assertEqual(form.fields['username'].label, "")
  298. def test_password_whitespace_not_stripped(self):
  299. data = {
  300. 'username': 'testuser',
  301. 'password': ' pass ',
  302. }
  303. form = AuthenticationForm(None, data)
  304. form.is_valid() # Not necessary to have valid credentails for the test.
  305. self.assertEqual(form.cleaned_data['password'], data['password'])
  306. class SetPasswordFormTest(TestDataMixin, TestCase):
  307. def test_password_verification(self):
  308. # The two new passwords do not match.
  309. user = User.objects.get(username='testclient')
  310. data = {
  311. 'new_password1': 'abc123',
  312. 'new_password2': 'abc',
  313. }
  314. form = SetPasswordForm(user, data)
  315. self.assertFalse(form.is_valid())
  316. self.assertEqual(
  317. form["new_password2"].errors,
  318. [force_text(form.error_messages['password_mismatch'])]
  319. )
  320. @mock.patch('django.contrib.auth.password_validation.password_changed')
  321. def test_success(self, password_changed):
  322. user = User.objects.get(username='testclient')
  323. data = {
  324. 'new_password1': 'abc123',
  325. 'new_password2': 'abc123',
  326. }
  327. form = SetPasswordForm(user, data)
  328. self.assertTrue(form.is_valid())
  329. form.save(commit=False)
  330. self.assertEqual(password_changed.call_count, 0)
  331. form.save()
  332. self.assertEqual(password_changed.call_count, 1)
  333. @override_settings(AUTH_PASSWORD_VALIDATORS=[
  334. {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
  335. {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': {
  336. 'min_length': 12,
  337. }},
  338. ])
  339. def test_validates_password(self):
  340. user = User.objects.get(username='testclient')
  341. data = {
  342. 'new_password1': 'testclient',
  343. 'new_password2': 'testclient',
  344. }
  345. form = SetPasswordForm(user, data)
  346. self.assertFalse(form.is_valid())
  347. self.assertEqual(len(form["new_password2"].errors), 2)
  348. self.assertIn('The password is too similar to the username.', form["new_password2"].errors)
  349. self.assertIn(
  350. 'This password is too short. It must contain at least 12 characters.',
  351. form["new_password2"].errors
  352. )
  353. def test_password_whitespace_not_stripped(self):
  354. user = User.objects.get(username='testclient')
  355. data = {
  356. 'new_password1': ' password ',
  357. 'new_password2': ' password ',
  358. }
  359. form = SetPasswordForm(user, data)
  360. self.assertTrue(form.is_valid())
  361. self.assertEqual(form.cleaned_data['new_password1'], data['new_password1'])
  362. self.assertEqual(form.cleaned_data['new_password2'], data['new_password2'])
  363. @override_settings(AUTH_PASSWORD_VALIDATORS=[
  364. {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
  365. {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': {
  366. 'min_length': 12,
  367. }},
  368. ])
  369. def test_help_text_translation(self):
  370. french_help_texts = [
  371. 'Votre mot de passe ne peut pas trop ressembler à vos autres informations personnelles.',
  372. 'Votre mot de passe doit contenir au minimum 12 caractères.',
  373. ]
  374. form = SetPasswordForm(self.u1)
  375. with translation.override('fr'):
  376. html = form.as_p()
  377. for french_text in french_help_texts:
  378. self.assertIn(french_text, html)
  379. class PasswordChangeFormTest(TestDataMixin, TestCase):
  380. def test_incorrect_password(self):
  381. user = User.objects.get(username='testclient')
  382. data = {
  383. 'old_password': 'test',
  384. 'new_password1': 'abc123',
  385. 'new_password2': 'abc123',
  386. }
  387. form = PasswordChangeForm(user, data)
  388. self.assertFalse(form.is_valid())
  389. self.assertEqual(form["old_password"].errors, [force_text(form.error_messages['password_incorrect'])])
  390. def test_password_verification(self):
  391. # The two new passwords do not match.
  392. user = User.objects.get(username='testclient')
  393. data = {
  394. 'old_password': 'password',
  395. 'new_password1': 'abc123',
  396. 'new_password2': 'abc',
  397. }
  398. form = PasswordChangeForm(user, data)
  399. self.assertFalse(form.is_valid())
  400. self.assertEqual(form["new_password2"].errors, [force_text(form.error_messages['password_mismatch'])])
  401. @mock.patch('django.contrib.auth.password_validation.password_changed')
  402. def test_success(self, password_changed):
  403. # The success case.
  404. user = User.objects.get(username='testclient')
  405. data = {
  406. 'old_password': 'password',
  407. 'new_password1': 'abc123',
  408. 'new_password2': 'abc123',
  409. }
  410. form = PasswordChangeForm(user, data)
  411. self.assertTrue(form.is_valid())
  412. form.save(commit=False)
  413. self.assertEqual(password_changed.call_count, 0)
  414. form.save()
  415. self.assertEqual(password_changed.call_count, 1)
  416. def test_field_order(self):
  417. # Regression test - check the order of fields:
  418. user = User.objects.get(username='testclient')
  419. self.assertEqual(list(PasswordChangeForm(user, {}).fields), ['old_password', 'new_password1', 'new_password2'])
  420. def test_password_whitespace_not_stripped(self):
  421. user = User.objects.get(username='testclient')
  422. user.set_password(' oldpassword ')
  423. data = {
  424. 'old_password': ' oldpassword ',
  425. 'new_password1': ' pass ',
  426. 'new_password2': ' pass ',
  427. }
  428. form = PasswordChangeForm(user, data)
  429. self.assertTrue(form.is_valid())
  430. self.assertEqual(form.cleaned_data['old_password'], data['old_password'])
  431. self.assertEqual(form.cleaned_data['new_password1'], data['new_password1'])
  432. self.assertEqual(form.cleaned_data['new_password2'], data['new_password2'])
  433. class UserChangeFormTest(TestDataMixin, TestCase):
  434. def test_username_validity(self):
  435. user = User.objects.get(username='testclient')
  436. data = {'username': 'not valid'}
  437. form = UserChangeForm(data, instance=user)
  438. self.assertFalse(form.is_valid())
  439. validator = next(v for v in User._meta.get_field('username').validators if v.code == 'invalid')
  440. self.assertEqual(form["username"].errors, [force_text(validator.message)])
  441. def test_bug_14242(self):
  442. # A regression test, introduce by adding an optimization for the
  443. # UserChangeForm.
  444. class MyUserForm(UserChangeForm):
  445. def __init__(self, *args, **kwargs):
  446. super(MyUserForm, self).__init__(*args, **kwargs)
  447. self.fields['groups'].help_text = 'These groups give users different permissions'
  448. class Meta(UserChangeForm.Meta):
  449. fields = ('groups',)
  450. # Just check we can create it
  451. MyUserForm({})
  452. def test_unusable_password(self):
  453. user = User.objects.get(username='empty_password')
  454. user.set_unusable_password()
  455. user.save()
  456. form = UserChangeForm(instance=user)
  457. self.assertIn(_("No password set."), form.as_table())
  458. def test_bug_17944_empty_password(self):
  459. user = User.objects.get(username='empty_password')
  460. form = UserChangeForm(instance=user)
  461. self.assertIn(_("No password set."), form.as_table())
  462. def test_bug_17944_unmanageable_password(self):
  463. user = User.objects.get(username='unmanageable_password')
  464. form = UserChangeForm(instance=user)
  465. self.assertIn(_("Invalid password format or unknown hashing algorithm."), form.as_table())
  466. def test_bug_17944_unknown_password_algorithm(self):
  467. user = User.objects.get(username='unknown_password')
  468. form = UserChangeForm(instance=user)
  469. self.assertIn(_("Invalid password format or unknown hashing algorithm."), form.as_table())
  470. def test_bug_19133(self):
  471. "The change form does not return the password value"
  472. # Use the form to construct the POST data
  473. user = User.objects.get(username='testclient')
  474. form_for_data = UserChangeForm(instance=user)
  475. post_data = form_for_data.initial
  476. # The password field should be readonly, so anything
  477. # posted here should be ignored; the form will be
  478. # valid, and give back the 'initial' value for the
  479. # password field.
  480. post_data['password'] = 'new password'
  481. form = UserChangeForm(instance=user, data=post_data)
  482. self.assertTrue(form.is_valid())
  483. # original hashed password contains $
  484. self.assertIn('$', form.cleaned_data['password'])
  485. def test_bug_19349_bound_password_field(self):
  486. user = User.objects.get(username='testclient')
  487. form = UserChangeForm(data={}, instance=user)
  488. # When rendering the bound password field,
  489. # ReadOnlyPasswordHashWidget needs the initial
  490. # value to render correctly
  491. self.assertEqual(form.initial['password'], form['password'].value())
  492. def test_custom_form(self):
  493. class CustomUserChangeForm(UserChangeForm):
  494. class Meta(UserChangeForm.Meta):
  495. model = ExtensionUser
  496. fields = ('username', 'password', 'date_of_birth',)
  497. user = User.objects.get(username='testclient')
  498. data = {
  499. 'username': 'testclient',
  500. 'password': 'testclient',
  501. 'date_of_birth': '1998-02-24',
  502. }
  503. form = CustomUserChangeForm(data, instance=user)
  504. self.assertTrue(form.is_valid())
  505. form.save()
  506. self.assertEqual(form.cleaned_data['username'], 'testclient')
  507. self.assertEqual(form.cleaned_data['date_of_birth'], datetime.date(1998, 2, 24))
  508. @override_settings(TEMPLATES=AUTH_TEMPLATES)
  509. class PasswordResetFormTest(TestDataMixin, TestCase):
  510. @classmethod
  511. def setUpClass(cls):
  512. super(PasswordResetFormTest, cls).setUpClass()
  513. # This cleanup is necessary because contrib.sites cache
  514. # makes tests interfere with each other, see #11505
  515. Site.objects.clear_cache()
  516. def create_dummy_user(self):
  517. """
  518. Create a user and return a tuple (user_object, username, email).
  519. """
  520. username = 'jsmith'
  521. email = 'jsmith@example.com'
  522. user = User.objects.create_user(username, email, 'test123')
  523. return (user, username, email)
  524. def test_invalid_email(self):
  525. data = {'email': 'not valid'}
  526. form = PasswordResetForm(data)
  527. self.assertFalse(form.is_valid())
  528. self.assertEqual(form['email'].errors, [_('Enter a valid email address.')])
  529. def test_nonexistent_email(self):
  530. """
  531. Test nonexistent email address. This should not fail because it would
  532. expose information about registered users.
  533. """
  534. data = {'email': 'foo@bar.com'}
  535. form = PasswordResetForm(data)
  536. self.assertTrue(form.is_valid())
  537. self.assertEqual(len(mail.outbox), 0)
  538. def test_cleaned_data(self):
  539. (user, username, email) = self.create_dummy_user()
  540. data = {'email': email}
  541. form = PasswordResetForm(data)
  542. self.assertTrue(form.is_valid())
  543. form.save(domain_override='example.com')
  544. self.assertEqual(form.cleaned_data['email'], email)
  545. self.assertEqual(len(mail.outbox), 1)
  546. def test_custom_email_subject(self):
  547. data = {'email': 'testclient@example.com'}
  548. form = PasswordResetForm(data)
  549. self.assertTrue(form.is_valid())
  550. # Since we're not providing a request object, we must provide a
  551. # domain_override to prevent the save operation from failing in the
  552. # potential case where contrib.sites is not installed. Refs #16412.
  553. form.save(domain_override='example.com')
  554. self.assertEqual(len(mail.outbox), 1)
  555. self.assertEqual(mail.outbox[0].subject, 'Custom password reset on example.com')
  556. def test_custom_email_constructor(self):
  557. data = {'email': 'testclient@example.com'}
  558. class CustomEmailPasswordResetForm(PasswordResetForm):
  559. def send_mail(self, subject_template_name, email_template_name,
  560. context, from_email, to_email,
  561. html_email_template_name=None):
  562. EmailMultiAlternatives(
  563. "Forgot your password?",
  564. "Sorry to hear you forgot your password.",
  565. None, [to_email],
  566. ['site_monitor@example.com'],
  567. headers={'Reply-To': 'webmaster@example.com'},
  568. alternatives=[
  569. ("Really sorry to hear you forgot your password.", "text/html")
  570. ],
  571. ).send()
  572. form = CustomEmailPasswordResetForm(data)
  573. self.assertTrue(form.is_valid())
  574. # Since we're not providing a request object, we must provide a
  575. # domain_override to prevent the save operation from failing in the
  576. # potential case where contrib.sites is not installed. Refs #16412.
  577. form.save(domain_override='example.com')
  578. self.assertEqual(len(mail.outbox), 1)
  579. self.assertEqual(mail.outbox[0].subject, 'Forgot your password?')
  580. self.assertEqual(mail.outbox[0].bcc, ['site_monitor@example.com'])
  581. self.assertEqual(mail.outbox[0].content_subtype, "plain")
  582. def test_preserve_username_case(self):
  583. """
  584. Preserve the case of the user name (before the @ in the email address)
  585. when creating a user (#5605).
  586. """
  587. user = User.objects.create_user('forms_test2', 'tesT@EXAMple.com', 'test')
  588. self.assertEqual(user.email, 'tesT@example.com')
  589. user = User.objects.create_user('forms_test3', 'tesT', 'test')
  590. self.assertEqual(user.email, 'tesT')
  591. def test_inactive_user(self):
  592. """
  593. Test that inactive user cannot receive password reset email.
  594. """
  595. (user, username, email) = self.create_dummy_user()
  596. user.is_active = False
  597. user.save()
  598. form = PasswordResetForm({'email': email})
  599. self.assertTrue(form.is_valid())
  600. form.save()
  601. self.assertEqual(len(mail.outbox), 0)
  602. def test_unusable_password(self):
  603. user = User.objects.create_user('testuser', 'test@example.com', 'test')
  604. data = {"email": "test@example.com"}
  605. form = PasswordResetForm(data)
  606. self.assertTrue(form.is_valid())
  607. user.set_unusable_password()
  608. user.save()
  609. form = PasswordResetForm(data)
  610. # The form itself is valid, but no email is sent
  611. self.assertTrue(form.is_valid())
  612. form.save()
  613. self.assertEqual(len(mail.outbox), 0)
  614. def test_save_plaintext_email(self):
  615. """
  616. Test the PasswordResetForm.save() method with no html_email_template_name
  617. parameter passed in.
  618. Test to ensure original behavior is unchanged after the parameter was added.
  619. """
  620. (user, username, email) = self.create_dummy_user()
  621. form = PasswordResetForm({"email": email})
  622. self.assertTrue(form.is_valid())
  623. form.save()
  624. self.assertEqual(len(mail.outbox), 1)
  625. message = mail.outbox[0].message()
  626. self.assertFalse(message.is_multipart())
  627. self.assertEqual(message.get_content_type(), 'text/plain')
  628. self.assertEqual(message.get('subject'), 'Custom password reset on example.com')
  629. self.assertEqual(len(mail.outbox[0].alternatives), 0)
  630. self.assertEqual(message.get_all('to'), [email])
  631. self.assertTrue(re.match(r'^http://example.com/reset/[\w+/-]', message.get_payload()))
  632. def test_save_html_email_template_name(self):
  633. """
  634. Test the PasswordResetFOrm.save() method with html_email_template_name
  635. parameter specified.
  636. Test to ensure that a multipart email is sent with both text/plain
  637. and text/html parts.
  638. """
  639. (user, username, email) = self.create_dummy_user()
  640. form = PasswordResetForm({"email": email})
  641. self.assertTrue(form.is_valid())
  642. form.save(html_email_template_name='registration/html_password_reset_email.html')
  643. self.assertEqual(len(mail.outbox), 1)
  644. self.assertEqual(len(mail.outbox[0].alternatives), 1)
  645. message = mail.outbox[0].message()
  646. self.assertEqual(message.get('subject'), 'Custom password reset on example.com')
  647. self.assertEqual(len(message.get_payload()), 2)
  648. self.assertTrue(message.is_multipart())
  649. self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain')
  650. self.assertEqual(message.get_payload(1).get_content_type(), 'text/html')
  651. self.assertEqual(message.get_all('to'), [email])
  652. self.assertTrue(re.match(r'^http://example.com/reset/[\w/-]+', message.get_payload(0).get_payload()))
  653. self.assertTrue(re.match(
  654. r'^<html><a href="http://example.com/reset/[\w/-]+/">Link</a></html>$',
  655. message.get_payload(1).get_payload()
  656. ))
  657. class ReadOnlyPasswordHashTest(SimpleTestCase):
  658. def test_bug_19349_render_with_none_value(self):
  659. # Rendering the widget with value set to None
  660. # mustn't raise an exception.
  661. widget = ReadOnlyPasswordHashWidget()
  662. html = widget.render(name='password', value=None, attrs={})
  663. self.assertIn(_("No password set."), html)
  664. def test_readonly_field_has_changed(self):
  665. field = ReadOnlyPasswordHashField()
  666. self.assertFalse(field.has_changed('aaa', 'bbb'))
  667. class AdminPasswordChangeFormTest(TestDataMixin, TestCase):
  668. @mock.patch('django.contrib.auth.password_validation.password_changed')
  669. def test_success(self, password_changed):
  670. user = User.objects.get(username='testclient')
  671. data = {
  672. 'password1': 'test123',
  673. 'password2': 'test123',
  674. }
  675. form = AdminPasswordChangeForm(user, data)
  676. self.assertTrue(form.is_valid())
  677. form.save(commit=False)
  678. self.assertEqual(password_changed.call_count, 0)
  679. form.save()
  680. self.assertEqual(password_changed.call_count, 1)
  681. def test_password_whitespace_not_stripped(self):
  682. user = User.objects.get(username='testclient')
  683. data = {
  684. 'password1': ' pass ',
  685. 'password2': ' pass ',
  686. }
  687. form = AdminPasswordChangeForm(user, data)
  688. self.assertTrue(form.is_valid())
  689. self.assertEqual(form.cleaned_data['password1'], data['password1'])
  690. self.assertEqual(form.cleaned_data['password2'], data['password2'])