def test_registration_no_sites(self): """ Registration still functions properly when ``django.contrib.sites`` is not installed; the fallback will be a ``RequestSite`` instance. """ resp = self.client.post(reverse('registration_register'), data={ 'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret' }) self.assertEqual(302, resp.status_code) new_user = UserModel().objects.get(username='******') self.failUnless(new_user.check_password('secret')) self.assertEqual(new_user.email, '*****@*****.**') self.failIf(new_user.is_active) self.assertEqual(self.registration_profile.objects.count(), 1) self.assertEqual(len(mail.outbox), 1)
def test_expired_user_deletion_missing_user(self): """ ``RegistrationProfile.objects.delete_expired_users()`` only deletes inactive users whose activation window has expired. If a ``UserModel`` is not present, the delete continues gracefully. """ self.registration_profile.objects.create_inactive_user( site=Site.objects.get_current(), **self.user_info) expired_user = (self.registration_profile.objects .create_inactive_user( site=Site.objects.get_current(), username='******', password='******', email='*****@*****.**')) expired_user.date_joined -= datetime.timedelta( days=settings.ACCOUNT_ACTIVATION_DAYS + 1) expired_user.save() # Ensure that we cleanup the expired profile even if the user does not # exist expired_user.delete() self.registration_profile.objects.delete_expired_users() self.assertEqual(self.registration_profile.objects.count(), 1) self.assertRaises(UserModel().DoesNotExist, UserModel().objects.get, username='******')
def test_registration(self): """ Registration creates a new inactive account and a new profile with activation key, populates the correct account data and sends an activation email. """ resp = self.client.post(reverse('registration_register'), data={ 'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret' }) self.assertRedirects(resp, reverse('registration_complete')) new_user = UserModel().objects.get(username='******') self.failUnless(new_user.check_password('secret')) self.assertEqual(new_user.email, '*****@*****.**') # New user must not be active. self.failIf(new_user.is_active) # A account profile was created, and an activation email # was sent. self.assertEqual(self.registration_profile.objects.count(), 1) self.assertEqual(len(mail.outbox), 1)
def test_registration(self): """ Registration creates a new account and logs the user in. """ resp = self.client.post(reverse('registration_register'), data={ 'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret' }) new_user = UserModel().objects.get(username='******') self.assertEqual(302, resp.status_code) self.failUnless(reverse('registration_complete') in resp['Location']) self.failUnless(new_user.check_password('secret')) self.assertEqual(new_user.email, '*****@*****.**') # New user must be active. self.failUnless(new_user.is_active) # New user must be logged in. resp = self.client.get(reverse('registration_register')) self.failUnless(resp.context['user'].is_authenticated())
def test_activation_expired(self): """ An expired account can't be activated. """ resp = self.client.post(reverse('registration_register'), data={ 'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret' }) profile = self.registration_profile.objects.get(user__username='******') user = profile.user user.date_joined -= datetime.timedelta( days=settings.ACCOUNT_ACTIVATION_DAYS) user.save() resp = self.client.get( reverse('registration_activate', args=(), kwargs={'activation_key': profile.activation_key})) self.assertEqual(200, resp.status_code) self.assertTemplateUsed(resp, 'account/activation.html') user = UserModel().objects.get(username='******') self.assertFalse(user.is_active)
def test_approval(self): """ Approval of an account functions properly. """ resp = self.client.post(reverse('registration_register'), data={'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret'}) profile = self.registration_profile.objects.get(user__username='******') resp = self.client.get( reverse('registration_activate', args=(), kwargs={'activation_key': profile.activation_key})) admin_user = UserModel().objects.create_superuser('admin', '*****@*****.**', 'admin') self.client.login(username=admin_user.username, password=admin_user) resp = self.client.get( reverse('registration_admin_approve', args=(), kwargs={'profile_id': profile.id})) user = profile.user # fail if the user is active (this should not happen yet) self.failIf(not user.is_active) self.assertRedirects(resp, reverse('registration_approve_complete'))
def test_registration_form_unique_email(self): """ Test that ``RegistrationFormUniqueEmail`` validates uniqueness of email addresses. """ # Create a user so we can verify that duplicate addresses # aren't permitted. UserModel().objects.create_user('alice', '*****@*****.**', 'secret') form = forms.RegistrationFormUniqueEmail( data={ 'username': '******', 'email': '*****@*****.**', 'password1': 'foo', 'password2': 'foo' }) self.failIf(form.is_valid()) self.assertEqual(form.errors['email'], [ "This email address is already in use. Please supply a different email address." ]) form = forms.RegistrationFormUniqueEmail( data={ 'username': '******', 'email': '*****@*****.**', 'password1': 'foo', 'password2': 'foo' }) self.failUnless(form.is_valid())
def test_activation_key_backwards_compatibility(self): """ Make sure that users created witht the old create_new_activation_key method can still be activated. """ current_method = self.registration_profile.create_new_activation_key def old_method(self, save=True): salt = hashlib.sha1(six.text_type(random.random()) .encode('ascii')).hexdigest()[:5] salt = salt.encode('ascii') user_pk = str(self.user.pk) if isinstance(user_pk, six.text_type): user_pk = user_pk.encode('utf-8') self.activation_key = hashlib.sha1(salt + user_pk).hexdigest() if save: self.save() return self.activation_key self.registration_profile.create_new_activation_key = old_method new_user = self.registration_profile.objects.create_inactive_user( site=Site.objects.get_current(), **self.user_info) profile = self.registration_profile.objects.get(user=new_user) self.registration_profile.create_new_activation_key = current_method activated = (self.registration_profile.objects .activate_user(profile.activation_key)) self.failUnless(isinstance(activated, UserModel())) self.assertEqual(activated.id, new_user.id) self.failIf(activated.is_active) profile = self.registration_profile.objects.get(user=new_user) self.assertTrue(profile.activated)
def test_admin_approval_already_approved(self): """ Approving an already approved user's account returns the User model """ new_user = self.registration_profile.objects.create_inactive_user( site=Site.objects.get_current(), **self.user_info) profile = self.registration_profile.objects.get(user=new_user) activated = (self.registration_profile.objects .activate_user(profile.activation_key)) self.failUnless(isinstance(activated, UserModel())) user = self.registration_profile.objects.admin_approve_user( profile.id, Site.objects.get_current()) self.failUnless(isinstance(user, UserModel())) self.assertEqual(user.is_active, True)
def test_activation_email_uses_registration_default_from_email(self): """ ``RegistrationProfile.send_activation_email`` sends an email. """ new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) profile.send_activation_email(Site.objects.get_current()) self.assertEqual(mail.outbox[0].from_email, '*****@*****.**')
def test_admin_approval_complete_email_uses_registration_default_from_email(self): """ ``SupervisedRegistrationManager.send_admin_approve_complete_email`` sends an email """ new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) profile.send_admin_approve_complete_email(Site.objects.get_current()) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].from_email, '*****@*****.**')
def test_admin_approval_complete_email_is_html_by_default(self): """ ``SupervisedRegistrationProfile.send_admin_approve_complete_email`` sends an html email by default. """ new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) profile.send_admin_approve_complete_email(Site.objects.get_current()) self.assertEqual(len(mail.outbox), 1) self.assertEqual(len(mail.outbox[0].alternatives), 1)
def test_activation_email_missing_template(self): """ ``RegistrationProfile.send_activation_email`` sends an email. """ new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) profile.send_activation_email(Site.objects.get_current()) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, [self.user_info['email']])
def test_admin_approval_complete_email(self): """ ``SupervisedRegistrationManager.send_admin_approve_complete_email`` sends an email to the approved user """ new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) profile.send_admin_approve_complete_email(Site.objects.get_current()) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, [self.user_info['email']])
def test_activation_email_falls_back_to_django_default_from_email(self): """ ``RegistrationProfile.send_activation_email`` sends an email. """ settings.REGISTRATION_DEFAULT_FROM_EMAIL = None new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) profile.send_activation_email(Site.objects.get_current()) self.assertEqual(mail.outbox[0].from_email, '*****@*****.**')
def test_management_command(self): """ The ``cleanupregistration`` management command properly deletes expired accounts. """ self.registration_profile.objects.create_inactive_user( site=Site.objects.get_current(), **self.user_info) expired_user = (self.registration_profile.objects .create_inactive_user(site=Site.objects.get_current(), username='******', password='******', email='*****@*****.**')) expired_user.date_joined -= datetime.timedelta( days=settings.ACCOUNT_ACTIVATION_DAYS + 1) expired_user.save() management.call_command('cleanupregistration') self.assertEqual(self.registration_profile.objects.count(), 1) self.assertRaises(UserModel().DoesNotExist, UserModel().objects.get, username='******')
def test_admin_approval_complete_email_falls_back_to_django_default_from_email(self): """ ``SupervisedRegistrationManager.send_admin_approve_complete_email`` sends an email """ settings.REGISTRATION_DEFAULT_FROM_EMAIL = None new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) profile.send_admin_approve_complete_email(Site.objects.get_current()) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].from_email, '*****@*****.**')
def test_admin_approval_nonexistent_id(self): """ Approving a non existent user profile does nothing and returns False """ new_user = self.registration_profile.objects.create_inactive_user( site=Site.objects.get_current(), **self.user_info) profile = self.registration_profile.objects.get(user=new_user) user = self.registration_profile.objects.admin_approve_user( profile.id, Site.objects.get_current()) self.failIf(isinstance(user, UserModel())) self.assertEqual(user, False)
def test_activation_email_is_plain_text_if_html_disabled(self): """ ``RegistrationProfile.send_activation_email`` sends a plain text email if settings.REGISTRATION_EMAIL_HTML is False. """ settings.REGISTRATION_EMAIL_HTML = False new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) profile.send_activation_email(Site.objects.get_current()) self.assertEqual(len(mail.outbox[0].alternatives), 0)
def test_expired_user_deletion(self): """ ``RegistrationProfile.objects.delete_expired_users()`` only deletes inactive users whose activation window has expired. """ self.registration_profile.objects.create_inactive_user( site=Site.objects.get_current(), **self.user_info) expired_user = (self.registration_profile.objects .create_inactive_user( site=Site.objects.get_current(), username='******', password='******', email='*****@*****.**')) expired_user.date_joined -= datetime.timedelta( days=settings.ACCOUNT_ACTIVATION_DAYS + 1) expired_user.save() self.registration_profile.objects.delete_expired_users() self.assertEqual(self.registration_profile.objects.count(), 1) self.assertRaises(UserModel().DoesNotExist, UserModel().objects.get, username='******')
def test_admin_approval_not_activated(self): """ Approving a non activated user's account fails """ new_user = self.registration_profile.objects.create_inactive_user( site=Site.objects.get_current(), **self.user_info) profile = self.registration_profile.objects.get(user=new_user) user = self.registration_profile.objects.admin_approve_user( profile.id, Site.objects.get_current()) self.failIf(isinstance(user, UserModel())) self.assertEqual(user, False) self.assertEqual(profile.user.is_active, False)
def test_admin_approval_email(self): """ ``SupervisedRegistrationManager.send_admin_approve_email`` sends an email to the site administrators """ new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) profile.activated = True self.registration_profile.objects.send_admin_approve_email( new_user, Site.objects.get_current()) self.assertEqual(len(mail.outbox), 1) admins_emails = [value[1] for value in settings.ADMINS] for email in mail.outbox[0].to: self.assertIn(email, admins_emails)
def test_expired_activation(self): """ Attempting to activate outside the permitted window does not activate the account. """ new_user = self.registration_profile.objects.create_inactive_user( site=Site.objects.get_current(), **self.user_info) new_user.date_joined -= datetime.timedelta( days=settings.ACCOUNT_ACTIVATION_DAYS + 1) new_user.save() profile = self.registration_profile.objects.get(user=new_user) activated = (self.registration_profile.objects .activate_user(profile.activation_key)) self.failIf(isinstance(activated, UserModel())) self.failIf(activated) new_user = UserModel().objects.get(username='******') self.failIf(new_user.is_active) profile = self.registration_profile.objects.get(user=new_user) self.assertFalse(profile.activated)
def test_profile_creation(self): """ Creating a account profile for a user populates the profile with the correct user and a SHA1 hash to use as activation key. """ new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) self.assertEqual(self.registration_profile.objects.count(), 1) self.assertEqual(profile.user.id, new_user.id) self.failUnless(re.match('^[a-f0-9]{40}$', profile.activation_key)) self.assertEqual(six.text_type(profile), "Registration information for alice")
def test_resend_activation_email(self): """ Test the admin custom command 'resend activation email' """ new_user = UserModel().objects.create_user(**self.user_info) profile = RegistrationProfile.objects.create_profile(new_user) registrationprofile_list = urlresolvers.reverse('admin:registration_registrationprofile_changelist') post_data = { 'action': 'resend_activation_email', helpers.ACTION_CHECKBOX_NAME: [profile.pk], } self.client.post(registrationprofile_list, post_data, follow=True) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, [self.user_info['email']])
def test_valid_activation(self): """ Activating a user within the permitted window makes the account active, and resets the activation key. """ new_user = self.registration_profile.objects.create_inactive_user( site=Site.objects.get_current(), **self.user_info) profile = self.registration_profile.objects.get(user=new_user) activated = (self.registration_profile.objects .activate_user(profile.activation_key)) self.failUnless(isinstance(activated, UserModel())) self.assertEqual(activated.id, new_user.id) self.failIf(activated.is_active) profile = self.registration_profile.objects.get(user=new_user) self.assertTrue(profile.activated)
def test_activate_users(self): """ Test the admin custom command 'activate users' """ new_user = UserModel().objects.create_user(**self.user_info) profile = RegistrationProfile.objects.create_profile(new_user) self.assertFalse(profile.activated) registrationprofile_list = urlresolvers.reverse('admin:registration_registrationprofile_changelist') post_data = { 'action': 'activate_users', helpers.ACTION_CHECKBOX_NAME: [profile.pk], } self.client.post(registrationprofile_list, post_data, follow=True) profile = RegistrationProfile.objects.get(user=new_user) self.assertTrue(profile.activated)
def setUp(self): self.client = Client() admin_user = UserModel().objects.create_superuser('admin', '*****@*****.**', 'admin') self.client.login(username=admin_user.username, password=admin_user) self.user_info = {'username': '******', 'password': '******', 'email': '*****@*****.**'} self.old_activation = getattr(settings, 'ACCOUNT_ACTIVATION_DAYS', None) self.old_reg_email = getattr(settings, 'REGISTRATION_DEFAULT_FROM_EMAIL', None) self.old_email_html = getattr(settings, 'REGISTRATION_EMAIL_HTML', None) self.old_django_email = getattr(settings, 'DEFAULT_FROM_EMAIL', None) settings.ACCOUNT_ACTIVATION_DAYS = 7 settings.REGISTRATION_DEFAULT_FROM_EMAIL = '*****@*****.**' settings.REGISTRATION_EMAIL_HTML = True settings.DEFAULT_FROM_EMAIL = '*****@*****.**'
def test_registration_no_email(self): """ Overriden Registration view does not send an activation email if the associated class variable is set to ``False`` """ class RegistrationNoEmailView(self.registration_view): SEND_ACTIVATION_EMAIL = False request_factory = RequestFactory() view = RegistrationNoEmailView.as_view() view( request_factory.post('/', data={ 'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret' })) UserModel().objects.get(username='******') # A account profile was created, and no activation email was sent. self.assertEqual(self.registration_profile.objects.count(), 1) self.assertEqual(len(mail.outbox), 0)
def test_registration_form(self): """ Test that ``RegistrationForm`` enforces username constraints and matching passwords. """ # Create a user so we can verify that duplicate usernames aren't # permitted. UserModel().objects.create_user('alice', '*****@*****.**', 'secret') bad_username_error = ( 'Enter a valid username. This value may contain only letters, ' 'numbers, and @/./+/-/_ characters.') if django.VERSION < (1, 10): bad_username_error = bad_username_error.replace( 'numbers,', 'numbers') elif six.PY2: bad_username_error = bad_username_error.replace( 'letters', 'English letters') invalid_data_dicts = [ # Non-alphanumeric username. { 'data': { 'username': '******', 'email': '*****@*****.**', 'password1': 'foo', 'password2': 'foo' }, 'error': ('username', [bad_username_error]) }, # Already-existing username. { 'data': { 'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret' }, 'error': ('username', ["A user with that username already exists."]) }, # Mismatched passwords. { 'data': { 'username': '******', 'email': '*****@*****.**', 'password1': 'foo', 'password2': 'bar' }, 'error': ('password2', ["The two password fields didn't match."]) }, ] for invalid_dict in invalid_data_dicts: form = forms.RegistrationForm(data=invalid_dict['data']) self.failIf(form.is_valid()) self.assertEqual(form.errors[invalid_dict['error'][0]], invalid_dict['error'][1]) form = forms.RegistrationForm( data={ 'username': '******', 'email': '*****@*****.**', 'password1': 'foo', 'password2': 'foo' }) self.failUnless(form.is_valid())