Rune Hansen avatar Rune Hansen committed baef373

Updated to support python 3.x. using the six library

Comments (0)

Files changed (4)

django_auth_ldap/backend.py

 from django.core.cache import cache
 from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
 import django.dispatch
-
+try:
+    from django.utils import six
+except ImportError:
+    try:
+        import six
+    except ImportError:
+        raise ImportError("""django-auth-ldap requires a version of six. 
+        This comes bundled with django 1.5. If using an earlier version of django, 
+        please manually install the six library""")
+    
 # Support Django 1.5's custom user models
 try:
     from django.contrib.auth import get_user_model
         """
         Exclude certain cached properties from pickling.
         """
-        state = filter(
-            lambda (k, v): k not in ['_settings', '_ldap'],
-            self.__dict__.iteritems()
-        )
-
+        state = [k_v1 for k_v1 in six.iteritems(self.__dict__) if k_v1[0] in ['backend', '_username', '_user']]
         return dict(state)
 
     def _get_settings(self):
         if len(password) == 0 and not self.settings.PERMIT_EMPTY_PASSWORD:
             logger.debug('Rejecting empty password for %s' % username)
             return None
-
         ldap_user = _LDAPUser(self, username=username.strip())
         user = ldap_user.authenticate(password)
-
         return user
 
     def get_user(self, user_id):
         Most of our properties are cached from the LDAP server. We only want to
         pickle a few crucial things.
         """
-        state = filter(
-            lambda (k, v): k in ['backend', '_username', '_user'],
-            self.__dict__.iteritems()
-        )
-
+        state = [k_v1 for k_v1 in six.iteritems(self.__dict__) if k_v1[0] in ['backend', '_username', '_user']]
         return dict(state)
 
     def _set_authenticated_user(self, user):
         user.ldap_user = self
         user.ldap_username = self._username
 
+        
     def _get_ldap(self):
         return self.backend.ldap
     ldap = property(_get_ldap)
             self._get_or_create_user()
 
             user = self._user
-        except self.AuthenticationFailed, e:
-            logger.debug(u"Authentication failed for %s" % self._username)
-        except self.ldap.LDAPError, e:
-            logger.warning(u"Caught LDAPError while authenticating %s: %s",
+
+        except self.AuthenticationFailed as e:
+            logger.debug(six.u("Authentication failed for %s") % self._username)
+        except self.ldap.LDAPError as e:
+            logger.warning(six.u("Caught LDAPError while authenticating %s: %s"),
                 self._username, pprint.pformat(e))
         except Exception:
-            logger.exception(u"Caught Exception while authenticating %s",
+            logger.exception(six.u("Caught Exception while authenticating %s"),
                 self._username)
             raise
 
             if self.settings.FIND_GROUP_PERMS:
                 try:
                     self._load_group_permissions()
-                except self.ldap.LDAPError, e:
+                except self.ldap.LDAPError as e:
                     logger.warning("Caught LDAPError loading group permissions: %s",
                         pprint.pformat(e))
 
                 self._get_or_create_user(force_populate=True)
 
             user = self._user
-        except self.ldap.LDAPError, e:
-            logger.warning(u"Caught LDAPError while authenticating %s: %s",
+        except self.ldap.LDAPError as e:
+            logger.warning(six.u("Caught LDAPError while authenticating %s: %s"),
                 self._username, pprint.pformat(e))
-        except Exception, e:
-            logger.error(u"Caught Exception while authenticating %s: %s",
+        except Exception as e:
+            logger.error(six.u("Caught Exception while authenticating %s: %s"),
                 self._username, pprint.pformat(e))
             logger.error(''.join(traceback.format_tb(sys.exc_info()[2])))
             raise
         Binds to the LDAP server with the user's DN and password. Raises
         AuthenticationFailed on failure.
         """
+        
         if self.dn is None:
             raise self.AuthenticationFailed("Failed to map the username to a DN.")
 
         try:
             sticky = self.settings.BIND_AS_AUTHENTICATING_USER
-
             self._bind_as(self.dn, password, sticky=sticky)
         except self.ldap.INVALID_CREDENTIALS:
             raise self.AuthenticationFailed("User DN/password rejected by LDAP server.")
         self._populate_user_from_group_memberships()
 
     def _populate_user_from_attributes(self):
-        for field, attr in self.settings.USER_ATTR_MAP.iteritems():
+        for field, attr in six.iteritems(self.settings.USER_ATTR_MAP):
             try:
                 setattr(self._user, field, self.attrs[attr][0])
-            except StandardError:
+            except Exception:
                 logger.warning("%s does not have a value for the attribute %s", self.dn, attr)
 
     def _populate_user_from_group_memberships(self):
-        for field, group_dn in self.settings.USER_FLAGS_BY_GROUP.iteritems():
+        for field, group_dn in six.iteritems(self.settings.USER_FLAGS_BY_GROUP):
             value = self._get_groups().is_member_of(group_dn)
             setattr(self._user, field, value)
 
         """
         save_profile = False
 
-        for field, attr in self.settings.PROFILE_ATTR_MAP.iteritems():
+        for field, attr in six.iteritems(self.settings.PROFILE_ATTR_MAP):
             try:
                 # user_attrs is a hash of lists of attribute values
                 setattr(profile, field, self.attrs[attr][0])
                 save_profile = True
-            except StandardError:
+            except Exception:
                 logger.warning("%s does not have a value for the attribute %s", self.dn, attr)
 
         return save_profile
         """
         save_profile = False
 
-        for field, group_dn in self.settings.PROFILE_FLAGS_BY_GROUP.iteritems():
+        for field, group_dn in six.iteritems(self.settings.PROFILE_FLAGS_BY_GROUP):
             value = self._get_groups().is_member_of(group_dn)
             setattr(profile, field, value)
             save_profile = True
         the life of this object. If False, then the caller only wishes to test
         the credentials, after which the connection will be considered unbound.
         """
-        self._get_connection().simple_bind_s(bind_dn.encode('utf-8'),
-            bind_password.encode('utf-8'))
+        if six.PY3:
+            self._get_connection().simple_bind_s(bind_dn,
+                                                     bind_password)
+        else:
+            self._get_connection().simple_bind_s(bind_dn.encode('utf-8'),
+                                                 bind_password.encode('utf-8'))
 
         self._connection_bound = sticky
 
         if self._connection is None:
             self._connection = self.ldap.initialize(self.settings.SERVER_URI)
 
-            for opt, value in self.settings.CONNECTION_OPTIONS.iteritems():
+            for opt, value in six.iteritems(self.settings.CONNECTION_OPTIONS):
                 self._connection.set_option(opt, value)
 
             if self.settings.START_TLS:
                 logger.debug("Initiating TLS")
                 self._connection.start_tls_s()
-
         return self._connection
 
 
         DN for maximum compatibility.
         """
         dn = self._ldap_user.dn.replace(' ', '%20')
-        key = u'auth_ldap.%s.%s.%s' % (self.__class__.__name__, attr_name, dn)
+        key = six.u('auth_ldap.%s.%s.%s') % (self.__class__.__name__, attr_name, dn)
 
         return key
 
         """
         from django.conf import settings
 
-        for name, default in self.defaults.iteritems():
+        for name, default in six.iteritems(self.defaults):
             value = getattr(settings, prefix + name, default)
             setattr(self, name, value)

django_auth_ldap/config.py

 import logging
 import pprint
 
+try:
+    from django.utils import six
+except ImportError:
+    try:
+        import six
+    except ImportError:
+        raise ImportError("""django-auth-ldap requires a version of six. 
+        This comes bundled with django 1.5. If using an earlier version of django, 
+        please manually install the six library""")
 
 class _LDAPConfig(object):
     """
 
         # Apply global LDAP options once
         if (not cls._ldap_configured) and (global_options is not None):
-            for opt, value in global_options.iteritems():
+            for opt, value in six.iteritems(global_options):
                 cls.ldap.set_option(opt, value)
 
             cls._ldap_configured = True
     documented for configuration purposes. Internal clients may use the other
     methods to refine and execute the search.
     """
-    def __init__(self, base_dn, scope, filterstr=u'(objectClass=*)'):
+    def __init__(self, base_dn, scope, filterstr=six.u('(objectClass=*)')):
         """
         These parameters are the same as the first three parameters to
         ldap.search_s.
         """
         term_strings = [self.filterstr]
 
-        for name, value in term_dict.iteritems():
+        for name, value in six.iteritems(term_dict):
             if escape:
                 value = self.ldap.filter.escape_filter_chars(value)
-            term_strings.append(u'(%s=%s)' % (name, value))
+            term_strings.append(six.u('(%s=%s)') % (name, value))
 
-        filterstr = u'(&%s)' % ''.join(term_strings)
+        filterstr = six.u('(&%s)') % ''.join(term_strings)
 
         return self.__class__(self.base_dn, self.scope, filterstr)
 
         string. The caller is responsible for passing in a properly escaped
         string.
         """
-        filterstr = u'(&%s%s)' % (self.filterstr, filterstr)
+        filterstr = six.u('(&%s%s)') % (self.filterstr, filterstr)
 
         return self.__class__(self.base_dn, self.scope, filterstr)
 
         """
         try:
             filterstr = self.filterstr % filterargs
-            results = connection.search_s(self.base_dn.encode('utf-8'),
-                self.scope, filterstr.encode('utf-8'))
-        except self.ldap.LDAPError, e:
+            if six.PY3:
+                results = connection.search_s(self.base_dn,
+                                              self.scope, filterstr)
+            else:
+                results = connection.search_s(self.base_dn.encode('utf-8'),
+                                              self.scope, filterstr.encode('utf-8'))
+                
+        except self.ldap.LDAPError as e:
             results = []
-            logger.error(u"search_s('%s', %d, '%s') raised %s" %
+            logger.error(six.u("search_s('%s', %d, '%s') raised %s") %
                 (self.base_dn, self.scope, filterstr, pprint.pformat(e)))
 
         return self._process_results(results)
         """
         try:
             filterstr = self.filterstr % filterargs
-            msgid = connection.search(self.base_dn.encode('utf-8'),
-                self.scope, filterstr.encode('utf-8'))
-        except self.ldap.LDAPError, e:
+            if six.PY3:
+                msgid = connection.search(self.base_dn,
+                                          self.scope, filterstr)
+            else:
+                msgid = connection.search(self.base_dn.encode('utf-8'),
+                                          self.scope, filterstr.encode('utf-8'))
+            
+        except self.ldap.LDAPError as e:
             msgid = None
-            logger.error(u"search('%s', %d, '%s') raised %s" %
+            logger.error(six.u("search('%s', %d, '%s') raised %s") %
                 (self.base_dn, self.scope, filterstr, pprint.pformat(e)))
 
         return msgid
             kind, results = connection.result(msgid)
             if kind != self.ldap.RES_SEARCH_RESULT:
                 results = []
-        except self.ldap.LDAPError, e:
+        except self.ldap.LDAPError as e:
             results = []
-            logger.error(u"result(%d) raised %s" % (msgid, pprint.pformat(e)))
+            logger.error(six.u("result(%d) raised %s") % (msgid, pprint.pformat(e)))
 
         return self._process_results(results)
 
         Returns a sanitized copy of raw LDAP results. This scrubs out
         references, decodes utf8, normalizes DNs, etc.
         """
-        results = filter(lambda r: r[0] is not None, results)
-        results = _DeepStringCoder('utf-8').decode(results)
+        results = [r for r in results if r[0] is not None]
+        if six.PY3:
+            results = results
+        else:
+            results = _DeepStringCoder('utf-8').decode(results)
 
         # The normal form of a DN is lower case.
-        results = map(lambda r: (r[0].lower(), r[1]), results)
-
+        results = [(r[0].lower(), r[1]) for r in results]
+        
         result_dns = [result[0] for result in results]
-        logger.debug(u"search_s('%s', %d, '%s') returned %d objects: %s" %
+        logger.debug(six.u("search_s('%s', %d, '%s') returned %d objects: %s") %
             (self.base_dn, self.scope, self.filterstr, len(result_dns), "; ".join(result_dns)))
 
         return results
             result = search._results(connection, msgid)
             results.update(dict(result))
 
-        return results.items()
+        return list(results.items())
 
 
 class _DeepStringCoder(object):
         # for search results.
         decoded = self.ldap.cidict.cidict()
 
-        for k, v in value.iteritems():
+        for k, v in six.iteritems(value):
             decoded[self.decode(k)] = self.decode(v)
 
         return decoded
             user_uid = ldap_user.attrs['uid'][0]
             user_gid = ldap_user.attrs['gidNumber'][0]
 
-            filterstr = u'(|(gidNumber=%s)(memberUid=%s))' % (
+            filterstr = six.u('(|(gidNumber=%s)(memberUid=%s))') % (
                 self.ldap.filter.escape_filter_chars(user_gid),
                 self.ldap.filter.escape_filter_chars(user_uid)
             )
             user_gid = ldap_user.attrs['gidNumber'][0]
 
             try:
-                is_member = ldap_user.connection.compare_s(group_dn.encode('utf-8'), 'memberUid', user_uid.encode('utf-8'))
+                if six.PY3:
+                    is_member = ldap_user.connection.compare_s(group_dn, 'memberUid', user_uid)
+                else:
+                    is_member = ldap_user.connection.compare_s(group_dn.encode('utf-8'), 'memberUid', user_uid.encode('utf-8'))
             except self.ldap.NO_SUCH_ATTRIBUTE:
                 is_member = False
 
             if not is_member:
                 try:
-                    is_member = ldap_user.connection.compare_s(group_dn.encode('utf-8'), 'gidNumber', user_gid.encode('utf-8'))
+                    if six.PY3:
+                        is_member = ldap_user.connection.compare_s(group_dn, 'gidNumber', user_gid)
+                    else:
+                        is_member = ldap_user.connection.compare_s(group_dn.encode('utf-8'), 'gidNumber', user_gid.encode('utf-8'))
                 except self.ldap.NO_SUCH_ATTRIBUTE:
                     is_member = False
         except (KeyError, IndexError):
 
     def is_member(self, ldap_user, group_dn):
         try:
-            result = ldap_user.connection.compare_s(
-                group_dn.encode('utf-8'),
-                self.member_attr.encode('utf-8'),
-                ldap_user.dn.encode('utf-8')
-            )
+            if six.PY3:
+                result = ldap_user.connection.compare_s(
+                    group_dn,
+                    self.member_attr,
+                    ldap_user.dn
+                )
+            else:
+                result = ldap_user.connection.compare_s(
+                    group_dn.encode('utf-8'),
+                    self.member_attr.encode('utf-8'),
+                    ldap_user.dn.encode('utf-8')
+                )
+                
         except self.ldap.NO_SUCH_ATTRIBUTE:
             result = 0
 
             # never to search with the same member DN twice.
             member_dn_set = set(new_group_info_map.keys()) - handled_dn_set
 
-        return group_info_map.values()
+        return list(group_info_map.values())
 
     def find_groups_with_any_member(self, member_dn_set, group_search, connection):
         terms = [
-            u"(%s=%s)" % (self.member_attr, self.ldap.filter.escape_filter_chars(dn))
+            six.u("(%s=%s)") % (self.member_attr, self.ldap.filter.escape_filter_chars(dn))
             for dn in member_dn_set
         ]
 
-        filterstr = u"(|%s)" % "".join(terms)
+        filterstr = six.u("(|%s)") % "".join(terms)
         search = group_search.search_with_additional_term_string(filterstr)
-
         return search.execute(connection)
 
 

django_auth_ldap/tests.py

 from django_auth_ldap.config import PosixGroupType, MemberDNGroupType, NestedMemberDNGroupType
 from django_auth_ldap.config import GroupOfNamesType
 
+try:
+    from django.utils import six
+except ImportError:
+    try:
+        import six
+    except ImportError:
+        raise ImportError("""django-auth-ldap requires a version of six. 
+        This comes bundled with django 1.5. If using an earlier version of django, 
+        please manually install the six library""")
+
+
 
 class TestSettings(backend.LDAPSettings):
     """
     from django.conf.
     """
     def __init__(self, **kwargs):
-        for name, default in self.defaults.iteritems():
+        for name, default in six.iteritems(self.defaults):
             value = kwargs.get(name, default)
             setattr(self, name, value)
 
 
         value = self._get_return_value('search_s',
             (base, scope, filterstr, attrlist, attrsonly))
+
         if value is None:
             value = self._search_s(base, scope, filterstr, attrlist, attrsonly)
 
 
         value = self._get_return_value('search_s',
             (base, scope, filterstr, attrlist, attrsonly))
+
         if value is None:
             value = self._search_s(base, scope, filterstr, attrlist, attrsonly)
 
         if result is None:
             result = self._compare_s(dn, attr, value)
 
-        # print "compare_s('%s', '%s', '%s'): %d" % (dn, attr, value, result)
+        # print("compare_s('%s', '%s', '%s'): %d" % (dn, attr, value, result))
 
         return result
 
         """
 
         valid_filterstr = re.compile(r'\(\w+=([\w@.]+|[*])\)')
-
         if not valid_filterstr.match(filterstr):
             raise self.PresetReturnRequiredError('search_s("%s", %d, "%s", "%s", %d)' %
                 (base, scope, filterstr, attrlist, attrsonly))
         def get_results(dn, filterstr, results):
             attrs = self.directory.get(dn)
             attr, value = filterstr[1:-1].split('=')
-            if attrs and attr in attrs.keys() and str(value) in attrs[attr] or value == u'*':
+            if attrs and attr in list(attrs.keys()) and str(value) in attrs[attr] or value == six.u('*'):
                 results.append((dn, attrs))
 
         results = []
-        all_dn = self.directory.keys()
+        all_dn = list(self.directory.keys())
         if scope == self.SCOPE_BASE:
             get_results(base, filterstr, results)
         elif scope == self.SCOPE_ONELEVEL:
         return len(self.async_results) - 1
 
     def _pop_async_result(self, msgid):
-        if msgid in xrange(len(self.async_results)):
+        if msgid in six.moves.xrange(len(self.async_results)):
             value = self.async_results[msgid]
             self.async_results[msgid] = None
         else:
         "givenName": ["Wolfgang"],
         "sn": [u"Dreßler".encode('utf-8')]
     })
+    
     nobody = ("uid=nobody,ou=people,o=test", {
         "uid": ["nobody"],
         "objectClass": ["person", "organizationalPerson", "inetOrgPerson", "posixAccount"],
 
         user = self.backend.authenticate(username='alice', password='password')
 
-        self.assert_(not user.has_usable_password())
+        self.assertTrue(not user.has_usable_password())
         self.assertEqual(user.username, 'alice')
         self.assertEqual(User.objects.count(), user_count + 1)
         self.assertEqual(self.mock_ldap.ldap_methods_called(),
 
         user = self.backend.authenticate(username='Alice', password='password')
 
-        self.assert_(not user.has_usable_password())
+        self.assertTrue(not user.has_usable_password())
         self.assertEqual(user.username, 'alice')
         self.assertEqual(User.objects.count(), user_count + 1)
         self.assertEqual(self.mock_ldap.ldap_methods_called(),
         )
 
         user = self.backend.authenticate(username='Alice', password='password')
-
-        self.assert_(isinstance(user, TestUser))
+        self.assertTrue(isinstance(user, TestUser))
 
     @override_settings(AUTH_USER_MODEL='django_auth_ldap.TestUser')
     def test_get_custom_user(self):
         user = self.backend.authenticate(username='Alice', password='password')
         user = self.backend.get_user(user.id)
 
-        self.assert_(isinstance(user, TestUser))
+        self.assertTrue(isinstance(user, TestUser))
 
     def test_new_user_whitespace(self):
         self._init_settings(
         user = self.backend.authenticate(username=' alice', password='password')
         user = self.backend.authenticate(username='alice ', password='password')
 
-        self.assert_(not user.has_usable_password())
+        self.assertTrue(not user.has_usable_password())
         self.assertEqual(user.username, 'alice')
         self.assertEqual(User.objects.count(), user_count + 1)
 
 
         user = self.backend.authenticate(username='evil_alice', password='password')
 
-        self.assert_(user is None)
+        self.assertTrue(user is None)
         self.assertEqual(User.objects.count(), user_count)
         self.assertEqual(self.mock_ldap.ldap_methods_called(),
             ['initialize', 'simple_bind_s'])
 
         user = self.backend.authenticate(username='alice', password='bogus')
 
-        self.assert_(user is None)
+        self.assertTrue(user is None)
         self.assertEqual(User.objects.count(), user_count)
         self.assertEqual(self.mock_ldap.ldap_methods_called(),
             ['initialize', 'simple_bind_s'])
         user = self.backend.authenticate(username='alice', password='password')
 
         # Make sure we only created one user
-        self.assert_(user is not None)
+        self.assertTrue(user is not None)
         self.assertEqual(User.objects.count(), user_count)
 
     def test_existing_user_insensitive(self):
 
         user = self.backend.authenticate(username='Alice', password='password')
 
-        self.assert_(user is not None)
+        self.assertTrue(user is not None)
         self.assertEqual(user.username, 'alice')
         self.assertEqual(User.objects.count(), 1)
 
 
         user = self.backend.authenticate(username='alice', password='password')
 
-        self.assert_(user is not None)
+        self.assertTrue(user is not None)
         self.assertEqual(User.objects.count(), user_count + 1)
         self.assertEqual(self.mock_ldap.ldap_methods_called(),
             ['initialize', 'simple_bind_s', 'search_s', 'simple_bind_s'])
 
         user = self.backend.authenticate(username='alice', password='password')
 
-        self.assert_(user is None)
+        self.assertTrue(user is None)
         self.assertEqual(self.mock_ldap.ldap_methods_called(),
             ['initialize', 'simple_bind_s', 'search_s'])
 
 
         user = self.backend.authenticate(username='alice', password='password')
 
-        self.assert_(user is None)
+        self.assertTrue(user is None)
         self.assertEqual(self.mock_ldap.ldap_methods_called(),
             ['initialize', 'simple_bind_s', 'search_s'])
 
 
         user = self.backend.authenticate(username='alice', password='bogus')
 
-        self.assert_(user is None)
+        self.assertTrue(user is None)
         self.assertEqual(self.mock_ldap.ldap_methods_called(),
             ['initialize', 'simple_bind_s', 'search_s', 'simple_bind_s'])
 
 
         user = self.backend.authenticate(username='alice', password='password')
 
-        self.assert_(user is not None)
-        self.assert_(user.ldap_user is not None)
+        self.assertTrue(user is not None)
+        self.assertTrue(user.ldap_user is not None)
         self.assertEqual(user.ldap_user.dn, self.alice[0])
         self.assertEqual(user.ldap_user.attrs, self.alice[1])
         self.assertEqual(self.mock_ldap.ldap_methods_called(),
 
         user = self.backend.authenticate(username='alice', password='password')
 
-        self.assert_(user is None)
+        self.assertTrue(user is None)
         self.assertEqual(self.mock_ldap.ldap_methods_called(),
             ['initialize', 'simple_bind_s'])
 
         )
 
         user = self.backend.authenticate(username=u'dreßler', password='password')
-
-        self.assert_(user is not None)
+        self.assertTrue(user is not None)
         self.assertEqual(user.username, u'dreßler')
         self.assertEqual(user.last_name, u'Dreßler')
 
         )
 
         user = self.backend.authenticate(username="alice", password="password")
-
-        self.assert_(isinstance(user.ldap_user.attrs, self.ldap.cidict.cidict))
+        if six.PY3:
+            self.assertTrue(isinstance(user.ldap_user.attrs, dict) and isinstance(self.ldap.cidict.cidict, type))
+        else:
+            self.assertTrue(isinstance(user.ldap_user.attrs, self.ldap.cidict.cidict))
 
     def test_populate_user(self):
         self._init_settings(
         )
 
         def handle_populate_user(sender, **kwargs):
-            self.assert_('user' in kwargs and 'ldap_user' in kwargs)
+            self.assertTrue('user' in kwargs and 'ldap_user' in kwargs)
             kwargs['user'].populate_user_handled = True
         backend.populate_user.connect(handle_populate_user)
 
         user = self.backend.authenticate(username='alice', password='password')
 
-        self.assert_(user.populate_user_handled)
+        self.assertTrue(user.populate_user_handled)
 
     def test_signal_populate_user_profile(self):
         settings.AUTH_PROFILE_MODULE = 'django_auth_ldap.TestProfile'
                 TestProfile.objects.create(user=kwargs['instance'])
 
         def handle_populate_user_profile(sender, **kwargs):
-            self.assert_('profile' in kwargs and 'ldap_user' in kwargs)
+            self.assertTrue('profile' in kwargs and 'ldap_user' in kwargs)
             kwargs['profile'].populated = True
 
         django.db.models.signals.post_save.connect(handle_user_saved, sender=User)
 
         user = self.backend.authenticate(username='alice', password='password')
 
-        self.assert_(user.get_profile().populated)
+        self.assertTrue(user.get_profile().populated)
 
     def test_no_update_existing(self):
         self._init_settings(
         alice = self.backend.authenticate(username='alice', password='password')
         bob = self.backend.authenticate(username='bob', password='password')
 
-        self.assert_(alice is not None)
-        self.assert_(bob is None)
+        self.assertTrue(alice is not None)
+        self.assertTrue(bob is None)
         self.assertEqual(self.mock_ldap.ldap_methods_called(),
             ['initialize', 'simple_bind_s', 'simple_bind_s', 'compare_s', 'initialize', 'simple_bind_s', 'simple_bind_s', 'compare_s'])
 
         alice = self.backend.authenticate(username='alice', password='password')
         bob = self.backend.authenticate(username='bob', password='password')
 
-        self.assert_(alice is None)
-        self.assert_(bob is not None)
+        self.assertTrue(alice is None)
+        self.assertTrue(bob is not None)
         self.assertEqual(self.mock_ldap.ldap_methods_called(),
             ['initialize', 'simple_bind_s', 'simple_bind_s', 'compare_s', 'initialize', 'simple_bind_s', 'simple_bind_s', 'compare_s'])
 
         alice = self.backend.authenticate(username='alice', password='password')
         bob = self.backend.authenticate(username='bob', password='password')
 
-        self.assert_(alice.is_active)
-        self.assert_(alice.is_staff)
-        self.assert_(alice.is_superuser)
-        self.assert_(not bob.is_active)
-        self.assert_(not bob.is_staff)
-        self.assert_(not bob.is_superuser)
+        self.assertTrue(alice.is_active)
+        self.assertTrue(alice.is_staff)
+        self.assertTrue(alice.is_superuser)
+        self.assertTrue(not bob.is_active)
+        self.assertTrue(not bob.is_staff)
+        self.assertTrue(not bob.is_superuser)
 
     def test_posix_membership(self):
         self._init_settings(
         alice = self.backend.authenticate(username='alice', password='password')
         bob = self.backend.authenticate(username='bob', password='password')
 
-        self.assert_(alice.is_active)
-        self.assert_(alice.is_staff)
-        self.assert_(alice.is_superuser)
-        self.assert_(not bob.is_active)
-        self.assert_(not bob.is_staff)
-        self.assert_(not bob.is_superuser)
+        self.assertTrue(alice.is_active)
+        self.assertTrue(alice.is_staff)
+        self.assertTrue(alice.is_superuser)
+        self.assertTrue(not bob.is_active)
+        self.assertTrue(not bob.is_staff)
+        self.assertTrue(not bob.is_superuser)
 
     def test_nested_dn_group_membership(self):
         self._init_settings(
         alice = self.backend.authenticate(username='alice', password='password')
         bob = self.backend.authenticate(username='bob', password='password')
 
-        self.assert_(alice.is_active)
-        self.assert_(alice.is_staff)
-        self.assert_(not bob.is_active)
-        self.assert_(not bob.is_staff)
+        self.assertTrue(alice.is_active)
+        self.assertTrue(alice.is_staff)
+        self.assertTrue(not bob.is_active)
+        self.assertTrue(not bob.is_staff)
 
     def test_posix_missing_attributes(self):
         self._init_settings(
 
         nobody = self.backend.authenticate(username='nobody', password='password')
 
-        self.assert_(not nobody.is_active)
+        self.assertTrue(not nobody.is_active)
 
     def test_profile_flags(self):
         settings.AUTH_PROFILE_MODULE = 'django_auth_ldap.TestProfile'
         alice = self.backend.authenticate(username='alice', password='password')
         bob = self.backend.authenticate(username='bob', password='password')
 
-        self.assert_(alice.get_profile().is_special)
-        self.assert_(not bob.get_profile().is_special)
+        self.assertTrue(alice.get_profile().is_special)
+        self.assertTrue(not bob.get_profile().is_special)
 
     def test_dn_group_permissions(self):
         self._init_settings(
 
         self.assertEqual(self.backend.get_group_permissions(alice), set(["auth.add_user", "auth.change_user"]))
         self.assertEqual(self.backend.get_all_permissions(alice), set(["auth.add_user", "auth.change_user"]))
-        self.assert_(self.backend.has_perm(alice, "auth.add_user"))
-        self.assert_(self.backend.has_module_perms(alice, "auth"))
+        self.assertTrue(self.backend.has_perm(alice, "auth.add_user"))
+        self.assertTrue(self.backend.has_module_perms(alice, "auth"))
 
     def test_empty_group_permissions(self):
         self._init_settings(
 
         self.assertEqual(self.backend.get_group_permissions(bob), set())
         self.assertEqual(self.backend.get_all_permissions(bob), set())
-        self.assert_(not self.backend.has_perm(bob, "auth.add_user"))
-        self.assert_(not self.backend.has_module_perms(bob, "auth"))
+        self.assertTrue(not self.backend.has_perm(bob, "auth.add_user"))
+        self.assertTrue(not self.backend.has_module_perms(bob, "auth"))
 
     def test_posix_group_permissions(self):
         self._init_settings(
 
         self.assertEqual(self.backend.get_group_permissions(alice), set(["auth.add_user", "auth.change_user"]))
         self.assertEqual(self.backend.get_all_permissions(alice), set(["auth.add_user", "auth.change_user"]))
-        self.assert_(self.backend.has_perm(alice, "auth.add_user"))
-        self.assert_(self.backend.has_module_perms(alice, "auth"))
+        self.assertTrue(self.backend.has_perm(alice, "auth.add_user"))
+        self.assertTrue(self.backend.has_module_perms(alice, "auth"))
 
     def test_foreign_user_permissions(self):
         self._init_settings(
         alice = self.backend.populate_user('alice')
         bob = self.backend.populate_user('bob')
 
-        self.assert_(alice is not None)
-        self.assertEqual(alice.first_name, u"")
-        self.assertEqual(alice.last_name, u"")
-        self.assert_(alice.is_active)
-        self.assert_(not alice.is_staff)
-        self.assert_(not alice.is_superuser)
-        self.assert_(bob is not None)
-        self.assertEqual(bob.first_name, u"")
-        self.assertEqual(bob.last_name, u"")
-        self.assert_(bob.is_active)
-        self.assert_(not bob.is_staff)
-        self.assert_(not bob.is_superuser)
+        self.assertTrue(alice is not None)
+        self.assertEqual(alice.first_name, six.u(""))
+        self.assertEqual(alice.last_name, six.u(""))
+        self.assertTrue(alice.is_active)
+        self.assertTrue(not alice.is_staff)
+        self.assertTrue(not alice.is_superuser)
+        self.assertTrue(bob is not None)
+        self.assertEqual(bob.first_name, six.u(""))
+        self.assertEqual(bob.last_name, six.u(""))
+        self.assertTrue(bob.is_active)
+        self.assertTrue(not bob.is_staff)
+        self.assertTrue(not bob.is_superuser)
 
     def test_populate_without_auth(self):
         self._init_settings(
         alice = self.backend.populate_user('alice')
         bob = self.backend.populate_user('bob')
 
-        self.assert_(alice is not None)
-        self.assertEqual(alice.first_name, u"Alice")
-        self.assertEqual(alice.last_name, u"Adams")
-        self.assert_(alice.is_active)
-        self.assert_(alice.is_staff)
-        self.assert_(alice.is_superuser)
-        self.assert_(bob is not None)
-        self.assertEqual(bob.first_name, u"Robert")
-        self.assertEqual(bob.last_name, u"Barker")
-        self.assert_(not bob.is_active)
-        self.assert_(not bob.is_staff)
-        self.assert_(not bob.is_superuser)
+        self.assertTrue(alice is not None)
+        self.assertEqual(alice.first_name, six.u("Alice"))
+        self.assertEqual(alice.last_name, six.u("Adams"))
+        self.assertTrue(alice.is_active)
+        self.assertTrue(alice.is_staff)
+        self.assertTrue(alice.is_superuser)
+        self.assertTrue(bob is not None)
+        self.assertEqual(bob.first_name, six.u("Robert"))
+        self.assertEqual(bob.last_name, six.u("Barker"))
+        self.assertTrue(not bob.is_active)
+        self.assertTrue(not bob.is_staff)
+        self.assertTrue(not bob.is_superuser)
 
     def test_populate_bogus_user(self):
         self._init_settings(
             START_TLS=False,
         )
 
-        self.assert_(not self.mock_ldap.tls_enabled)
+        self.assertTrue(not self.mock_ldap.tls_enabled)
         self.backend.authenticate(username='alice', password='password')
-        self.assert_(not self.mock_ldap.tls_enabled)
+        self.assertTrue(not self.mock_ldap.tls_enabled)
 
     def test_start_tls(self):
         self._init_settings(
             START_TLS=True,
         )
 
-        self.assert_(not self.mock_ldap.tls_enabled)
+        self.assertTrue(not self.mock_ldap.tls_enabled)
         self.backend.authenticate(username='alice', password='password')
-        self.assert_(self.mock_ldap.tls_enabled)
+        self.assertTrue(self.mock_ldap.tls_enabled)
 
     def test_null_search_results(self):
         """
 
         alice = self.backend.authenticate(username='alice', password='password')
 
-        self.assert_(alice is not None)
+        self.assertTrue(alice is not None)
 
         self.assertEqual(self.mock_ldap.ldap_methods_called(),
             ['initialize', 'simple_bind_s', 'search', 'search', 'result',
             USER_DN_TEMPLATE='uid=%(user)s,ou=people,o=test',
         )
 
-        alice = self.backend.authenticate(username=u'alice', password=u'')
+        alice = self.backend.authenticate(username=six.u('alice'), password=six.u(''))
 
         self.assertEqual(alice, None)
         self.assertEqual(self.mock_ldap.ldap_methods_called(), [])
             PERMIT_EMPTY_PASSWORD=True,
         )
 
-        alice = self.backend.authenticate(username=u'alice', password=u'')
+        alice = self.backend.authenticate(username=six.u('alice'), password=six.u(''))
 
         self.assertEqual(alice, None)
         self.assertEqual(self.mock_ldap.ldap_methods_called(),
             [self.active_gon, self.staff_gon, self.superuser_gon, self.nested_gon]
         )
 
-        alice0 = self.backend.authenticate(username=u'alice', password=u'password')
+        alice0 = self.backend.authenticate(username=six.u('alice'), password=six.u('password'))
 
         pickled = pickle.dumps(alice0, pickle.HIGHEST_PROTOCOL)
         alice = pickle.loads(pickled)
         alice.ldap_user.backend.settings = alice0.ldap_user.backend.settings
 
-        self.assert_(alice is not None)
+        self.assertTrue(alice is not None)
         self.assertEqual(self.backend.get_group_permissions(alice), set(["auth.add_user", "auth.change_user"]))
         self.assertEqual(self.backend.get_all_permissions(alice), set(["auth.add_user", "auth.change_user"]))
-        self.assert_(self.backend.has_perm(alice, "auth.add_user"))
-        self.assert_(self.backend.has_module_perms(alice, "auth"))
+        self.assertTrue(self.backend.has_perm(alice, "auth.add_user"))
+        self.assertTrue(self.backend.has_module_perms(alice, "auth"))
 
     def _init_settings(self, **kwargs):
         self.backend.settings = TestSettings(**kwargs)

test/test/settings.py

 
     'django_auth_ldap',
 )
+
+TEMPLATE_DEBUG = True
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.