James Bennett avatar James Bennett committed 8225c00

Major refactor of tests to make them more fine-grained.

Comments (0)

Files changed (1)

registration/tests.py

 class RegistrationFormTests(TestCase):
     """
     Test the default registration forms.
-    
+
     """
     def test_registration_form(self):
         """
         Test that ``RegistrationForm`` enforces username constraints
         and matching passwords.
-        
+
         """
         # Create a user so we can verify that duplicate usernames aren't
         # permitted.
         """
         Test that ``RegistrationFormTermsOfService`` requires
         agreement to the terms of service.
-        
+
         """
         form = forms.RegistrationFormTermsOfService(data={ 'username': 'foo',
                                                            'email': 'foo@example.com',
                                                            'password2': 'foo' })
         self.failIf(form.is_valid())
         self.assertEqual(form.errors['tos'], [u"You must agree to the terms to register"])
-        
+
         form = forms.RegistrationFormTermsOfService(data={ 'username': 'foo',
                                                            'email': 'foo@example.com',
                                                            'password1': 'foo',
         """
         Test that ``RegistrationFormUniqueEmail`` validates uniqueness
         of email addresses.
-        
+
         """
         # Create a user so we can verify that duplicate addresses
         # aren't permitted.
         User.objects.create_user('alice', 'alice@example.com', 'secret')
-        
+
         form = forms.RegistrationFormUniqueEmail(data={ 'username': 'foo',
                                                         'email': 'alice@example.com',
                                                         'password1': 'foo',
         """
         Test that ``RegistrationFormNoFreeEmail`` disallows
         registration with free email addresses.
-        
+
         """
         base_data = { 'username': 'foo',
                       'password1': 'foo',
     created for the sending of activation emails; details on these
     templates and their contexts may be found in the documentation for
     the default backend.
-    
+
     """
     def setUp(self):
         """
         Create an instance of the default backend for use in testing,
         and set ``ACCOUNT_ACTIVATION_DAYS``.
-        
+
         """
         from registration.backends.default import DefaultBackend
         self.backend = DefaultBackend()
     def tearDown(self):
         """
         Restore the original value of ``ACCOUNT_ACTIVATION_DAYS``.
-        
+
         """
         settings.ACCOUNT_ACTIVATION_DAYS = self.old_activation
 
         inactive account and a new profile with activation key,
         populates the correct account data and sends an activation
         email.
-        
+
         """
-        new_user = self.backend.register({}, username='bob', email='bob@example.com', password1='secret')
+        new_user = self.backend.register({},
+                                         username='bob',
+                                         email='bob@example.com',
+                                         password1='secret')
+
+        # Details of the returned user must match what went in.
         self.assertEqual(new_user.username, 'bob')
         self.failUnless(new_user.check_password('secret'))
         self.assertEqual(new_user.email, 'bob@example.com')
+
+        # New user must not be active.
         self.failIf(new_user.is_active)
+
+        # A registration profile was created, and an activation email
+        # was sent.
         self.assertEqual(RegistrationProfile.objects.count(), 1)
         self.assertEqual(len(mail.outbox), 1)
 
-    def test_activation(self):
+    def test_valid_activation(self):
         """
         Test the activation process: activating within the permitted
         window sets the account's ``is_active`` field to ``True`` and
-        resets the activation key, while failing to activate within
-        the permitted window forbids later activation.
-        
+        resets the activation key.
+
         """
-        # First, test with a user activating inside the activation
-        # window.
-        valid_user = self.backend.register({}, username='alice', email='alice@example.com', password1='swordfish')
+        valid_user = self.backend.register({},
+                                           username='alice',
+                                           email='alice@example.com',
+                                           password1='swordfish')
+
         valid_profile = RegistrationProfile.objects.get(user=valid_user)
         activated = self.backend.activate({}, valid_profile.activation_key)
         self.assertEqual(activated.username, valid_user.username)
         valid_profile = RegistrationProfile.objects.get(user=valid_user)
         self.assertEqual(valid_profile.activation_key, RegistrationProfile.ACTIVATED)
 
-        # Now test again, but with a user activating outside the
-        # activation window.
-        expired_user = self.backend.register({}, username='bob', email='bob@example.com', password1='secret')
+    def test_invalid_activation(self):
+        """
+        Test the activation process: trying to activate outside the
+        permitted window fails, and leaves the account inactive.
+
+        """
+        expired_user = self.backend.register({},
+                                             username='bob',
+                                             email='bob@example.com',
+                                             password1='secret')
+
         expired_user.date_joined = expired_user.date_joined - datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
         expired_user.save()
         expired_profile = RegistrationProfile.objects.get(user=expired_user)
         """
         Test that the setting ``REGISTRATION_OPEN`` appropriately
         controls whether registration is permitted.
-        
+
         """
         old_allowed = getattr(settings, 'REGISTRATION_OPEN', True)
         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
         """
         Test that the default form class returned is
         ``registration.forms.RegistrationForm``.
-        
+
         """
         self.failUnless(self.backend.get_form_class({}) is forms.RegistrationForm)
 
         """
         Test that the default post-registration redirect is the named
         pattern ``registration_complete``.
-        
+
         """
         self.assertEqual(self.backend.post_registration_redirect({}, User()),
                          'registration_complete')
     """
     Test that utilities for retrieving the active backend work
     properly.
-    
+
     """
     def test_get_backend(self):
         """
         Set ``REGISTRATION_BACKEND`` temporarily, then verify that
         ``get_backend()`` returns the correct value.
-        
+
         """
         from registration import get_backend
         from registration.backends.default import DefaultBackend
 
-        # Stash away the original value of the setting so we can
-        # restore it again later.
         old_backend = getattr(settings, 'REGISTRATION_BACKEND', None)
-        
+
         settings.REGISTRATION_BACKEND = 'registration.backends.default.DefaultBackend'
         self.failUnless(isinstance(get_backend(), DefaultBackend))
 
         settings.REGISTRATION_BACKEND = old_backend
 
-    def test_backend_error(self):
+    def test_backend_error_none(self):
         """
-        Test that an invalid or nonexistent value for the
-        ``REGISTRATION_BACKEND`` setting raises the correct exception.
-        
+        Test that an invalid value for the ``REGISTRATION_BACKEND``
+        setting raises the correct exception.
+
         """
         from registration import get_backend
 
         settings.REGISTRATION_BACKEND = None
         self.assertRaises(ImproperlyConfigured, get_backend)
 
-        # Test nonexistent module
+        settings.REGISTRATION_BACKEND = old_backend
+
+    def test_backend_error_invalid(self):
+        """
+        Test that a nonexistent/unimportable backend raises the
+        correct exception.
+
+        """
+        from registration import get_backend
+
+        old_backend = getattr(settings, 'REGISTRATION_BACKEND', None)
+
         settings.REGISTRATION_BACKEND = 'registration.backends.doesnotexist.NonExistentBackend'
         self.assertRaises(ImproperlyConfigured, get_backend)
 
 class RegistrationViewTests(TestCase):
     """
     Test the registration views.
-    
+
     """
     urls = 'registration.backends.default.urls'
-    
+
     def setUp(self):
         """
         Set ``REGISTRATION_BACKEND`` to the default backend, and store
         the original value to be restored later.
-        
+
         """
         self.old_backend = getattr(settings, 'REGISTRATION_BACKEND', None)
         settings.REGISTRATION_BACKEND = 'registration.backends.default.DefaultBackend'
     def tearDown(self):
         """
         Retore the original value of ``REGISTRATION_BACKEND``.
-        
+
         """
         settings.REGISTRATION_BACKEND = self.old_backend
         settings.ACCOUNT_ACTIVATION_DAYS = self.old_activation
 
-    def test_registration_view(self):
+    def test_registration_view_initial(self):
         """
-        Call the ``register`` view and ensure that it properly
-        validates data and creates a new user.
-        
+        A ``GET`` to the ``register`` view uses the appropriate
+        template and populates the registration form into the context.
+
         """
+        from registration.forms import RegistrationForm
+
         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'], RegistrationForm))
 
+    def test_registration_view_success(self):
+        """
+        A ``POST`` to the ``register`` view with valid date properly
+        creates a new user and issues a redirect.
+
+        """
         response = self.client.post(reverse('registration_register'),
                                     data={ 'username': 'alice',
                                            'email': 'alice@example.com',
                              'http://testserver%s' % reverse('registration_complete'))
         self.assertEqual(len(mail.outbox), 1)
 
-        # Invalid data can't register.
+    def test_registration_view_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': 'bob',
                                            'email': 'bobe@example.com',
         self.assertEqual(response.status_code, 200)
         self.failIf(response.context['form'].is_valid())
         self.assertFormError(response, 'form', field=None, errors=u'You must type the same password each time')
-        self.assertEqual(len(mail.outbox), 1)
+        self.assertEqual(len(mail.outbox), 0)
 
-        # If registration is closed, trying to register should
-        # redirect to the "registration closed" message.
+    def test_registration_view_closed(self):
+        """
+        Any attempt to access the ``register`` view when registration
+        is closed fails and redirects.
+
+        """
         old_allowed = getattr(settings, 'REGISTRATION_OPEN', True)
         settings.REGISTRATION_OPEN = False
 
+        closed_redirect = 'http://testserver%s' % reverse('registration_disallowed')
+
         response = self.client.get(reverse('registration_register'))
-        self.assertEqual(response.status_code, 302)
-        self.assertEqual(response['Location'], 'http://testserver%s' % reverse('registration_disallowed'))
+        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': 'alice',
+                                           'email': 'alice@example.com',
+                                           'password1': 'swordfish',
+                                           'password2': 'swordfish' })
+        self.assertRedirects(response, closed_redirect)
+        self.assertEqual(RegistrationProfile.objects.count(), 0)
 
         settings.REGISTRATION_OPEN = old_allowed
 
+    def test_valid_activation(self):
+        """
+        Test that the ``activate`` view properly handles a valid
+        activation (in this case, based on the default backend's
+        activation window).
 
-    def test_activation_view(self):
-        """
-        Call the ``activate`` view and ensure that it properly
-        activates users within the valid activation window, but not
-        otherwise.
-        
         """
         # First, register an account.
         self.client.post(reverse('registration_register'),
                                 'password1': 'swordfish',
                                 'password2': 'swordfish' })
         profile = RegistrationProfile.objects.get(user__username='alice')
+
         response = self.client.get(reverse('registration_activate',
                                            kwargs={ 'activation_key': profile.activation_key }))
         self.assertEqual(response.status_code, 200)
         self.failUnless(isinstance(response.context['account'], User))
         self.assertEqual(response.context['account'].username,
                          u'alice')
-
         self.failUnless(User.objects.get(username='alice').is_active)
 
-        # Register another one and reset its date_joined to be outside
+    def test_invalid_activation(self):
+        """
+        Test that the ``activate`` view properly handles an invalid
+        activation (in this case, based on the default backend's
+        activation window).
+
+        """
+        # Register an account and reset its date_joined to be outside
         # the activation window.
         self.client.post(reverse('registration_register'),
                          data={ 'username': 'bob',
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.