diff --git a/analytical/tests/test_utils.py b/analytical/tests/test_utils.py index d8dec09..3b1636a 100644 --- a/analytical/tests/test_utils.py +++ b/analytical/tests/test_utils.py @@ -1,16 +1,29 @@ """ Tests for the analytical.utils module. """ +import django from django.conf import settings +from django.db import models from django.http import HttpRequest from django.template import Context from django.test.utils import override_settings from analytical.utils import ( - get_domain, is_internal_ip, get_required_setting, AnalyticalException) + get_domain, get_identity, is_internal_ip, get_required_setting, + AnalyticalException) from analytical.tests.utils import TestCase +try: + from unittest import skipIf +except ImportError: # Python 2.6 fallback + from unittest2 import skipIf + +try: + from django.contrib.auth.models import AbstractBaseUser +except ImportError: # Django < 1.5 fallback + AbstractBaseUser = models.Model + class SettingDeletedTestCase(TestCase): @@ -33,6 +46,18 @@ class SettingDeletedTestCase(TestCase): get_required_setting, "USER_ID", "\d+", "invalid USER_ID") +class MyUser(AbstractBaseUser): + identity = models.CharField() + USERNAME_FIELD = 'identity' + + +class GetIdentityTestCase(TestCase): + @skipIf(django.VERSION < (1, 5,), 'Custom usernames not supported in Django < 1.5') + def test_custom_username_field(self): + get_id = get_identity(Context({}), user=MyUser(identity='fake_id')) + self.assertEqual(get_id, 'fake_id') + + @override_settings(ANALYTICAL_DOMAIN="example.org") class GetDomainTestCase(TestCase): def test_get_service_domain_from_context(self): diff --git a/analytical/utils.py b/analytical/utils.py index 6fb7b93..2c52478 100644 --- a/analytical/utils.py +++ b/analytical/utils.py @@ -76,7 +76,10 @@ def get_identity(context, prefix=None, identity_func=None, user=None): if identity_func is not None: return identity_func(user) else: - return user.username + try: + return user.get_username() + except AttributeError: # Django < 1.5 fallback + return user.username except (KeyError, AttributeError): pass return None diff --git a/tox.ini b/tox.ini index 902d99d..713551a 100644 --- a/tox.ini +++ b/tox.ini @@ -18,6 +18,7 @@ basepython = deps = coverage==3.7.1 coveralls + py26: unittest2 django14: Django>=1.4,<1.5 django15: Django>=1.5,<1.6 django16: Django>=1.6,<1.7