Commits

Peter Sanchez committed f47f6bb

Moved to factory_boy instead of fixtures. More readable and maintainable.

  • Participants
  • Parent commits dd51b83

Comments (0)

Files changed (4)

 Testing
 -------
 
+You need factory_boy installed for tests to run. To install, use:
+
+    $ pip install factory_boy
+
+Note: For more info on factory_boy, see: https://github.com/dnerdy/factory_boy
+
 From within your Django project, you can simply do:
 
     $ python manage.py test impersonate

File impersonate/fixtures/test_data.json

-[
-    {
-        "pk": 1, 
-        "model": "auth.user", 
-        "fields": {
-            "username": "user1", 
-            "first_name": "John", 
-            "last_name": "Smith", 
-            "is_active": true, 
-            "is_superuser": true, 
-            "is_staff": true, 
-            "last_login": "2012-11-18T21:39:07.470Z", 
-            "groups": [], 
-            "user_permissions": [], 
-            "password": "pbkdf2_sha256$10000$rFUAeNe8N8AC$1BYYCs9seuca2NqBLLtO3wmNVdnBeSbASF2LhhFbp1k=", 
-            "email": "user1@test-email.com", 
-            "date_joined": "2012-11-18T21:39:07.470Z"
-        }
-    }, 
-    {
-        "pk": 2, 
-        "model": "auth.user", 
-        "fields": {
-            "username": "user2", 
-            "first_name": "John", 
-            "last_name": "Doe", 
-            "is_active": true, 
-            "is_superuser": true, 
-            "is_staff": true, 
-            "last_login": "2012-11-18T21:39:17.669Z", 
-            "groups": [], 
-            "user_permissions": [], 
-            "password": "pbkdf2_sha256$10000$rFUAeNe8N8AC$1BYYCs9seuca2NqBLLtO3wmNVdnBeSbASF2LhhFbp1k=",
-            "email": "user2@test-email.com", 
-            "date_joined": "2012-11-18T21:39:17.669Z"
-        }
-    }, 
-    {
-        "pk": 3, 
-        "model": "auth.user", 
-        "fields": {
-            "username": "user3", 
-            "first_name": "", 
-            "last_name": "", 
-            "is_active": true, 
-            "is_superuser": false, 
-            "is_staff": true, 
-            "last_login": "2012-11-19T01:47:54.213Z", 
-            "groups": [], 
-            "user_permissions": [], 
-            "password": "pbkdf2_sha256$10000$rFUAeNe8N8AC$1BYYCs9seuca2NqBLLtO3wmNVdnBeSbASF2LhhFbp1k=", 
-            "email": "user3@test-email.com", 
-            "date_joined": "2012-11-19T01:47:54.213Z"
-        }
-    }, 
-    {
-        "pk": 4, 
-        "model": "auth.user", 
-        "fields": {
-            "username": "user4", 
-            "first_name": "", 
-            "last_name": "", 
-            "is_active": true, 
-            "is_superuser": false, 
-            "is_staff": false, 
-            "last_login": "2013-03-11T20:53:07.138Z", 
-            "groups": [], 
-            "user_permissions": [], 
-            "password": "pbkdf2_sha256$10000$rFUAeNe8N8AC$1BYYCs9seuca2NqBLLtO3wmNVdnBeSbASF2LhhFbp1k=",
-            "email": "user4@test-email.com", 
-            "date_joined": "2013-03-11T20:51:37.424Z"
-        }
-    }
-]

File impersonate/tests.py

         is_staff = False
 '''
 import urllib
+import factory
 from urlparse import urlsplit
 from django.test import TestCase
 from django.utils import unittest
 from django.test.client import Client
+from django.test.utils import override_settings
 from django.core.urlresolvers import reverse
 
 try:
     User = get_user_model()
 
 
+class UserFactory(factory.Factory):
+    FACTORY_FOR = User
+
+    username = ''
+    first_name = ''
+    last_name = ''
+    email = factory.LazyAttribute(
+        lambda a: '{0}@test-email.com'.format(a.username).lower()
+    )
+    is_superuser = False
+    is_staff = False
+
+    @classmethod
+    def _prepare(cls, create, **kwargs):
+        password = kwargs.pop('password', None)
+        user = super(UserFactory, cls)._prepare(create, **kwargs)
+        if password:
+            user.set_password(password)
+            if create:
+                user.save()
+        return user
+
+
 class TestImpersonation(TestCase):
-    fixtures = ['test_data.json']
-
     def setUp(self):
         self.client = Client()
+        user_data = (
+            ('John', 'Smith', True, True),
+            ('John', 'Doe', True, True),
+            ('', '', False, True),
+            ('', '', False, False),
+        )
+        for cnt, data in enumerate(user_data):
+            UserFactory.create(**{
+                'username': 'user{0}'.format(cnt + 1),
+                'first_name': data[0],
+                'last_name': data[1],
+                'is_superuser': data[2],
+                'is_staff': data[3],
+                'password': 'foobar',
+            })
 
     def _impersonate_helper(self, user, passwd,
                             user_id_to_impersonate, qwargs={}):
         self.assertEqual(self.client.session.get('_impersonate'), None)
         self.client.logout()
 
+    @override_settings(LOGIN_REDIRECT_URL='/test-redirect/')
+    def test_unsuccessful_impersonation_restricted_uri(self):
+        response = self._impersonate_helper('user1', 'foobar', 4)
+        self.assertEqual(self.client.session['_impersonate'].id, 4)
+        response = self.client.get(reverse('impersonate-list'))
+        self._redirect_check(response, '/test-redirect/')
+        self.client.logout()
+
     def test_successful_impersonation_redirect_url(self):
         with self.settings(IMPERSONATE_REDIRECT_URL='/test-redirect/'):
             response = self._impersonate_helper('user1', 'foobar', 4)
         with self.settings(IMPERSONATE_PAGINATE_COUNT=2):
             response = self.client.get(reverse('impersonate-list'))
             self.assertEqual(response.context['paginator'].num_pages, 2)
+
+        # Out of range page number
+        response = self.client.get(reverse('impersonate-list'), {'page': 10})
+        self.assertEqual(response.context['page_number'], 10)
+        self.assertEqual(response.context['page'], None)
+
+        # Invalid integer
+        response = self.client.get(reverse('impersonate-list'), {'page': 'no'})
+        self.assertEqual(response.context['page_number'], 1)
+        self.assertEqual(len(response.context['page'].object_list), 4)
+
         self.client.logout()
 
     def test_user_search_and_pagination(self):
     },
     USE_TZ=True,
     ROOT_URLCONF='{}.urls'.format(APP_NAME),
+    MIDDLEWARE_CLASSES=(
+        'django.contrib.sessions.middleware.SessionMiddleware',
+        'django.contrib.auth.middleware.AuthenticationMiddleware',
+        'impersonate.middleware.ImpersonateMiddleware',
+    ),
     INSTALLED_APPS=(
         'django.contrib.auth',
         'django.contrib.contenttypes',