11import importlib
22from io import StringIO
3+ from unittest .mock import patch
34
45import pytest
56from django .contrib .admin import site
1112from rest_framework .authtoken .admin import TokenAdmin
1213from rest_framework .authtoken .management .commands .drf_create_token import \
1314 Command as AuthTokenCommand
14- from rest_framework .authtoken .models import Token
15+ from rest_framework .authtoken .models import Token , TokenProxy
1516from rest_framework .authtoken .serializers import AuthTokenSerializer
1617from rest_framework .exceptions import ValidationError
1718
18-
1919class AuthTokenTests (TestCase ):
2020
2121 def setUp (self ):
@@ -36,6 +36,28 @@ def test_model_admin_displayed_fields(self):
3636 token_admin = TokenAdmin (self .token , self .site )
3737 assert token_admin .get_fields (mock_request ) == ('user' ,)
3838
39+ def test_model_admin__username_field (self ):
40+ import rest_framework .authtoken .admin as authtoken_admin_m
41+
42+ class EmailUser (User ):
43+ USERNAME_FIELD = 'email'
44+ username = None
45+
46+ with patch ('django.contrib.admin.site.register' ): # avoid duplicate registrations
47+ for user_model in (User , EmailUser ):
48+ with (
49+ self .subTest (user_model = user_model ),
50+ patch ('django.contrib.auth.get_user_model' , return_value = user_model ) as get_user_model
51+ ):
52+ importlib .reload (authtoken_admin_m ) # reload after patching
53+ assert get_user_model .call_count == 1
54+
55+ mock_request = object ()
56+ token_admin = authtoken_admin_m .TokenAdmin (TokenProxy , self .site )
57+ assert token_admin .get_search_fields (mock_request ) == (f'user__{ user_model .USERNAME_FIELD } ' ,)
58+ assert token_admin .get_ordering (mock_request ) == (f'user__{ user_model .USERNAME_FIELD } ' ,)
59+ importlib .reload (authtoken_admin_m ) # restore after testing
60+
3961 def test_token_string_representation (self ):
4062 assert str (self .token ) == 'test token'
4163
0 commit comments