Merge pull request #20 from diox/no-username-compat

Add compatibility with user model without username field
This commit is contained in:
ricky rosario 2015-02-17 12:50:28 -05:00
Родитель b5544185b2 3c2240b4d2
Коммит aba5f513e0
5 изменённых файлов: 50 добавлений и 2 удалений

Просмотреть файл

@ -1,3 +1,4 @@
sudo: false
language: python
python:
- "2.6"

Просмотреть файл

@ -24,5 +24,6 @@ class ThreadRequestMiddleware(object):
_local.remote_addr = request.META.get('REMOTE_ADDR', '')
name = '<anon>'
if hasattr(request, 'user') and request.user.is_authenticated():
name = encoding.smart_str(request.user.username)
field = getattr(request.user, 'USERNAME_FIELD', 'username')
name = encoding.smart_str(getattr(request.user, field, ''))
_local.username = name

44
commonware/log/tests.py Normal file
Просмотреть файл

@ -0,0 +1,44 @@
from django.test import SimpleTestCase
import mock
from nose.tools import eq_
from test_utils import RequestFactory
from commonware.log.middleware import (_local, ThreadRequestMiddleware,
get_remote_addr, get_username)
class ThreadRequestMiddlewareTests(SimpleTestCase):
def setUp(self):
if hasattr(_local, 'username'):
delattr(_local, 'username')
if hasattr(_local, 'remote_addr'):
delattr(_local, 'remote_addr')
self.middleware = ThreadRequestMiddleware()
def test_get_remote_addr(self):
req = RequestFactory().get('/')
req.META['REMOTE_ADDR'] = '63.245.217.194'
eq_(get_remote_addr(), None)
self.middleware.process_request(req)
eq_(get_remote_addr(), '63.245.217.194')
def test_get_username_no_username_field(self):
req = RequestFactory().get('/')
req.user = mock.Mock()
del req.user.USERNAME_FIELD
req.user.username = 'my-username'
eq_(get_username(), '<anon>')
self.middleware.process_request(req)
eq_(get_username(), 'my-username')
def test_get_username_with_username_field(self):
req = RequestFactory().get('/')
req.user = mock.Mock()
req.user.USERNAME_FIELD = 'myfield'
req.user.myfield = 'my-new-username'
eq_(get_username(), '<anon>')
self.middleware.process_request(req)
eq_(get_username(), 'my-new-username')

Просмотреть файл

@ -9,3 +9,5 @@ JINJA_CONFIG = {}
STS_SUBDOMAINS = False
KNOWN_PROXIES = []
SECRET_KEY = 'not so secret key for testing'

Просмотреть файл

@ -2,6 +2,6 @@
nose
mock
fabric
Django>=1.3
Django<1.7
-e git+git://github.com/jbalogh/test-utils.git#egg=test_utils
-e git+git://github.com/jbalogh/django-nose.git#egg=django_nose