test_forms.py 26 KB

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