Code

Ticket #19822: 19822-1.diff

File 19822-1.diff, 2.7 KB (added by claudep, 14 months ago)
Line 
1diff --git a/django/contrib/auth/tests/custom_user.py b/django/contrib/auth/tests/custom_user.py
2index 8cc57d4..e4ac8bc 100644
3--- a/django/contrib/auth/tests/custom_user.py
4+++ b/django/contrib/auth/tests/custom_user.py
5@@ -144,3 +144,12 @@ class IsActiveTestUser1(AbstractBaseUser):
6         app_label = 'auth'
7 
8     # the is_active attr is provided by AbstractBaseUser
9+
10+
11+class CustomUserNonUniqueUsername(AbstractBaseUser):
12+    username =models.CharField(max_length=30)
13+
14+    USERNAME_FIELD = 'username'
15+
16+    class Meta:
17+        app_label = 'auth'
18diff --git a/django/contrib/auth/tests/management.py b/django/contrib/auth/tests/management.py
19index 42f14d6..67708fc 100644
20--- a/django/contrib/auth/tests/management.py
21+++ b/django/contrib/auth/tests/management.py
22@@ -9,6 +9,7 @@ from django.contrib.auth.tests import CustomUser
23 from django.contrib.auth.tests.utils import skipIfCustomUser
24 from django.core.management import call_command
25 from django.core.management.base import CommandError
26+from django.db.models.loading import get_app
27 from django.test import TestCase
28 from django.test.utils import override_settings
29 from django.utils import six
30@@ -170,6 +171,17 @@ class CreatesuperuserManagementCommandTestCase(TestCase):
31         self.assertEqual(CustomUser._default_manager.count(), 0)
32 
33 
34+class CustomUserModelValidationTestCase(TestCase):
35+    @override_settings(AUTH_USER_MODEL='auth.CustomUserNonUniqueUsername')
36+    def test_username_non_unique(self):
37+        """
38+        A non-unique USERNAME_FIELD should raise a model validation error.
39+        """
40+        from django.core.management.validation import get_validation_errors
41+        new_io = StringIO()
42+        get_validation_errors(new_io, get_app('auth'))
43+        self.assertIn("The USERNAME_FIELD must be indexed as unique", new_io.getvalue())
44+
45 class PermissionDuplicationTestCase(TestCase):
46 
47     def setUp(self):
48diff --git a/django/core/management/validation.py b/django/core/management/validation.py
49index f49a3c2..ab47f3b 100644
50--- a/django/core/management/validation.py
51+++ b/django/core/management/validation.py
52@@ -54,6 +54,8 @@ def get_validation_errors(outfile, app=None):
53             # Check that the USERNAME FIELD isn't included in REQUIRED_FIELDS.
54             if cls.USERNAME_FIELD in cls.REQUIRED_FIELDS:
55                 e.add(opts, 'The field named as the USERNAME_FIELD should not be included in REQUIRED_FIELDS on a swappable User model.')
56+            if not opts.get_field(cls.USERNAME_FIELD).unique:
57+                e.add(opts, 'The USERNAME_FIELD must be indexed as unique (unique=True in the field parameters).')
58 
59         # Model isn't swapped; do field-specific validation.
60         for f in opts.local_fields: