test_forms.py 28 KB

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