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

« back to all changes in this revision

Viewing changes to django/contrib/auth/tests/test_context_processors.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
import os
 
2
 
 
3
from django.conf import global_settings
 
4
from django.contrib.auth import authenticate
 
5
from django.contrib.auth.tests.utils import skipIfCustomUser
 
6
from django.contrib.auth.models import User, Permission
 
7
from django.contrib.contenttypes.models import ContentType
 
8
from django.contrib.auth.context_processors import PermWrapper, PermLookupDict
 
9
from django.db.models import Q
 
10
from django.test import TestCase
 
11
from django.test.utils import override_settings
 
12
from django.utils._os import upath
 
13
 
 
14
 
 
15
class MockUser(object):
 
16
    def has_module_perms(self, perm):
 
17
        if perm == 'mockapp':
 
18
            return True
 
19
        return False
 
20
 
 
21
    def has_perm(self, perm):
 
22
        if perm == 'mockapp.someperm':
 
23
            return True
 
24
        return False
 
25
 
 
26
 
 
27
class PermWrapperTests(TestCase):
 
28
    """
 
29
    Test some details of the PermWrapper implementation.
 
30
    """
 
31
    class EQLimiterObject(object):
 
32
        """
 
33
        This object makes sure __eq__ will not be called endlessly.
 
34
        """
 
35
        def __init__(self):
 
36
            self.eq_calls = 0
 
37
 
 
38
        def __eq__(self, other):
 
39
            if self.eq_calls > 0:
 
40
                return True
 
41
            self.eq_calls += 1
 
42
            return False
 
43
 
 
44
    def test_permwrapper_in(self):
 
45
        """
 
46
        Test that 'something' in PermWrapper works as expected.
 
47
        """
 
48
        perms = PermWrapper(MockUser())
 
49
        # Works for modules and full permissions.
 
50
        self.assertTrue('mockapp' in perms)
 
51
        self.assertFalse('nonexisting' in perms)
 
52
        self.assertTrue('mockapp.someperm' in perms)
 
53
        self.assertFalse('mockapp.nonexisting' in perms)
 
54
 
 
55
    def test_permlookupdict_in(self):
 
56
        """
 
57
        No endless loops if accessed with 'in' - refs #18979.
 
58
        """
 
59
        pldict = PermLookupDict(MockUser(), 'mockapp')
 
60
        with self.assertRaises(TypeError):
 
61
            self.EQLimiterObject() in pldict
 
62
 
 
63
 
 
64
@skipIfCustomUser
 
65
@override_settings(
 
66
    TEMPLATE_LOADERS=('django.template.loaders.filesystem.Loader',),
 
67
    TEMPLATE_DIRS=(
 
68
        os.path.join(os.path.dirname(upath(__file__)), 'templates'),
 
69
    ),
 
70
    USE_TZ=False,                           # required for loading the fixture
 
71
    PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
 
72
)
 
73
class AuthContextProcessorTests(TestCase):
 
74
    """
 
75
    Tests for the ``django.contrib.auth.context_processors.auth`` processor
 
76
    """
 
77
    urls = 'django.contrib.auth.tests.urls'
 
78
    fixtures = ['context-processors-users.xml']
 
79
 
 
80
    @override_settings(
 
81
        MIDDLEWARE_CLASSES=global_settings.MIDDLEWARE_CLASSES,
 
82
        TEMPLATE_CONTEXT_PROCESSORS=global_settings.TEMPLATE_CONTEXT_PROCESSORS,
 
83
    )
 
84
    def test_session_not_accessed(self):
 
85
        """
 
86
        Tests that the session is not accessed simply by including
 
87
        the auth context processor
 
88
        """
 
89
        response = self.client.get('/auth_processor_no_attr_access/')
 
90
        self.assertContains(response, "Session not accessed")
 
91
 
 
92
    @override_settings(
 
93
        MIDDLEWARE_CLASSES=global_settings.MIDDLEWARE_CLASSES,
 
94
        TEMPLATE_CONTEXT_PROCESSORS=global_settings.TEMPLATE_CONTEXT_PROCESSORS,
 
95
    )
 
96
    def test_session_is_accessed(self):
 
97
        """
 
98
        Tests that the session is accessed if the auth context processor
 
99
        is used and relevant attributes accessed.
 
100
        """
 
101
        response = self.client.get('/auth_processor_attr_access/')
 
102
        self.assertContains(response, "Session accessed")
 
103
 
 
104
    def test_perms_attrs(self):
 
105
        u = User.objects.create_user(username='normal', password='secret')
 
106
        u.user_permissions.add(
 
107
            Permission.objects.get(
 
108
                content_type=ContentType.objects.get_for_model(Permission),
 
109
                codename='add_permission'))
 
110
        self.client.login(username='normal', password='secret')
 
111
        response = self.client.get('/auth_processor_perms/')
 
112
        self.assertContains(response, "Has auth permissions")
 
113
        self.assertContains(response, "Has auth.add_permission permissions")
 
114
        self.assertNotContains(response, "nonexisting")
 
115
    
 
116
    def test_perm_in_perms_attrs(self):
 
117
        u = User.objects.create_user(username='normal', password='secret')
 
118
        u.user_permissions.add(
 
119
            Permission.objects.get(
 
120
                content_type=ContentType.objects.get_for_model(Permission),
 
121
                codename='add_permission'))
 
122
        self.client.login(username='normal', password='secret')
 
123
        response = self.client.get('/auth_processor_perm_in_perms/')
 
124
        self.assertContains(response, "Has auth permissions")
 
125
        self.assertContains(response, "Has auth.add_permission permissions")
 
126
        self.assertNotContains(response, "nonexisting")
 
127
 
 
128
    def test_message_attrs(self):
 
129
        self.client.login(username='super', password='secret')
 
130
        response = self.client.get('/auth_processor_messages/')
 
131
        self.assertContains(response, "Message 1")
 
132
 
 
133
    def test_user_attrs(self):
 
134
        """
 
135
        Test that the lazy objects returned behave just like the wrapped objects.
 
136
        """
 
137
        # These are 'functional' level tests for common use cases.  Direct
 
138
        # testing of the implementation (SimpleLazyObject) is in the 'utils'
 
139
        # tests.
 
140
        self.client.login(username='super', password='secret')
 
141
        user = authenticate(username='super', password='secret')
 
142
        response = self.client.get('/auth_processor_user/')
 
143
        self.assertContains(response, "unicode: super")
 
144
        self.assertContains(response, "id: 100")
 
145
        self.assertContains(response, "username: super")
 
146
        # bug #12037 is tested by the {% url %} in the template:
 
147
        self.assertContains(response, "url: /userpage/super/")
 
148
 
 
149
        # See if this object can be used for queries where a Q() comparing
 
150
        # a user can be used with another Q() (in an AND or OR fashion).
 
151
        # This simulates what a template tag might do with the user from the
 
152
        # context. Note that we don't need to execute a query, just build it.
 
153
        #
 
154
        # The failure case (bug #12049) on Python 2.4 with a LazyObject-wrapped
 
155
        # User is a fatal TypeError: "function() takes at least 2 arguments
 
156
        # (0 given)" deep inside deepcopy().
 
157
        #
 
158
        # Python 2.5 and 2.6 succeeded, but logged internally caught exception
 
159
        # spew:
 
160
        #
 
161
        #    Exception RuntimeError: 'maximum recursion depth exceeded while
 
162
        #    calling a Python object' in <type 'exceptions.AttributeError'>
 
163
        #    ignored"
 
164
        query = Q(user=response.context['user']) & Q(someflag=True)
 
165
 
 
166
        # Tests for user equality.  This is hard because User defines
 
167
        # equality in a non-duck-typing way
 
168
        # See bug #12060
 
169
        self.assertEqual(response.context['user'], user)
 
170
        self.assertEqual(user, response.context['user'])