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 registration 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_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.get_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_username_lowercase(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.RegistrationFormUsernameLowercase( data={ 'username': '******', 'email': '*****@*****.**', 'password1': 'foo', 'password2': 'foo' }) self.failIf(form.is_valid()) self.assertEqual(form.errors['username'], ["A user with that username already exists."]) form = forms.RegistrationFormUsernameLowercase( data={ 'username': '******', 'email': '*****@*****.**', 'password1': 'foo', 'password2': 'foo' }) self.failUnless(form.is_valid())
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_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, 'registration/activate.html') user = UserModel().objects.get(username='******') self.assertFalse(user.is_active)
def test_expired_user_deletion_ignore_activated(self): """ ``RegistrationProfile.objects.delete_expired_users()`` only deletes inactive users whose activation window has expired and if their profile is not activated. """ user = (self.registration_profile.objects .create_inactive_user( site=Site.objects.get_current(), username='******', password='******', email='*****@*****.**')) profile = self.registration_profile.objects.get(user=user) _, activated = self.registration_profile.objects.activate_user( profile.activation_key, Site.objects.get_current()) self.assertTrue(activated) # Expire the activation window. user.date_joined -= datetime.timedelta( days=settings.ACCOUNT_ACTIVATION_DAYS + 1) user.save() self.registration_profile.objects.delete_expired_users() self.assertEqual(self.registration_profile.objects.count(), 1) self.assertEqual(UserModel().objects.get(username='******'), user)
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() request = request_factory.post('/', data={ 'username': '******', 'email': '*****@*****.**', 'password1': 'secret', 'password2': 'secret' }) request.user = AnonymousUser() view(request) UserModel().objects.get(username='******') # A registration 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_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) user, activated = self.registration_profile.objects.activate_user( profile.activation_key, Site.objects.get_current()) self.failUnless(isinstance(user, UserModel())) self.assertTrue(activated) 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_falls_back_to_django_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_activation_email_uses_site_address_improperly_configured(self): """ ``RegistrationProfile.send_activation_email`` won't send an email if improperly configured. """ new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) with self.assertRaises(ImproperlyConfigured): profile.send_activation_email(Site.objects.get_current())
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. """ 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_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_admin_approval_complete_email_falls_back_to_django_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_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_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_uses_site_address(self): """ ``RegistrationProfile.send_activation_email`` sends an email with the ``from`` address configured by the site. """ new_user = UserModel().objects.create_user(**self.user_info) profile = self.registration_profile.objects.create_profile(new_user) site = Site.objects.get_current() profile.send_activation_email(site) from_email = 'admin@{}'.format(site.domain) self.assertEqual(mail.outbox[0].from_email, from_email)
def test_admin_approval_email_uses_registration_default_from_email(self): """ ``SupervisedRegistrationManager.send_admin_approve_email``` sends an email. """ 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(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_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_expired_user_deletion_activation_window(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_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) user, activated = self.registration_profile.objects.activate_user( profile.activation_key, Site.objects.get_current()) self.failIf(isinstance(user, 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_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.REGISTRATION_ADMINS] for email in mail.outbox[0].to: self.assertIn(email, admins_emails)
def test_profile_creation(self): """ Creating a registration 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_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) user, activated = self.registration_profile.objects.activate_user( profile.activation_key, Site.objects.get_current()) self.failUnless(isinstance(user, UserModel())) self.assertEqual(user.id, new_user.id) self.failIf(user.is_active) self.assertTrue(activated) profile = self.registration_profile.objects.get(user=new_user) self.assertTrue(profile.activated)
def test_activation_key_backwards_compatibility(self): """ Make sure that users created with 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 user, activated = self.registration_profile.objects.activate_user( profile.activation_key, Site.objects.get_current()) self.failUnless(isinstance(user, UserModel())) self.assertEqual(user.id, new_user.id) self.failIf(user.is_active) self.assertTrue(activated) profile = self.registration_profile.objects.get(user=new_user) self.assertTrue(profile.activated)
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())