~ubuntu-branches/debian/sid/python-django/sid

« back to all changes in this revision

Viewing changes to django/contrib/auth/tests/basic.py

  • Committer: Package Import Robot
  • Author(s): Luke Faraone
  • Date: 2013-11-07 15:33:49 UTC
  • mfrom: (1.3.12)
  • Revision ID: package-import@ubuntu.com-20131107153349-e31sc149l2szs3jb
Tags: 1.6-1
* New upstream version. Closes: #557474, #724637.
* python-django now also suggests the installation of ipython,
  bpython, python-django-doc, and libgdal1.
  Closes: #636511, #686333, #704203
* Set package maintainer to Debian Python Modules Team.
* Bump standards version to 3.9.5, no changes needed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# -*- encoding: utf-8 -*-
2
 
from __future__ import unicode_literals
3
 
 
4
 
import locale
5
 
 
6
 
from django.contrib.auth import get_user_model
7
 
from django.contrib.auth.management.commands import createsuperuser
8
 
from django.contrib.auth.models import User, AnonymousUser
9
 
from django.contrib.auth.tests.custom_user import CustomUser
10
 
from django.contrib.auth.tests.utils import skipIfCustomUser
11
 
from django.core.exceptions import ImproperlyConfigured
12
 
from django.core.management import call_command
13
 
from django.test import TestCase
14
 
from django.test.utils import override_settings
15
 
from django.utils.encoding import force_str
16
 
from django.utils.six import binary_type, PY3, StringIO
17
 
 
18
 
 
19
 
def mock_inputs(inputs):
20
 
    """
21
 
    Decorator to temporarily replace input/getpass to allow interactive
22
 
    createsuperuser.
23
 
    """
24
 
    def inner(test_func):
25
 
        def wrapped(*args):
26
 
            class mock_getpass:
27
 
                @staticmethod
28
 
                def getpass(prompt=b'Password: ', stream=None):
29
 
                    if not PY3:
30
 
                        # getpass on Windows only supports prompt as bytestring (#19807)
31
 
                        assert isinstance(prompt, binary_type)
32
 
                    return inputs['password']
33
 
 
34
 
            def mock_input(prompt):
35
 
                # prompt should be encoded in Python 2. This line will raise an
36
 
                # Exception if prompt contains unencoded non-ascii on Python 2.
37
 
                prompt = str(prompt)
38
 
                assert str('__proxy__') not in prompt
39
 
                response = ''
40
 
                for key, val in inputs.items():
41
 
                    if force_str(key) in prompt.lower():
42
 
                        response = val
43
 
                        break
44
 
                return response
45
 
 
46
 
            old_getpass = createsuperuser.getpass
47
 
            old_input = createsuperuser.input
48
 
            createsuperuser.getpass = mock_getpass
49
 
            createsuperuser.input = mock_input
50
 
            try:
51
 
                test_func(*args)
52
 
            finally:
53
 
                createsuperuser.getpass = old_getpass
54
 
                createsuperuser.input = old_input
55
 
        return wrapped
56
 
    return inner
57
 
 
58
 
 
59
 
@skipIfCustomUser
60
 
class BasicTestCase(TestCase):
61
 
    def test_user(self):
62
 
        "Check that users can be created and can set their password"
63
 
        u = User.objects.create_user('testuser', 'test@example.com', 'testpw')
64
 
        self.assertTrue(u.has_usable_password())
65
 
        self.assertFalse(u.check_password('bad'))
66
 
        self.assertTrue(u.check_password('testpw'))
67
 
 
68
 
        # Check we can manually set an unusable password
69
 
        u.set_unusable_password()
70
 
        u.save()
71
 
        self.assertFalse(u.check_password('testpw'))
72
 
        self.assertFalse(u.has_usable_password())
73
 
        u.set_password('testpw')
74
 
        self.assertTrue(u.check_password('testpw'))
75
 
        u.set_password(None)
76
 
        self.assertFalse(u.has_usable_password())
77
 
 
78
 
        # Check authentication/permissions
79
 
        self.assertTrue(u.is_authenticated())
80
 
        self.assertFalse(u.is_staff)
81
 
        self.assertTrue(u.is_active)
82
 
        self.assertFalse(u.is_superuser)
83
 
 
84
 
        # Check API-based user creation with no password
85
 
        u2 = User.objects.create_user('testuser2', 'test2@example.com')
86
 
        self.assertFalse(u2.has_usable_password())
87
 
 
88
 
    def test_user_no_email(self):
89
 
        "Check that users can be created without an email"
90
 
        u = User.objects.create_user('testuser1')
91
 
        self.assertEqual(u.email, '')
92
 
 
93
 
        u2 = User.objects.create_user('testuser2', email='')
94
 
        self.assertEqual(u2.email, '')
95
 
 
96
 
        u3 = User.objects.create_user('testuser3', email=None)
97
 
        self.assertEqual(u3.email, '')
98
 
 
99
 
    def test_anonymous_user(self):
100
 
        "Check the properties of the anonymous user"
101
 
        a = AnonymousUser()
102
 
        self.assertEqual(a.pk, None)
103
 
        self.assertFalse(a.is_authenticated())
104
 
        self.assertFalse(a.is_staff)
105
 
        self.assertFalse(a.is_active)
106
 
        self.assertFalse(a.is_superuser)
107
 
        self.assertEqual(a.groups.all().count(), 0)
108
 
        self.assertEqual(a.user_permissions.all().count(), 0)
109
 
 
110
 
    def test_superuser(self):
111
 
        "Check the creation and properties of a superuser"
112
 
        super = User.objects.create_superuser('super', 'super@example.com', 'super')
113
 
        self.assertTrue(super.is_superuser)
114
 
        self.assertTrue(super.is_active)
115
 
        self.assertTrue(super.is_staff)
116
 
 
117
 
    def test_createsuperuser_management_command(self):
118
 
        "Check the operation of the createsuperuser management command"
119
 
        # We can use the management command to create a superuser
120
 
        new_io = StringIO()
121
 
        call_command("createsuperuser",
122
 
            interactive=False,
123
 
            username="joe",
124
 
            email="joe@somewhere.org",
125
 
            stdout=new_io
126
 
        )
127
 
        command_output = new_io.getvalue().strip()
128
 
        self.assertEqual(command_output, 'Superuser created successfully.')
129
 
        u = User.objects.get(username="joe")
130
 
        self.assertEqual(u.email, 'joe@somewhere.org')
131
 
 
132
 
        # created password should be unusable
133
 
        self.assertFalse(u.has_usable_password())
134
 
 
135
 
        # We can supress output on the management command
136
 
        new_io = StringIO()
137
 
        call_command("createsuperuser",
138
 
            interactive=False,
139
 
            username="joe2",
140
 
            email="joe2@somewhere.org",
141
 
            verbosity=0,
142
 
            stdout=new_io
143
 
        )
144
 
        command_output = new_io.getvalue().strip()
145
 
        self.assertEqual(command_output, '')
146
 
        u = User.objects.get(username="joe2")
147
 
        self.assertEqual(u.email, 'joe2@somewhere.org')
148
 
        self.assertFalse(u.has_usable_password())
149
 
 
150
 
        call_command("createsuperuser",
151
 
            interactive=False,
152
 
            username="joe+admin@somewhere.org",
153
 
            email="joe@somewhere.org",
154
 
            verbosity=0
155
 
        )
156
 
        u = User.objects.get(username="joe+admin@somewhere.org")
157
 
        self.assertEqual(u.email, 'joe@somewhere.org')
158
 
        self.assertFalse(u.has_usable_password())
159
 
 
160
 
    @mock_inputs({'password': "nopasswd"})
161
 
    def test_createsuperuser_nolocale(self):
162
 
        """
163
 
        Check that createsuperuser does not break when no locale is set. See
164
 
        ticket #16017.
165
 
        """
166
 
 
167
 
        old_getdefaultlocale = locale.getdefaultlocale
168
 
        try:
169
 
            # Temporarily remove locale information
170
 
            locale.getdefaultlocale = lambda: (None, None)
171
 
 
172
 
            # Call the command in this new environment
173
 
            call_command("createsuperuser",
174
 
                interactive=True,
175
 
                username="nolocale@somewhere.org",
176
 
                email="nolocale@somewhere.org",
177
 
                verbosity=0
178
 
            )
179
 
 
180
 
        except TypeError:
181
 
            self.fail("createsuperuser fails if the OS provides no information about the current locale")
182
 
 
183
 
        finally:
184
 
            # Re-apply locale information
185
 
            locale.getdefaultlocale = old_getdefaultlocale
186
 
 
187
 
        # If we were successful, a user should have been created
188
 
        u = User.objects.get(username="nolocale@somewhere.org")
189
 
        self.assertEqual(u.email, 'nolocale@somewhere.org')
190
 
 
191
 
    @mock_inputs({
192
 
        'password': "nopasswd",
193
 
        'uživatel': 'foo',  # username (cz)
194
 
        'email': 'nolocale@somewhere.org'})
195
 
    def test_createsuperuser_non_ascii_verbose_name(self):
196
 
        # Aliased so the string doesn't get extracted
197
 
        from django.utils.translation import ugettext_lazy as ulazy
198
 
        username_field = User._meta.get_field('username')
199
 
        old_verbose_name = username_field.verbose_name
200
 
        username_field.verbose_name = ulazy('uživatel')
201
 
        new_io = StringIO()
202
 
        try:
203
 
            call_command("createsuperuser",
204
 
                interactive=True,
205
 
                stdout=new_io
206
 
            )
207
 
        finally:
208
 
            username_field.verbose_name = old_verbose_name
209
 
 
210
 
        command_output = new_io.getvalue().strip()
211
 
        self.assertEqual(command_output, 'Superuser created successfully.')
212
 
 
213
 
    def test_get_user_model(self):
214
 
        "The current user model can be retrieved"
215
 
        self.assertEqual(get_user_model(), User)
216
 
 
217
 
    @override_settings(AUTH_USER_MODEL='auth.CustomUser')
218
 
    def test_swappable_user(self):
219
 
        "The current user model can be swapped out for another"
220
 
        self.assertEqual(get_user_model(), CustomUser)
221
 
        with self.assertRaises(AttributeError):
222
 
            User.objects.all()
223
 
 
224
 
    @override_settings(AUTH_USER_MODEL='badsetting')
225
 
    def test_swappable_user_bad_setting(self):
226
 
        "The alternate user setting must point to something in the format app.model"
227
 
        with self.assertRaises(ImproperlyConfigured):
228
 
            get_user_model()
229
 
 
230
 
    @override_settings(AUTH_USER_MODEL='thismodel.doesntexist')
231
 
    def test_swappable_user_nonexistent_model(self):
232
 
        "The current user model must point to an installed model"
233
 
        with self.assertRaises(ImproperlyConfigured):
234
 
            get_user_model()