Commits

James Bennett committed be835dd

Use mock requests everywhere, and test that registration still works when using only RequestSite.

  • Participants
  • Parent commits d58e853

Comments (0)

Files changed (1)

File registration/tests/backends.py

 
 from django.conf import settings
 from django.contrib.auth.models import User
+from django.contrib.sites.models import Site
 from django.core import mail
 from django.core.exceptions import ImproperlyConfigured
+from django.core.handlers.wsgi import WSGIRequest
+from django.test import Client
 from django.test import TestCase
 
 from registration import get_backend
 from registration.models import RegistrationProfile
 
 
+class _MockRequestClient(Client):
+    """
+    A ``django.test.Client`` subclass which can return mock
+    ``HttpRequest`` objects.
+    
+    """
+    def request(self, **request):
+        """
+        Rather than issuing a request and returning the response, this
+        simply constructs an ``HttpRequest`` object and returns it.
+        
+        """
+        environ = {
+            'HTTP_COOKIE':      self.cookies,
+            'PATH_INFO':         '/',
+            'QUERY_STRING':      '',
+            'REMOTE_ADDR':       '127.0.0.1',
+            'REQUEST_METHOD':    'GET',
+            'SCRIPT_NAME':       '',
+            'SERVER_NAME':       'testserver',
+            'SERVER_PORT':       '80',
+            'SERVER_PROTOCOL':   'HTTP/1.1',
+            'wsgi.version':      (1,0),
+            'wsgi.url_scheme':   'http',
+            'wsgi.errors':       self.errors,
+            'wsgi.multiprocess': True,
+            'wsgi.multithread':  False,
+            'wsgi.run_once':     False,
+            }
+        environ.update(self.defaults)
+        environ.update(request)
+        return WSGIRequest(environ)
+
+
+def _mock_request():
+    """
+    Construct and return a mock ``HttpRequest`` object; this is used
+    in testing backend methods which expect an ``HttpRequest`` but
+    which are not being called from views.
+    
+    """
+    return _MockRequestClient().request()
+
+
 class BackendRetrievalTests(TestCase):
     """
     Test that utilities for retrieving the active backend work
         email.
 
         """
-        new_user = self.backend.register({},
+        new_user = self.backend.register(_mock_request(),
                                          username='bob',
                                          email='bob@example.com',
                                          password1='secret')
         self.assertEqual(RegistrationProfile.objects.count(), 1)
         self.assertEqual(len(mail.outbox), 1)
 
+    def test_registration_no_sites(self):
+        """
+        Test that registration still functions properly when
+        ``django.contrib.sites`` is not installed; the fallback will
+        be a ``RequestSite`` instance.
+        
+        """
+        Site._meta.installed = False
+
+        new_user = self.backend.register(_mock_request(),
+                                         username='bob',
+                                         email='bob@example.com',
+                                         password1='secret')
+
+        self.assertEqual(new_user.username, 'bob')
+        self.failUnless(new_user.check_password('secret'))
+        self.assertEqual(new_user.email, 'bob@example.com')
+
+        self.failIf(new_user.is_active)
+
+        self.assertEqual(RegistrationProfile.objects.count(), 1)
+        self.assertEqual(len(mail.outbox), 1)
+        
+        Site._meta.installed = True
+
     def test_valid_activation(self):
         """
         Test the activation process: activating within the permitted
         resets the activation key.
 
         """
-        valid_user = self.backend.register({},
+        valid_user = self.backend.register(_mock_request(),
                                            username='alice',
                                            email='alice@example.com',
                                            password1='swordfish')
 
         valid_profile = RegistrationProfile.objects.get(user=valid_user)
-        activated = self.backend.activate({}, valid_profile.activation_key)
+        activated = self.backend.activate(_mock_request(),
+                                          valid_profile.activation_key)
         self.assertEqual(activated.username, valid_user.username)
         self.failUnless(activated.is_active)
 
         permitted window fails, and leaves the account inactive.
 
         """
-        expired_user = self.backend.register({},
+        expired_user = self.backend.register(_mock_request(),
                                              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)
-        self.failIf(self.backend.activate({}, expired_profile.activation_key))
+        self.failIf(self.backend.activate(_mock_request(),
+                                          expired_profile.activation_key))
         self.failUnless(expired_profile.activation_key_expired())
 
     def test_allow(self):
         """
         old_allowed = getattr(settings, 'REGISTRATION_OPEN', True)
         settings.REGISTRATION_OPEN = True
-        self.failUnless(self.backend.registration_allowed({}))
+        self.failUnless(self.backend.registration_allowed(_mock_request()))
 
         settings.REGISTRATION_OPEN = False
-        self.failIf(self.backend.registration_allowed({}))
+        self.failIf(self.backend.registration_allowed(_mock_request()))
         settings.REGISTRATION_OPEN = old_allowed
 
     def test_form_class(self):
         ``registration.forms.RegistrationForm``.
 
         """
-        self.failUnless(self.backend.get_form_class({}) is forms.RegistrationForm)
+        self.failUnless(self.backend.get_form_class(_mock_request()) is forms.RegistrationForm)
 
     def test_post_registration_redirect(self):
         """
         pattern ``registration_complete``.
 
         """
-        self.assertEqual(self.backend.post_registration_redirect({}, User()),
+        self.assertEqual(self.backend.post_registration_redirect(_mock_request(), User()),
                          'registration_complete')
 
     def test_registration_signal(self):
         received_signals = []
         signals.user_registered.connect(receiver, sender=self.backend.__class__)
 
-        self.backend.register({},
+        self.backend.register(_mock_request(),
                               username='bob',
                               email='bob@example.com',
                               password1='secret')
         received_signals = []
         signals.user_activated.connect(receiver, sender=self.backend.__class__)
 
-        new_user = self.backend.register({},
+        new_user = self.backend.register(_mock_request(),
                                          username='bob',
                                          email='bob@example.com',
                                          password1='secret')
         profile = RegistrationProfile.objects.get(user=new_user)
-        self.backend.activate({}, profile.activation_key)
+        self.backend.activate(_mock_request(), profile.activation_key)
 
         self.assertEqual(len(received_signals), 1)
         self.assertEqual(received_signals, [signals.user_activated])
         received_signals = []
         signals.user_activated.connect(receiver, sender=self.backend.__class__)
 
-        new_user = self.backend.register({},
+        new_user = self.backend.register(_mock_request(),
                                          username='bob',
                                          email='bob@example.com',
                                          password1='secret')
         new_user.date_joined -= datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
         new_user.save()
         profile = RegistrationProfile.objects.get(user=new_user)
-        self.backend.activate({}, profile.activation_key)
+        self.backend.activate(_mock_request(), profile.activation_key)
 
         self.assertEqual(len(received_signals), 0)