예제 #1
0
    def setUp(self):
        self.backend = DefaultRegistrationBackend()
        self.mock_request = mock_request()
        self.admin = User.objects.create_superuser(username='******',
                                                   email='*****@*****.**',
                                                   password='******')

        self.client.login(username='******', password='******')
        self.admin_url = reverse('admin:index')
예제 #2
0
    def test_invite_to_slack(self):
        """
        Personaがacceptされたとき、Slackに自動的に招待する
        """
        request = mock_request()
        backend = DefaultRegistrationBackend()

        with patch.object(SlackInvitationClient, 'invite') as invite:
            new_user = backend.register(username='******',
                                        email='*****@*****.**',
                                        request=request)

            profile = new_user.registration_profile
            backend.accept(profile, request=request)

            invite.assert_called_with('*****@*****.**')
예제 #3
0
    def test_invite_to_slack(self):
        """
        Personaがacceptされたとき、Slackに自動的に招待する
        """
        request = mock_request()
        backend = DefaultRegistrationBackend()

        with patch.object(SlackInvitationClient, 'invite') as invite:
            new_user = backend.register(
                username='******', email='*****@*****.**',
                request=request)

            profile = new_user.registration_profile
            backend.accept(profile, request=request)

            invite.assert_called_with('*****@*****.**')
예제 #4
0
파일: tests.py 프로젝트: glisti/horsys
class RegistrationAutoLoginTestCase(TestCase):
    backend = DefaultRegistrationBackend()
    mock_request = mock_request()

    def test_no_auto_login_with_setting(self):
        """Auto login feature should be able to off with ``REGISTRATION_AUTO_LOGIN = False``"""
        self.mock_request.user = AnonymousUser()

        with override_settings(REGISTRATION_AUTO_LOGIN = False):

            new_user = self.backend.register(
                    'bob', '*****@*****.**', request=self.mock_request,
                )
            self.backend.accept(
                    new_user.registration_profile, request=self.mock_request,
                )
            self.backend.activate(
                    new_user.registration_profile.activation_key,
                    password='******',request=self.mock_request,
                )

            self.failIf(self.mock_request.user.is_authenticated())

    def test_no_auto_login_with_no_password(self):
        """Auto login feature should not be occur with no password 
        (programatically activated by Django Admin action)
        
        """
        self.mock_request.user = AnonymousUser()

        new_user = self.backend.register(
                'bob', '*****@*****.**', request=self.mock_request,
            )
        self.backend.accept(
                new_user.registration_profile, request=self.mock_request,
            )
        self.backend.activate(
                new_user.registration_profile.activation_key,
                request=self.mock_request,
            )

        self.failIf(self.mock_request.user.is_authenticated())

    def test_auto_login(self):
        """Wheather auto login feature works correctly"""
        self.mock_request.user = AnonymousUser()

        new_user = self.backend.register(
                'bob', '*****@*****.**', request=self.mock_request,
            )
        self.backend.accept(
                new_user.registration_profile, request=self.mock_request,
            )
        self.backend.activate(
                new_user.registration_profile.activation_key,
                password='******',request=self.mock_request,
            )

        self.failUnless(self.mock_request.user.is_authenticated())
    def setUp(self):
        self.backend = DefaultRegistrationBackend()
        self.mock_request = mock_request()
        self.admin = User.objects.create_superuser(
                username='******', email='*****@*****.**',
                password='******')

        self.client.login(username='******', password='******')
        self.admin_url = reverse('admin:index')
 def setUp(self):
     self.backend = DefaultRegistrationBackend()
     self.mock_request = mock_request()
class DefaultRegistrationBackendTestCase(TestCase):

    def setUp(self):
        self.backend = DefaultRegistrationBackend()
        self.mock_request = mock_request()


    def test_registration(self):
        new_user = self.backend.register(
                username='******', email='*****@*****.**',
                request=self.mock_request)

        self.assertEqual(new_user.username, 'bob')
        self.assertEqual(new_user.email, '*****@*****.**')

        self.failIf(new_user.is_active)
        self.failIf(new_user.has_usable_password())

        # A inspection profile was created, and an registration email
        # was sent.
        self.assertEqual(RegistrationProfile.objects.count(), 1)
        self.assertEqual(len(mail.outbox), 1)

    def test_acceptance(self):
        new_user = self.backend.register(
                username='******', email='*****@*****.**',
                request=self.mock_request)

        profile = new_user.registration_profile
        accepted_user = self.backend.accept(profile, request=self.mock_request)

        self.failUnless(accepted_user)
        self.assertEqual(profile, accepted_user.registration_profile)
        self.assertEqual(profile.status, 'accepted')
        self.assertNotEqual(profile.activation_key, None)

    def test_rejection(self):
        new_user = self.backend.register(
                username='******', email='*****@*****.**',
                request=self.mock_request)

        profile = new_user.registration_profile
        rejected_user = self.backend.reject(profile, request=self.mock_request)

        self.failUnless(rejected_user)
        self.assertEqual(profile, rejected_user.registration_profile)
        self.assertEqual(profile.status, 'rejected')
        self.assertEqual(profile.activation_key, None)

    def test_activation_with_password(self):
        new_user = self.backend.register(
                username='******', email='*****@*****.**',
                request=self.mock_request)

        profile = new_user.registration_profile
        self.backend.accept(profile, request=self.mock_request)
        activated_user = self.backend.activate(
                activation_key=profile.activation_key,
                request=self.mock_request,
                password='******')

        self.failUnless(activated_user)
        self.assertEqual(activated_user, new_user)
        self.failUnless(activated_user.is_active)
        self.failUnless(activated_user.has_usable_password())
        self.failUnless(activated_user.check_password('swardfish'))

    def test_activation_without_password(self):
        new_user = self.backend.register(
                username='******', email='*****@*****.**',
                request=self.mock_request)

        profile = new_user.registration_profile
        self.backend.accept(profile, request=self.mock_request)
        activated_user = self.backend.activate(
                activation_key=profile.activation_key,
                request=self.mock_request)

        self.failUnless(activated_user)
        self.assertEqual(activated_user, new_user)
        self.failUnless(activated_user.is_active)
        self.failUnless(activated_user.has_usable_password())

    def test_untreated_activation(self):
        User = get_user_model()
        new_user = self.backend.register(
                username='******', email='*****@*****.**',
                request=self.mock_request)

        profile = new_user.registration_profile
        activated_user = self.backend.activate(
                activation_key=profile.activation_key,
                request=self.mock_request,
                password='******')

        self.failIf(activated_user)
        new_user = User.objects.get(pk=new_user.pk)
        self.failIf(new_user.is_active)
        self.failIf(new_user.has_usable_password())

    def test_rejected_activation(self):
        User = get_user_model()
        new_user = self.backend.register(
                username='******', email='*****@*****.**',
                request=self.mock_request)

        profile = new_user.registration_profile
        self.backend.reject(profile, request=self.mock_request)
        activated_user = self.backend.activate(
                activation_key=profile.activation_key,
                request=self.mock_request,
                password='******')

        self.failIf(activated_user)
        new_user = User.objects.get(pk=new_user.pk)
        self.failIf(new_user.is_active)
        self.failIf(new_user.has_usable_password())

    def test_expired_activation(self):
        User = get_user_model()
        expired_user = self.backend.register(
                username='******', email='*****@*****.**',
                request=self.mock_request)

        profile = expired_user.registration_profile
        self.backend.accept(profile, request=self.mock_request)

        expired_user.date_joined -= datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS+1)
        expired_user.save()

        activated_user = self.backend.activate(
                activation_key=profile.activation_key,
                request=self.mock_request,
                password='******')

        self.failIf(activated_user)
        expired_user = User.objects.get(pk=expired_user.pk)
        self.failIf(expired_user.is_active)
        self.failIf(expired_user.has_usable_password())

    def test_allow(self):
        old_allowed = settings.REGISTRATION_OPEN
        settings.REGISTRATION_OPEN = True
        self.failUnless(self.backend.registration_allowed())

        settings.REGISTRATION_OPEN = False
        self.failIf(self.backend.registration_allowed())
        settings.REGISTRATION_OPEN = old_allowed

    def test_get_registration_form_class(self):
        form_class = self.backend.get_registration_form_class()
        self.failUnless(form_class is forms.RegistrationForm)

    def test_get_activation_form_class(self):
        form_class = self.backend.get_activation_form_class()
        self.failUnless(form_class is forms.ActivationForm)

    def test_get_registration_complete_url(self):
        User = get_user_model()
        fake_user = User()
        url = self.backend.get_registration_complete_url(fake_user)
        self.assertEqual(url, reverse('registration_complete'))

    def test_get_registration_closed_url(self):
        url = self.backend.get_registration_closed_url()
        self.assertEqual(url, reverse('registration_disallowed'))

    def test_get_activation_complete_url(self):
        User = get_user_model()
        fake_user = User()
        url = self.backend.get_activation_complete_url(fake_user)
        self.assertEqual(url, reverse('registration_activation_complete'))

    def test_registration_signal(self):
        def receiver(sender, user, profile, **kwargs):
            self.assertEqual(user.username, 'bob')
            self.assertEqual(user.registration_profile, profile)
            received_signals.append(kwargs.get('signal'))

        received_signals = []
        signals.user_registered.connect(receiver, sender=self.backend.__class__)

        self.backend.register(username='******', email='*****@*****.**', request=self.mock_request)

        self.assertEqual(len(received_signals), 1)
        self.assertEqual(received_signals, [signals.user_registered])

    def test_acceptance_signal(self):
        def receiver(sender, user, profile, **kwargs):
            self.assertEqual(user.username, 'bob')
            self.assertEqual(user.registration_profile, profile)
            received_signals.append(kwargs.get('signal'))

        received_signals = []
        signals.user_accepted.connect(receiver, sender=self.backend.__class__)

        self.backend.register(username='******', email='*****@*****.**', request=self.mock_request)
        profile = RegistrationProfile.objects.get(user__username='******')
        self.backend.accept(profile, request=self.mock_request)

        self.assertEqual(len(received_signals), 1)
        self.assertEqual(received_signals, [signals.user_accepted])

    def test_acceptance_signal_fail(self):
        def receiver(sender, user, profile, **kwargs):
            self.assertEqual(user.username, 'bob')
            self.assertEqual(user.registration_profile, profile)
            received_signals.append(kwargs.get('signal'))

        received_signals = []

        self.backend.register(username='******', email='*****@*****.**', request=self.mock_request)
        profile = RegistrationProfile.objects.get(user__username='******')
        self.backend.accept(profile, request=self.mock_request)

        signals.user_accepted.connect(receiver, sender=self.backend.__class__)
        # accept -> accept is not allowed thus fail
        self.backend.accept(profile, request=self.mock_request)

        self.assertEqual(len(received_signals), 0)

    def test_rejection_signal(self):
        def receiver(sender, user, profile, **kwargs):
            self.assertEqual(user.username, 'bob')
            self.assertEqual(user.registration_profile, profile)
            received_signals.append(kwargs.get('signal'))

        received_signals = []
        signals.user_rejected.connect(receiver, sender=self.backend.__class__)

        self.backend.register(username='******', email='*****@*****.**', request=self.mock_request)
        profile = RegistrationProfile.objects.get(user__username='******')
        self.backend.reject(profile, request=self.mock_request)

        self.assertEqual(len(received_signals), 1)
        self.assertEqual(received_signals, [signals.user_rejected])

    def test_rejection_signal_fail(self):
        def receiver(sender, user, profile, **kwargs):
            self.assertEqual(user.username, 'bob')
            self.assertEqual(user.registration_profile, profile)
            received_signals.append(kwargs.get('signal'))

        received_signals = []
        signals.user_rejected.connect(receiver, sender=self.backend.__class__)

        self.backend.register(username='******', email='*****@*****.**', request=self.mock_request)
        profile = RegistrationProfile.objects.get(user__username='******')
        self.backend.accept(profile, request=self.mock_request)
        # accept -> reject is not allowed
        self.backend.reject(profile, request=self.mock_request)

        self.assertEqual(len(received_signals), 0)

    def test_activation_signal(self):
        def receiver(sender, user, password, is_generated, **kwargs):
            self.assertEqual(user.username, 'bob')
            self.assertEqual(password, 'swordfish')
            self.failIf(is_generated)
            received_signals.append(kwargs.get('signal'))

        received_signals = []
        signals.user_activated.connect(receiver, sender=self.backend.__class__)

        self.backend.register(username='******', email='*****@*****.**', request=self.mock_request)
        profile = RegistrationProfile.objects.get(user__username='******')
        self.backend.accept(profile, request=self.mock_request)
        self.backend.activate(profile.activation_key, request=self.mock_request, password='******')

        self.assertEqual(len(received_signals), 1)
        self.assertEqual(received_signals, [signals.user_activated])
class RegistrationViewTestCase(TestCase):

    def setUp(self):
        self.backend = DefaultRegistrationBackend()
        self.mock_request = mock_request()


    def test_registration_view_get(self):
        """
        A ``GET`` to the ``register`` view uses the appropriate
        template and populates the registration form into the context.

        """
        response = self.client.get(reverse('registration_register'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response,
                                'registration/registration_form.html')
        self.failUnless(isinstance(response.context['form'],
                                   forms.RegistrationForm))

    def test_registration_view_post_success(self):
        """
        A ``POST`` to the ``register`` view with valid data properly
        creates a new user and issues a redirect.

        """
        response = self.client.post(reverse('registration_register'),
                                    data={'username': '******',
                                          'email1': '*****@*****.**',
                                          'email2': '*****@*****.**'})
        self.assertRedirects(response,
                             'http://testserver%s' % reverse('registration_complete'))
        self.assertEqual(RegistrationProfile.objects.count(), 1)
        self.assertEqual(len(mail.outbox), 1)

    def test_registration_view_post_failure(self):
        """
        A ``POST`` to the ``register`` view with invalid data does not
        create a user, and displays appropriate error messages.

        """
        response = self.client.post(reverse('registration_register'),
                                    data={'username': '******',
                                          'email1': '*****@*****.**',
                                          'email2': '*****@*****.**'})
        self.assertEqual(response.status_code, 200)
        self.failIf(response.context['form'].is_valid())
        self.assertFormError(response, 'form', field=None,
                             errors="The two email fields didn't match.")
        self.assertEqual(len(mail.outbox), 0)

    def test_registration_complete_view_get(self):
        """
        A ``GET`` to the ``complete`` view uses the appropriate
        template and populates the registration form into the context.

        """
        # register save registration_profile in the session
        response = self.client.post(reverse('registration_register'),
                                    data={'username': '******',
                                          'email1': '*****@*****.**',
                                          'email2': '*****@*****.**'})
        response = self.client.get(reverse('registration_complete'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response,
                                'registration/registration_complete.html')
        self.failUnless(isinstance(response.context['registration_profile'],
                                   RegistrationProfile))
        profile = response.context['registration_profile']
        self.assertEqual(profile.user.username, 'alice')
        self.assertEqual(profile.user.email, '*****@*****.**')

    def test_registration_view_closed(self):
        """
        Any attempt to access the ``register`` view when registration
        is closed fails and redirects.

        """
        settings.REGISTRATION_OPEN = False

        closed_redirect = 'http://testserver%s' % reverse('registration_disallowed')

        response = self.client.get(reverse('registration_register'))
        self.assertRedirects(response, closed_redirect)

        # Even if valid data is posted, it still shouldn't work.
        response = self.client.post(reverse('registration_register'),
                                    data={'username': '******',
                                          'email1': '*****@*****.**',
                                          'email2': '*****@*****.**'})
        self.assertRedirects(response, closed_redirect)
        self.assertEqual(RegistrationProfile.objects.count(), 0)

        settings.REGISTRATION_OPEN = True

    def test_activation_view_get_success(self):
        """
        A ``GET`` to the ``ActivationView`` view with valid activation_key

        """
        new_user = self.backend.register(username='******', email='*****@*****.**', request=self.mock_request)
        new_user = self.backend.accept(new_user.registration_profile, request=self.mock_request)
    
        activation_url = reverse('registration_activate', kwargs={
            'activation_key': new_user.registration_profile.activation_key})

        response = self.client.get(activation_url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response,
                                'registration/activation_form.html')
        self.failUnless(isinstance(response.context['form'],
                                   forms.ActivationForm))

    def test_activation_view_get_fail(self):
        """
        A ``GET`` to the ``ActivationView`` view wht invalid activation_key 
        raise Http404

        """
        self.backend.register(username='******', email='*****@*****.**', request=self.mock_request)
    
        activation_url = reverse('registration_activate', kwargs={
            'activation_key': 'invalidactivationkey'})

        response = self.client.get(activation_url)
        self.assertEqual(response.status_code, 404)

    def test_activation_view_post_success(self):
        """
        A ``POST`` to the ``ActivationView`` view with valid data properly
        handles a valid activation

        """
        User = get_user_model()
        new_user = self.backend.register(username='******', email='*****@*****.**', request=self.mock_request)
        new_user = self.backend.accept(new_user.registration_profile, request=self.mock_request)
    
        activation_url = reverse('registration_activate', kwargs={
            'activation_key': new_user.registration_profile.activation_key})

        response = self.client.post(activation_url,{
            'password1': 'swordfish',
            'password2': 'swordfish'})

        success_redirect = 'http://testserver%s' % reverse('registration_activation_complete')
        self.assertRedirects(response, success_redirect)
        # RegistrationProfile should be removed with activation
        self.assertEqual(RegistrationProfile.objects.count(), 0)
        # registration, acceptance and activation
        self.assertEqual(len(mail.outbox), 3)
        self.failUnless(User.objects.get(username='******').is_active)

    def test_activation_view_post_failure(self):
        """
        A ``POST`` to the ``ActivationView`` view with invalid data does not
        activate a user, and raise Http404

        """
        expired_user = self.backend.register(username='******', email='*****@*****.**', request=self.mock_request)
        expired_user = self.backend.accept(expired_user.registration_profile, request=self.mock_request)
        expired_user.date_joined -= datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS+1)
        expired_user.save()
    
        activation_url = reverse('registration_activate', kwargs={
            'activation_key': expired_user.registration_profile.activation_key})

        response = self.client.post(activation_url,{
            'password1': 'swordfish',
            'password2': 'swordfish'})

        self.assertEqual(response.status_code, 404)
예제 #9
0
class RegistrationActivatedTestCase(TestCase):
    def setUp(self):
        self.backend = DefaultRegistrationBackend()
        self.mock_request = mock_request()

    def test_activated_user_should_be_children(self):
        """
        新規会員登録が承認されたユーザーのactivationが行われたとき、
        signalを受けて権限をwilleからchildrenに変更する
        """
        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)
        profile = RegistrationProfile.objects.get(user__username='******')
        self.backend.accept(profile, request=self.mock_request)
        user = profile.user

        # Activateする直前まではwille
        self.assertEqual(user.role, 'wille')
        self.backend.activate(profile.activation_key,
                              request=self.mock_request,
                              password='******')
        # Activateしたらちゃんとchildrenになる
        user = Persona.objects.get(pk=user.pk)
        self.assertEqual(user.role, 'children')

    def test_profile_should_be_created_on_activation(self):
        """
        新規会員登録が承認されたとき、profileが生成される
        """
        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)
        registration_profile = RegistrationProfile.objects.get(
            user__username='******')
        self.backend.accept(registration_profile, request=self.mock_request)
        user = registration_profile.user

        # Activateする直前まではProfileが存在しない
        profile_count = Profile.objects.count()
        self.assertRaises(ObjectDoesNotExist, Profile.objects.get, user=user)
        self.backend.activate(registration_profile.activation_key,
                              request=self.mock_request,
                              password='******')

        # ActivateしたらProfileが生成される
        self.assertEqual(Profile.objects.count(), profile_count + 1)
        profile = Profile.objects.get(user=user)
        self.assertIsNotNone(profile)
예제 #10
0
class RegistrationActivatedTestCase(TestCase):
    def setUp(self):
        self.backend = DefaultRegistrationBackend()
        self.mock_request = mock_request()

    def test_activated_user_should_be_children(self):
        """
        新規会員登録が承認されたユーザーのactivationが行われたとき、
        signalを受けて権限をwilleからchildrenに変更する
        """
        self.backend.register(username='******', email='*****@*****.**', request=self.mock_request)
        profile = RegistrationProfile.objects.get(user__username='******')
        self.backend.accept(profile, request=self.mock_request)
        user = profile.user

        # Activateする直前まではwille
        self.assertEqual(user.role, 'wille')
        self.backend.activate(profile.activation_key, request=self.mock_request, password='******')
        # Activateしたらちゃんとchildrenになる
        user = Persona.objects.get(pk=user.pk)
        self.assertEqual(user.role, 'children')

    def test_profile_should_be_created_on_activation(self):
        """
        新規会員登録が承認されたとき、profileが生成される
        """
        self.backend.register(username='******', email='*****@*****.**', request=self.mock_request)
        registration_profile = RegistrationProfile.objects.get(user__username='******')
        self.backend.accept(registration_profile, request=self.mock_request)
        user = registration_profile.user

        # Activateする直前まではProfileが存在しない
        profile_count = Profile.objects.count()
        self.assertRaises(ObjectDoesNotExist, Profile.objects.get, user=user)
        self.backend.activate(registration_profile.activation_key, request=self.mock_request, password='******')

        # ActivateしたらProfileが生成される
        self.assertEqual(Profile.objects.count(), profile_count + 1)
        profile = Profile.objects.get(user=user)
        self.assertIsNotNone(profile)
예제 #11
0
 def setUp(self):
     self.backend = DefaultRegistrationBackend()
     self.mock_request = mock_request()
예제 #12
0
class DefaultRegistrationBackendTestCase(TestCase):
    def setUp(self):
        self.backend = DefaultRegistrationBackend()
        self.mock_request = mock_request()

    def test_registration(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)

        self.assertEqual(new_user.username, 'bob')
        self.assertEqual(new_user.email, '*****@*****.**')

        self.failIf(new_user.is_active)
        self.failIf(new_user.has_usable_password())

        # A inspection profile was created, and an registration email
        # was sent.
        self.assertEqual(RegistrationProfile.objects.count(), 1)
        self.assertEqual(len(mail.outbox), 1)

    def test_acceptance(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)

        profile = new_user.registration_profile
        accepted_user = self.backend.accept(profile, request=self.mock_request)

        self.failUnless(accepted_user)
        self.assertEqual(profile, accepted_user.registration_profile)
        self.assertEqual(profile.status, 'accepted')
        self.assertNotEqual(profile.activation_key, None)

    def test_rejection(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)

        profile = new_user.registration_profile
        rejected_user = self.backend.reject(profile, request=self.mock_request)

        self.failUnless(rejected_user)
        self.assertEqual(profile, rejected_user.registration_profile)
        self.assertEqual(profile.status, 'rejected')
        self.assertEqual(profile.activation_key, None)

    def test_activation_with_password(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)

        profile = new_user.registration_profile
        self.backend.accept(profile, request=self.mock_request)
        activated_user = self.backend.activate(
            activation_key=profile.activation_key,
            request=self.mock_request,
            password='******')

        self.failUnless(activated_user)
        self.assertEqual(activated_user, new_user)
        self.failUnless(activated_user.is_active)
        self.failUnless(activated_user.has_usable_password())
        self.failUnless(activated_user.check_password('swardfish'))

    def test_activation_without_password(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)

        profile = new_user.registration_profile
        self.backend.accept(profile, request=self.mock_request)
        activated_user = self.backend.activate(
            activation_key=profile.activation_key, request=self.mock_request)

        self.failUnless(activated_user)
        self.assertEqual(activated_user, new_user)
        self.failUnless(activated_user.is_active)
        self.failUnless(activated_user.has_usable_password())

    def test_untreated_activation(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)

        profile = new_user.registration_profile
        activated_user = self.backend.activate(
            activation_key=profile.activation_key,
            request=self.mock_request,
            password='******')

        self.failIf(activated_user)
        new_user = User.objects.get(pk=new_user.pk)
        self.failIf(new_user.is_active)
        self.failIf(new_user.has_usable_password())

    def test_rejected_activation(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)

        profile = new_user.registration_profile
        self.backend.reject(profile, request=self.mock_request)
        activated_user = self.backend.activate(
            activation_key=profile.activation_key,
            request=self.mock_request,
            password='******')

        self.failIf(activated_user)
        new_user = User.objects.get(pk=new_user.pk)
        self.failIf(new_user.is_active)
        self.failIf(new_user.has_usable_password())

    def test_expired_activation(self):
        expired_user = self.backend.register(username='******',
                                             email='*****@*****.**',
                                             request=self.mock_request)

        profile = expired_user.registration_profile
        self.backend.accept(profile, request=self.mock_request)

        expired_user.date_joined -= datetime.timedelta(
            days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
        expired_user.save()

        activated_user = self.backend.activate(
            activation_key=profile.activation_key,
            request=self.mock_request,
            password='******')

        self.failIf(activated_user)
        expired_user = User.objects.get(pk=expired_user.pk)
        self.failIf(expired_user.is_active)
        self.failIf(expired_user.has_usable_password())

    def test_allow(self):
        old_allowed = settings.REGISTRATION_OPEN
        settings.REGISTRATION_OPEN = True
        self.failUnless(self.backend.registration_allowed())

        settings.REGISTRATION_OPEN = False
        self.failIf(self.backend.registration_allowed())
        settings.REGISTRATION_OPEN = old_allowed

    def test_get_registration_form_class(self):
        form_class = self.backend.get_registration_form_class()
        self.failUnless(form_class is forms.RegistrationForm)

    def test_get_activation_form_class(self):
        form_class = self.backend.get_activation_form_class()
        self.failUnless(form_class is forms.ActivationForm)

    def test_get_registration_complete_url(self):
        fake_user = User()
        url = self.backend.get_registration_complete_url(fake_user)
        self.assertEqual(url, reverse('registration_complete'))

    def test_get_registration_closed_url(self):
        url = self.backend.get_registration_closed_url()
        self.assertEqual(url, reverse('registration_disallowed'))

    def test_get_activation_complete_url(self):
        fake_user = User()
        url = self.backend.get_activation_complete_url(fake_user)
        self.assertEqual(url, reverse('registration_activation_complete'))

    def test_registration_signal(self):
        def receiver(sender, user, profile, **kwargs):
            self.assertEqual(user.username, 'bob')
            self.assertEqual(user.registration_profile, profile)
            received_signals.append(kwargs.get('signal'))

        received_signals = []
        signals.user_registered.connect(receiver,
                                        sender=self.backend.__class__)

        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)

        self.assertEqual(len(received_signals), 1)
        self.assertEqual(received_signals, [signals.user_registered])

    def test_acceptance_signal(self):
        def receiver(sender, user, profile, **kwargs):
            self.assertEqual(user.username, 'bob')
            self.assertEqual(user.registration_profile, profile)
            received_signals.append(kwargs.get('signal'))

        received_signals = []
        signals.user_accepted.connect(receiver, sender=self.backend.__class__)

        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)
        profile = RegistrationProfile.objects.get(user__username='******')
        self.backend.accept(profile, request=self.mock_request)

        self.assertEqual(len(received_signals), 1)
        self.assertEqual(received_signals, [signals.user_accepted])

    def test_acceptance_signal_fail(self):
        def receiver(sender, user, profile, **kwargs):
            self.assertEqual(user.username, 'bob')
            self.assertEqual(user.registration_profile, profile)
            received_signals.append(kwargs.get('signal'))

        received_signals = []

        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)
        profile = RegistrationProfile.objects.get(user__username='******')
        self.backend.accept(profile, request=self.mock_request)

        signals.user_accepted.connect(receiver, sender=self.backend.__class__)
        # accept -> accept is not allowed thus fail
        self.backend.accept(profile, request=self.mock_request)

        self.assertEqual(len(received_signals), 0)

    def test_rejection_signal(self):
        def receiver(sender, user, profile, **kwargs):
            self.assertEqual(user.username, 'bob')
            self.assertEqual(user.registration_profile, profile)
            received_signals.append(kwargs.get('signal'))

        received_signals = []
        signals.user_rejected.connect(receiver, sender=self.backend.__class__)

        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)
        profile = RegistrationProfile.objects.get(user__username='******')
        self.backend.reject(profile, request=self.mock_request)

        self.assertEqual(len(received_signals), 1)
        self.assertEqual(received_signals, [signals.user_rejected])

    def test_rejection_signal_fail(self):
        def receiver(sender, user, profile, **kwargs):
            self.assertEqual(user.username, 'bob')
            self.assertEqual(user.registration_profile, profile)
            received_signals.append(kwargs.get('signal'))

        received_signals = []
        signals.user_rejected.connect(receiver, sender=self.backend.__class__)

        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)
        profile = RegistrationProfile.objects.get(user__username='******')
        self.backend.accept(profile, request=self.mock_request)
        # accept -> reject is not allowed
        self.backend.reject(profile, request=self.mock_request)

        self.assertEqual(len(received_signals), 0)

    def test_activation_signal(self):
        def receiver(sender, user, password, is_generated, **kwargs):
            self.assertEqual(user.username, 'bob')
            self.assertEqual(password, 'swordfish')
            self.failIf(is_generated)
            received_signals.append(kwargs.get('signal'))

        received_signals = []
        signals.user_activated.connect(receiver, sender=self.backend.__class__)

        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)
        profile = RegistrationProfile.objects.get(user__username='******')
        self.backend.accept(profile, request=self.mock_request)
        self.backend.activate(profile.activation_key,
                              request=self.mock_request,
                              password='******')

        self.assertEqual(len(received_signals), 1)
        self.assertEqual(received_signals, [signals.user_activated])
예제 #13
0
class RegistrationViewTestCase(TestCase):
    def setUp(self):
        self.backend = DefaultRegistrationBackend()
        self.mock_request = mock_request()

    def test_registration_view_get(self):
        """
        A ``GET`` to the ``register`` view uses the appropriate
        template and populates the registration form into the context.

        """
        response = self.client.get(reverse('registration_register'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response,
                                'registration/registration_form.html')
        self.failUnless(
            isinstance(response.context['form'], forms.RegistrationForm))

    def test_registration_view_post_success(self):
        """
        A ``POST`` to the ``register`` view with valid data properly
        creates a new user and issues a redirect.

        """
        response = self.client.post(reverse('registration_register'),
                                    data={
                                        'username': '******',
                                        'email1': '*****@*****.**',
                                        'email2': '*****@*****.**'
                                    })
        self.assertRedirects(
            response, 'http://testserver%s' % reverse('registration_complete'))
        self.assertEqual(RegistrationProfile.objects.count(), 1)
        self.assertEqual(len(mail.outbox), 1)

    def test_registration_view_post_failure(self):
        """
        A ``POST`` to the ``register`` view with invalid data does not
        create a user, and displays appropriate error messages.

        """
        response = self.client.post(reverse('registration_register'),
                                    data={
                                        'username': '******',
                                        'email1': '*****@*****.**',
                                        'email2': '*****@*****.**'
                                    })
        self.assertEqual(response.status_code, 200)
        self.failIf(response.context['form'].is_valid())
        self.assertFormError(response,
                             'form',
                             field=None,
                             errors=u"The two email fields didn't match.")
        self.assertEqual(len(mail.outbox), 0)

    def test_registration_view_closed(self):
        """
        Any attempt to access the ``register`` view when registration
        is closed fails and redirects.

        """
        settings.REGISTRATION_OPEN = False

        closed_redirect = 'http://testserver%s' % reverse(
            'registration_disallowed')

        response = self.client.get(reverse('registration_register'))
        self.assertRedirects(response, closed_redirect)

        # Even if valid data is posted, it still shouldn't work.
        response = self.client.post(reverse('registration_register'),
                                    data={
                                        'username': '******',
                                        'email1': '*****@*****.**',
                                        'email2': '*****@*****.**'
                                    })
        self.assertRedirects(response, closed_redirect)
        self.assertEqual(RegistrationProfile.objects.count(), 0)

        settings.REGISTRATION_OPEN = True

    def test_activation_view_get_success(self):
        """
        A ``GET`` to the ``ActivationView`` view with valid activation_key

        """
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        new_user = self.backend.accept(new_user.registration_profile,
                                       request=self.mock_request)

        activation_url = reverse(
            'registration_activate',
            kwargs={
                'activation_key': new_user.registration_profile.activation_key
            })

        response = self.client.get(activation_url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'registration/activation_form.html')
        self.failUnless(
            isinstance(response.context['form'], forms.ActivationForm))

    def test_activation_view_get_fail(self):
        """
        A ``GET`` to the ``ActivationView`` view wht invalid activation_key 
        raise Http404

        """
        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)

        activation_url = reverse(
            'registration_activate',
            kwargs={'activation_key': 'invalidactivationkey'})

        response = self.client.get(activation_url)
        self.assertEqual(response.status_code, 404)

    def test_activation_view_post_success(self):
        """
        A ``POST`` to the ``ActivationView`` view with valid data properly
        handles a valid activation

        """
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        new_user = self.backend.accept(new_user.registration_profile,
                                       request=self.mock_request)

        activation_url = reverse(
            'registration_activate',
            kwargs={
                'activation_key': new_user.registration_profile.activation_key
            })

        response = self.client.post(activation_url, {
            'password1': 'swordfish',
            'password2': 'swordfish'
        })

        success_redirect = 'http://testserver%s' % reverse(
            'registration_activation_complete')
        self.assertRedirects(response, success_redirect)
        # RegistrationProfile should be removed with activation
        self.assertEqual(RegistrationProfile.objects.count(), 0)
        # registration, acceptance and activation
        self.assertEqual(len(mail.outbox), 3)
        self.failUnless(User.objects.get(username='******').is_active)

    def test_activation_view_post_failure(self):
        """
        A ``POST`` to the ``ActivationView`` view with invalid data does not
        activate a user, and raise Http404

        """
        expired_user = self.backend.register(username='******',
                                             email='*****@*****.**',
                                             request=self.mock_request)
        expired_user = self.backend.accept(expired_user.registration_profile,
                                           request=self.mock_request)
        expired_user.date_joined -= datetime.timedelta(
            days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
        expired_user.save()

        activation_url = reverse(
            'registration_activate',
            kwargs={
                'activation_key':
                expired_user.registration_profile.activation_key
            })

        response = self.client.post(activation_url, {
            'password1': 'swordfish',
            'password2': 'swordfish'
        })

        self.assertEqual(response.status_code, 404)
class RegistrationAdminTestCase(TestCase):
    def setUp(self):
        User = get_user_model()
        self.backend = DefaultRegistrationBackend()
        self.mock_request = mock_request()
        self.admin = User.objects.create_superuser(username='******',
                                                   email='*****@*****.**',
                                                   password='******')

        self.client.login(username='******', password='******')
        self.admin_url = reverse('admin:index')

    def test_change_list_view_get(self):
        url = reverse('admin:registration_registrationprofile_changelist')
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'admin/change_list.html')

    def test_change_view_get(self):
        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)

        url = reverse('admin:registration_registrationprofile_change',
                      args=(1, ))
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html')

    def test_change_view_get_404(self):
        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)

        url = reverse('admin:registration_registrationprofile_change',
                      args=(100, ))
        response = self.client.get(url)

        self.assertEqual(response.status_code, 404)

    def test_change_view_post_valid_accept_from_untreated(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)

        url = reverse('admin:registration_registrationprofile_change',
                      args=(1, ))
        redirect_url = reverse(
            'admin:registration_registrationprofile_changelist')
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'accept'
            })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_valid_accept_from_accepted(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        self.backend.accept(new_user.registration_profile,
                            request=self.mock_request)
        previous_activation_key = new_user.registration_profile.activation_key
        url = reverse('admin:registration_registrationprofile_change',
                      args=(1, ))
        redirect_url = reverse(
            'admin:registration_registrationprofile_changelist')
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'accept'
            })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')
        self.assertNotEqual(profile.activation_key, previous_activation_key)

    def test_change_view_post_valid_accept_from_rejected(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        self.backend.reject(new_user.registration_profile,
                            request=self.mock_request)

        url = reverse('admin:registration_registrationprofile_change',
                      args=(1, ))
        redirect_url = reverse(
            'admin:registration_registrationprofile_changelist')
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'accept'
            })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_valid_reject_from_untreated(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)

        url = reverse('admin:registration_registrationprofile_change',
                      args=(1, ))
        redirect_url = reverse(
            'admin:registration_registrationprofile_changelist')
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'reject'
            })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'rejected')

    def test_change_view_post_invalid_reject_from_accepted(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        self.backend.accept(new_user.registration_profile,
                            request=self.mock_request)

        url = reverse('admin:registration_registrationprofile_change',
                      args=(1, ))
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'reject'
            })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html')
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'], [
                "Select a valid choice. "
                "reject is not one of the available choices."
            ])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_invalid_reject_from_rejected(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        self.backend.reject(new_user.registration_profile,
                            request=self.mock_request)

        url = reverse('admin:registration_registrationprofile_change',
                      args=(1, ))
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'reject'
            })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html')
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'], [
                "Select a valid choice. "
                "reject is not one of the available choices."
            ])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'rejected')

    def test_change_view_post_invalid_activate_from_untreated(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)

        url = reverse('admin:registration_registrationprofile_change',
                      args=(1, ))
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'activate'
            })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html')
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'], [
                "Select a valid choice. "
                "activate is not one of the available choices."
            ])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'untreated')

    def test_change_view_post_valid_activate_from_accepted(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        self.backend.accept(new_user.registration_profile,
                            request=self.mock_request)

        url = reverse('admin:registration_registrationprofile_change',
                      args=(1, ))
        redirect_url = reverse(
            'admin:registration_registrationprofile_changelist')
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'activate'
            })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.filter(user__pk=new_user.pk)
        self.failIf(profile.exists())

    def test_change_view_post_invalid_activate_from_rejected(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        self.backend.reject(new_user.registration_profile,
                            request=self.mock_request)

        url = reverse('admin:registration_registrationprofile_change',
                      args=(1, ))
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'activate'
            })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html')
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'], [
                "Select a valid choice. "
                "activate is not one of the available choices."
            ])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'rejected')

    def test_change_view_post_valid_force_activate_from_untreated(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)

        url = reverse('admin:registration_registrationprofile_change',
                      args=(1, ))
        redirect_url = reverse(
            'admin:registration_registrationprofile_changelist')
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'force_activate'
            })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.filter(user__pk=new_user.pk)
        self.failIf(profile.exists())

    def test_change_view_post_invalid_force_activate_from_accepted(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        self.backend.accept(new_user.registration_profile,
                            request=self.mock_request)

        url = reverse('admin:registration_registrationprofile_change',
                      args=(1, ))
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'force_activate'
            })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html')
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'], [
                "Select a valid choice. "
                "force_activate is not one of the available choices."
            ])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_valid_force_activate_from_rejected(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        self.backend.reject(new_user.registration_profile,
                            request=self.mock_request)

        url = reverse('admin:registration_registrationprofile_change',
                      args=(1, ))
        redirect_url = reverse(
            'admin:registration_registrationprofile_changelist')
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'force_activate'
            })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.filter(user__pk=new_user.pk)
        self.failIf(profile.exists())

    def test_resend_acceptance_email_action(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)
        admin_class.resend_acceptance_email(None,
                                            RegistrationProfile.objects.all())

        # one for registration, one for resend
        self.assertEqual(len(mail.outbox), 2)

    def test_accept_users_action(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)
        admin_class.accept_users(None, RegistrationProfile.objects.all())

        for profile in RegistrationProfile.objects.all():
            self.assertEqual(profile.status, 'accepted')
            self.assertNotEqual(profile.activation_key, None)

    def test_reject_users_action(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)
        admin_class.reject_users(None, RegistrationProfile.objects.all())

        for profile in RegistrationProfile.objects.all():
            self.assertEqual(profile.status, 'rejected')
            self.assertEqual(profile.activation_key, None)

    def test_force_activate_users_action(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)
        admin_class.force_activate_users(None,
                                         RegistrationProfile.objects.all())

        self.assertEqual(RegistrationProfile.objects.count(), 0)

    @override_settings(REGISTRATION_SUPPLEMENT_CLASS=None)
    def test_get_inline_instances_without_supplements(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)
        # Prevent caching
        if hasattr(admin_class.backend, '_supplement_class_cache'):
            delattr(admin_class.backend, '_supplement_class_cache')

        inline_instances = admin_class.get_inline_instances(
            self.mock_request, None)
        self.assertEqual(len(inline_instances), 0)

    @override_settings(
        REGISTRATION_SUPPLEMENT_CLASS=
        "registration.supplements.default.models.DefaultRegistrationSupplement"
    )
    def test_get_inline_instances_with_default_supplements(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)
        # Prevent caching
        if hasattr(admin_class.backend, '_supplement_class_cache'):
            delattr(admin_class.backend, '_supplement_class_cache')

        inline_instances = admin_class.get_inline_instances(
            self.mock_request, None)
        self.assertEqual(len(inline_instances), 1)
예제 #15
0
class RegistrationNotificationTestCase(TestCase):
    backend = DefaultRegistrationBackend()
    mock_request = mock_request()

    def test_notify_admins(self):
        with override_settings(REGISTRATION_NOTIFICATION_MANAGERS=False):
            self.backend.register(
                    'bob', '*****@*****.**', request=self.mock_request
                )

            self.assertEqual(len(mail.outbox), 1)
            self.assertEqual(sorted(mail.outbox[0].to), sorted([
                    '*****@*****.**',
                    '*****@*****.**',
                ]))

    def test_notify_managers(self):
        with override_settings(REGISTRATION_NOTIFICATION_ADMINS=False):
            self.backend.register(
                    'bob', '*****@*****.**', request=self.mock_request
                )

            self.assertEqual(len(mail.outbox), 1)
            self.assertEqual(sorted(mail.outbox[0].to), sorted([
                    '*****@*****.**',
                    '*****@*****.**',
                ]))

    def test_notify_recipients_iterable(self):
        with override_settings(
            REGISTRATION_NOTIFICATION_ADMINS = False,
            REGISTRATION_NOTIFICATION_MANAGERS = False,
            REGISTRATION_NOTIFICATION_RECIPIENTS=(
                    '*****@*****.**',
                    '*****@*****.**',
                )):
            self.backend.register(
                    'bob', '*****@*****.**', request=self.mock_request
                )

            self.assertEqual(len(mail.outbox), 1)
            self.assertEqual(sorted(mail.outbox[0].to), sorted([
                    '*****@*****.**',
                    '*****@*****.**',
                ]))

    def test_notify_recipients_function(self):
        with override_settings(
            REGISTRATION_NOTIFICATION_ADMINS=False,
            REGISTRATION_NOTIFICATION_MANAGERS=False,
            REGISTRATION_NOTIFICATION_RECIPIENTS=lambda:(
                    '*****@*****.**',
                    '*****@*****.**',
                )):
            self.backend.register(
                    'bob', '*****@*****.**', request=self.mock_request
                )

            self.assertEqual(len(mail.outbox), 1)
            self.assertEqual(sorted(mail.outbox[0].to), sorted([
                    '*****@*****.**',
                    '*****@*****.**',
                ]))

    def test_notify_all(self):
        with override_settings(
            REGISTRATION_NOTIFICATION_ADMINS=True,
            REGISTRATION_NOTIFICATION_MANAGERS=True,
            REGISTRATION_NOTIFICATION_RECIPIENTS=(
                    '*****@*****.**',
                    '*****@*****.**',
                )):
            self.backend.register(
                    'bob', '*****@*****.**', request=self.mock_request
                )

            self.assertEqual(len(mail.outbox), 1)
            self.assertEqual(sorted(mail.outbox[0].to), sorted([
                    '*****@*****.**',
                    '*****@*****.**',
                    '*****@*****.**',
                    '*****@*****.**',
                    '*****@*****.**',
                    '*****@*****.**',
                ]))

    def test_notify_duplicated(self):
        with override_settings(
            REGISTRATION_NOTIFICATION_ADMINS=True,
            REGISTRATION_NOTIFICATION_MANAGERS=True,
            REGISTRATION_NOTIFICATION_RECIPIENTS=(
                    '*****@*****.**',
                    '*****@*****.**',
                    '*****@*****.**',
                    '*****@*****.**',
                    '*****@*****.**',
                    '*****@*****.**',
                ),
            ADMINS=(
                    ('admin1', '*****@*****.**'),
                    ('admin2', '*****@*****.**'),
                    ('manager1', '*****@*****.**'), 
                    ('manager2', '*****@*****.**'),
                    ('recipient1', '*****@*****.**'), 
                    ('recipient2', '*****@*****.**'),
                ),
            MANAGERS=(
                    ('admin1', '*****@*****.**'),
                    ('admin2', '*****@*****.**'),
                    ('manager1', '*****@*****.**'), 
                    ('manager2', '*****@*****.**'),
                    ('recipient1', '*****@*****.**'), 
                    ('recipient2', '*****@*****.**'),
                )):
            self.backend.register(
                    'bob', '*****@*****.**', request=self.mock_request
                )

            self.assertEqual(len(mail.outbox), 1)
            self.assertEqual(sorted(mail.outbox[0].to), sorted([
                    '*****@*****.**',
                    '*****@*****.**',
                    '*****@*****.**',
                    '*****@*****.**',
                    '*****@*****.**',
                    '*****@*****.**',
                ]))
예제 #16
0
class RegistrationAdminTestCase(TestCase):
    def setUp(self):
        self.backend = DefaultRegistrationBackend()
        self.mock_request = mock_request()
        self.admin = User.objects.create_superuser(username='******',
                                                   email='*****@*****.**',
                                                   password='******')

        self.client.login(username='******', password='******')
        self.admin_url = reverse('admin:index')

    def test_change_list_view_get(self):
        url = self.admin_url + "registration/registrationprofile/"
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'admin/change_list.html')

    def test_change_view_get(self):
        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html')

    def test_change_view_get_404(self):
        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/100/"
        response = self.client.get(url)

        self.assertEqual(response.status_code, 404)

    def test_change_view_post_valid_accept_from_untreated(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        redirect_url = self.admin_url + "registration/registrationprofile/"
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'accept'
            })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_valid_inaccept_from_accepted(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        self.backend.accept(new_user.registration_profile,
                            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'accept'
            })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html')
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'], [
                u"Select a valid choice. accept is not one of the available choices."
            ])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_valid_accept_from_rejected(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        self.backend.reject(new_user.registration_profile,
                            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        redirect_url = self.admin_url + "registration/registrationprofile/"
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'accept'
            })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_valid_reject_from_untreated(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        redirect_url = self.admin_url + "registration/registrationprofile/"
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'reject'
            })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'rejected')

    def test_change_view_post_invalid_reject_from_accepted(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        self.backend.accept(new_user.registration_profile,
                            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'reject'
            })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html')
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'], [
                u"Select a valid choice. reject is not one of the available choices."
            ])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_invalid_reject_from_rejected(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        self.backend.reject(new_user.registration_profile,
                            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'reject'
            })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html')
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'], [
                u"Select a valid choice. reject is not one of the available choices."
            ])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'rejected')

    def test_change_view_post_invalid_activate_from_untreated(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'activate'
            })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html')
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'], [
                u"Select a valid choice. activate is not one of the available choices."
            ])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'untreated')

    def test_change_view_post_valid_activate_from_accepted(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        self.backend.accept(new_user.registration_profile,
                            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        redirect_url = self.admin_url + "registration/registrationprofile/"
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'activate'
            })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.filter(user__pk=new_user.pk)
        self.failIf(profile.exists())

    def test_change_view_post_invalid_activate_from_rejected(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        self.backend.reject(new_user.registration_profile,
                            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'activate'
            })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html')
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'], [
                u"Select a valid choice. activate is not one of the available choices."
            ])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'rejected')

    def test_change_view_post_valid_force_activate_from_untreated(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        redirect_url = self.admin_url + "registration/registrationprofile/"
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'force_activate'
            })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.filter(user__pk=new_user.pk)
        self.failIf(profile.exists())

    def test_change_view_post_invalid_force_activate_from_accepted(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        self.backend.accept(new_user.registration_profile,
                            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'force_activate'
            })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html')
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'], [
                u"Select a valid choice. force_activate is not one of the available choices."
            ])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_valid_force_activate_from_rejected(self):
        new_user = self.backend.register(username='******',
                                         email='*****@*****.**',
                                         request=self.mock_request)
        self.backend.reject(new_user.registration_profile,
                            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        redirect_url = self.admin_url + "registration/registrationprofile/"
        response = self.client.post(
            url, {
                '_supplement-TOTAL_FORMS': 0,
                '_supplement-INITIAL_FORMS': 0,
                '_supplement-MAXNUM_FORMS': '',
                'action_name': 'force_activate'
            })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.filter(user__pk=new_user.pk)
        self.failIf(profile.exists())

    def test_resend_acceptance_email_action(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)
        admin_class.resend_acceptance_email(None,
                                            RegistrationProfile.objects.all())

        # one for registration, one for resend
        self.assertEqual(len(mail.outbox), 2)

    def test_accept_users_action(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)
        admin_class.accept_users(None, RegistrationProfile.objects.all())

        for profile in RegistrationProfile.objects.all():
            self.assertEqual(profile.status, 'accepted')
            self.assertNotEqual(profile.activation_key, None)

    def test_reject_users_action(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)
        admin_class.reject_users(None, RegistrationProfile.objects.all())

        for profile in RegistrationProfile.objects.all():
            self.assertEqual(profile.status, 'rejected')
            self.assertEqual(profile.activation_key, None)

    def test_force_activate_users_action(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        self.backend.register(username='******',
                              email='*****@*****.**',
                              request=self.mock_request)
        admin_class.force_activate_users(None,
                                         RegistrationProfile.objects.all())

        self.assertEqual(RegistrationProfile.objects.count(), 0)
class RegistrationAdminTestCase(TestCase):

    def setUp(self):
        User = get_user_model()
        self.backend = DefaultRegistrationBackend()
        self.mock_request = mock_request()
        self.admin = User.objects.create_superuser(
            username='******', email='*****@*****.**',
            password='******')

        self.client.login(username='******', password='******')
        self.admin_url = reverse('admin:index')

    def test_change_list_view_get(self):
        url = self.admin_url + "registration/registrationprofile/"
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response,
                                'admin/change_list.html')

    def test_change_view_get(self):
        self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html'
        )

    def test_change_view_get_404(self):
        self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/100/"
        response = self.client.get(url)

        self.assertEqual(response.status_code, 404)

    def test_change_view_post_valid_accept_from_untreated(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        redirect_url = self.admin_url + "registration/registrationprofile/"
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'accept'
        })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_valid_accept_from_accepted(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)
        self.backend.accept(
            new_user.registration_profile,
            request=self.mock_request)
        previous_activation_key = new_user.registration_profile.activation_key
        url = self.admin_url + "registration/registrationprofile/1/"
        redirect_url = self.admin_url + "registration/registrationprofile/"
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'accept'
        })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')
        self.assertNotEqual(profile.activation_key, previous_activation_key)

    def test_change_view_post_valid_accept_from_rejected(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)
        self.backend.reject(
            new_user.registration_profile,
            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        redirect_url = self.admin_url + "registration/registrationprofile/"
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'accept'
        })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_valid_reject_from_untreated(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        redirect_url = self.admin_url + "registration/registrationprofile/"
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'reject'
        })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'rejected')

    def test_change_view_post_invalid_reject_from_accepted(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)
        self.backend.accept(
            new_user.registration_profile,
            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'reject'
        })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html'
        )
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'],
            [u"Select a valid choice. "
             u"reject is not one of the available choices."])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_invalid_reject_from_rejected(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)
        self.backend.reject(
            new_user.registration_profile,
            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'reject'
        })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html'
        )
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'],
            [u"Select a valid choice. "
             u"reject is not one of the available choices."])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'rejected')

    def test_change_view_post_invalid_activate_from_untreated(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'activate'
        })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html'
        )
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'],
            [u"Select a valid choice. "
             u"activate is not one of the available choices."])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'untreated')

    def test_change_view_post_valid_activate_from_accepted(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)
        self.backend.accept(
            new_user.registration_profile,
            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        redirect_url = self.admin_url + "registration/registrationprofile/"
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'activate'
        })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.filter(user__pk=new_user.pk)
        self.failIf(profile.exists())

    def test_change_view_post_invalid_activate_from_rejected(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)
        self.backend.reject(
            new_user.registration_profile,
            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'activate'
        })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html'
        )
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'],
            [u"Select a valid choice. "
             u"activate is not one of the available choices."])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'rejected')

    def test_change_view_post_valid_force_activate_from_untreated(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        redirect_url = self.admin_url + "registration/registrationprofile/"
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'force_activate'
        })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.filter(user__pk=new_user.pk)
        self.failIf(profile.exists())

    def test_change_view_post_invalid_force_activate_from_accepted(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)
        self.backend.accept(
            new_user.registration_profile,
            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'force_activate'
        })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html'
        )
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'],
            [u"Select a valid choice. "
             u"force_activate is not one of the available choices."])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_valid_force_activate_from_rejected(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)
        self.backend.reject(
            new_user.registration_profile,
            request=self.mock_request)

        url = self.admin_url + "registration/registrationprofile/1/"
        redirect_url = self.admin_url + "registration/registrationprofile/"
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'force_activate'
        })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.filter(user__pk=new_user.pk)
        self.failIf(profile.exists())

    def test_resend_acceptance_email_action(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        self.backend.register(
            username='******', email='*****@*****.**', request=self.mock_request)
        admin_class.resend_acceptance_email(
            None, RegistrationProfile.objects.all())

        # one for registration, one for resend
        self.assertEqual(len(mail.outbox), 2)

    def test_accept_users_action(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        self.backend.register(
            username='******', email='*****@*****.**', request=self.mock_request)
        admin_class.accept_users(None, RegistrationProfile.objects.all())

        for profile in RegistrationProfile.objects.all():
            self.assertEqual(profile.status, 'accepted')
            self.assertNotEqual(profile.activation_key, None)

    def test_reject_users_action(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        self.backend.register(
            username='******', email='*****@*****.**', request=self.mock_request)
        admin_class.reject_users(None, RegistrationProfile.objects.all())

        for profile in RegistrationProfile.objects.all():
            self.assertEqual(profile.status, 'rejected')
            self.assertEqual(profile.activation_key, None)

    def test_force_activate_users_action(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        self.backend.register(
            username='******', email='*****@*****.**', request=self.mock_request)
        admin_class.force_activate_users(
            None, RegistrationProfile.objects.all())

        self.assertEqual(RegistrationProfile.objects.count(), 0)
class RegistrationAdminTestCase(TestCase):

    def setUp(self):
        User = get_user_model()
        self.backend = DefaultRegistrationBackend()
        self.mock_request = mock_request()
        self.admin = User.objects.create_superuser(
            username='******', email='*****@*****.**',
            password='******')

        self.client.login(username='******', password='******')
        self.admin_url = reverse('admin:index')

    def test_change_list_view_get(self):
        url = urlresolvers.reverse('admin:registration_registrationprofile_changelist')
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response,
                                'admin/change_list.html')

    def test_change_view_get(self):
        self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)

        url = urlresolvers.reverse('admin:registration_registrationprofile_change', args=(1,))
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html'
        )

    def test_change_view_get_404(self):
        self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)

        url = urlresolvers.reverse('admin:registration_registrationprofile_change', args=(100,))
        response = self.client.get(url)

        self.assertEqual(response.status_code, 404)

    def test_change_view_post_valid_accept_from_untreated(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)

        url = urlresolvers.reverse('admin:registration_registrationprofile_change', args=(1,))
        redirect_url = urlresolvers.reverse('admin:registration_registrationprofile_changelist')
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'accept'
        })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_valid_accept_from_accepted(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)
        self.backend.accept(
            new_user.registration_profile,
            request=self.mock_request)
        previous_activation_key = new_user.registration_profile.activation_key
        url = urlresolvers.reverse('admin:registration_registrationprofile_change', args=(1,))
        redirect_url = urlresolvers.reverse('admin:registration_registrationprofile_changelist')
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'accept'
        })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')
        self.assertNotEqual(profile.activation_key, previous_activation_key)

    def test_change_view_post_valid_accept_from_rejected(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)
        self.backend.reject(
            new_user.registration_profile,
            request=self.mock_request)

        url = urlresolvers.reverse('admin:registration_registrationprofile_change', args=(1,))
        redirect_url = urlresolvers.reverse('admin:registration_registrationprofile_changelist')
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'accept'
        })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_valid_reject_from_untreated(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)

        url = urlresolvers.reverse('admin:registration_registrationprofile_change', args=(1,))
        redirect_url = urlresolvers.reverse('admin:registration_registrationprofile_changelist')
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'reject'
        })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'rejected')

    def test_change_view_post_invalid_reject_from_accepted(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)
        self.backend.accept(
            new_user.registration_profile,
            request=self.mock_request)

        url = urlresolvers.reverse('admin:registration_registrationprofile_change', args=(1,))
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'reject'
        })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html'
        )
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'],
            ["Select a valid choice. "
             "reject is not one of the available choices."])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_invalid_reject_from_rejected(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)
        self.backend.reject(
            new_user.registration_profile,
            request=self.mock_request)

        url = urlresolvers.reverse('admin:registration_registrationprofile_change', args=(1,))
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'reject'
        })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html'
        )
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'],
            ["Select a valid choice. "
             "reject is not one of the available choices."])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'rejected')

    def test_change_view_post_invalid_activate_from_untreated(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)

        url = urlresolvers.reverse('admin:registration_registrationprofile_change', args=(1,))
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'activate'
        })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html'
        )
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'],
            ["Select a valid choice. "
             "activate is not one of the available choices."])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'untreated')

    def test_change_view_post_valid_activate_from_accepted(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)
        self.backend.accept(
            new_user.registration_profile,
            request=self.mock_request)

        url = urlresolvers.reverse('admin:registration_registrationprofile_change', args=(1,))
        redirect_url = urlresolvers.reverse('admin:registration_registrationprofile_changelist')
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'activate'
        })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.filter(user__pk=new_user.pk)
        self.failIf(profile.exists())

    def test_change_view_post_invalid_activate_from_rejected(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)
        self.backend.reject(
            new_user.registration_profile,
            request=self.mock_request)

        url = urlresolvers.reverse('admin:registration_registrationprofile_change', args=(1,))
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'activate'
        })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html'
        )
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'],
            ["Select a valid choice. "
             "activate is not one of the available choices."])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'rejected')

    def test_change_view_post_valid_force_activate_from_untreated(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)

        url = urlresolvers.reverse('admin:registration_registrationprofile_change', args=(1,))
        redirect_url = urlresolvers.reverse('admin:registration_registrationprofile_changelist')
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'force_activate'
        })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.filter(user__pk=new_user.pk)
        self.failIf(profile.exists())

    def test_change_view_post_invalid_force_activate_from_accepted(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)
        self.backend.accept(
            new_user.registration_profile,
            request=self.mock_request)

        url = urlresolvers.reverse('admin:registration_registrationprofile_change', args=(1,))
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'force_activate'
        })

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(
            response,
            'admin/registration/registrationprofile/change_form.html'
        )
        self.failIf(response.context['adminform'].form.is_valid())
        self.assertEqual(
            response.context['adminform'].form.errors['action_name'],
            ["Select a valid choice. "
             "force_activate is not one of the available choices."])

        profile = RegistrationProfile.objects.get(user__pk=new_user.pk)
        self.assertEqual(profile.status, 'accepted')

    def test_change_view_post_valid_force_activate_from_rejected(self):
        new_user = self.backend.register(
            username='******', email='*****@*****.**',
            request=self.mock_request)
        self.backend.reject(
            new_user.registration_profile,
            request=self.mock_request)

        url = urlresolvers.reverse('admin:registration_registrationprofile_change', args=(1,))
        redirect_url = urlresolvers.reverse('admin:registration_registrationprofile_changelist')
        response = self.client.post(url, {
            '_supplement-TOTAL_FORMS': 0,
            '_supplement-INITIAL_FORMS': 0,
            '_supplement-MAXNUM_FORMS': '',
            'action_name': 'force_activate'
        })

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, redirect_url)

        profile = RegistrationProfile.objects.filter(user__pk=new_user.pk)
        self.failIf(profile.exists())

    def test_resend_acceptance_email_action(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        self.backend.register(
            username='******', email='*****@*****.**', request=self.mock_request)
        admin_class.resend_acceptance_email(
            None, RegistrationProfile.objects.all())

        # one for registration, one for resend
        self.assertEqual(len(mail.outbox), 2)

    def test_accept_users_action(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        self.backend.register(
            username='******', email='*****@*****.**', request=self.mock_request)
        admin_class.accept_users(None, RegistrationProfile.objects.all())

        for profile in RegistrationProfile.objects.all():
            self.assertEqual(profile.status, 'accepted')
            self.assertNotEqual(profile.activation_key, None)

    def test_reject_users_action(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        self.backend.register(
            username='******', email='*****@*****.**', request=self.mock_request)
        admin_class.reject_users(None, RegistrationProfile.objects.all())

        for profile in RegistrationProfile.objects.all():
            self.assertEqual(profile.status, 'rejected')
            self.assertEqual(profile.activation_key, None)

    def test_force_activate_users_action(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        self.backend.register(
            username='******', email='*****@*****.**', request=self.mock_request)
        admin_class.force_activate_users(
            None, RegistrationProfile.objects.all())

        self.assertEqual(RegistrationProfile.objects.count(), 0)

    @override_settings(REGISTRATION_SUPPLEMENT_CLASS=None)
    def test_get_inline_instances_without_supplements(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)
        # Prevent caching
        if hasattr(admin_class.backend, '_supplement_class_cache'):
            delattr(admin_class.backend, '_supplement_class_cache')

        inline_instances = admin_class.get_inline_instances(self.mock_request, None)
        self.assertEqual(len(inline_instances), 0)

    @override_settings(
        REGISTRATION_SUPPLEMENT_CLASS="registration.supplements.default.models.DefaultRegistrationSupplement"
    )
    def test_get_inline_instances_with_default_supplements(self):
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)
        # Prevent caching
        if hasattr(admin_class.backend, '_supplement_class_cache'):
            delattr(admin_class.backend, '_supplement_class_cache')

        inline_instances = admin_class.get_inline_instances(self.mock_request, None)
        self.assertEqual(len(inline_instances), 1)