aboutsummaryrefslogtreecommitdiff
path: root/tests/contrib/django_util/test_django_util.py
blob: 84457cb6b23fe3a3c7cc276a50c98317edc2f8ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Tests the initialization logic of django_util."""

import copy

import django.conf
from django.conf.urls import include, url
from django.contrib.auth.models import AnonymousUser
from django.core import exceptions
import mock
from six.moves import reload_module
from tests.contrib.django_util import TestWithDjangoEnvironment
import unittest2

from oauth2client.contrib import django_util
import oauth2client.contrib.django_util
from oauth2client.contrib.django_util import (
    _CREDENTIALS_KEY, get_storage, site, UserOAuth2)


urlpatterns = [
    url(r'^oauth2/', include(site.urls))
]


class OAuth2SetupTest(unittest2.TestCase):

    def setUp(self):
        self.save_settings = copy.deepcopy(django.conf.settings)
        # OAuth2 Settings gets configured based on Django settings
        # at import time, so in order for us to reload the settings
        # we need to reload the module
        reload_module(oauth2client.contrib.django_util)

    def tearDown(self):
        django.conf.settings = copy.deepcopy(self.save_settings)

    @mock.patch("oauth2client.contrib.django_util.clientsecrets")
    def test_settings_initialize(self, clientsecrets):
        django.conf.settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = 'file.json'
        clientsecrets.loadfile.return_value = (
            clientsecrets.TYPE_WEB,
            {
                'client_id': 'myid',
                'client_secret': 'hunter2'
            }
        )

        oauth2_settings = django_util.OAuth2Settings(django.conf.settings)
        self.assertTrue(clientsecrets.loadfile.called)
        self.assertEqual(oauth2_settings.client_id, 'myid')
        self.assertEqual(oauth2_settings.client_secret, 'hunter2')
        django.conf.settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = None

    @mock.patch("oauth2client.contrib.django_util.clientsecrets")
    def test_settings_initialize_invalid_type(self, clientsecrets):
        django.conf.settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = 'file.json'
        clientsecrets.loadfile.return_value = (
            "wrong_type",
            {
                'client_id': 'myid',
                'client_secret': 'hunter2'
            }
        )

        with self.assertRaises(ValueError):
            django_util.OAuth2Settings.__init__(
                object.__new__(django_util.OAuth2Settings),
                django.conf.settings)

    @mock.patch("oauth2client.contrib.django_util.clientsecrets")
    def test_no_settings(self, clientsecrets):
        django.conf.settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = None
        django.conf.settings.GOOGLE_OAUTH2_CLIENT_SECRET = None
        django.conf.settings.GOOGLE_OAUTH2_CLIENT_ID = None

        with self.assertRaises(exceptions.ImproperlyConfigured):
            django_util.OAuth2Settings.__init__(
                object.__new__(django_util.OAuth2Settings),
                django.conf.settings)

    @mock.patch("oauth2client.contrib.django_util.clientsecrets")
    def test_no_session_middleware(self, clientsecrets):
        django.conf.settings.MIDDLEWARE_CLASSES = ()

        with self.assertRaises(exceptions.ImproperlyConfigured):
            django_util.OAuth2Settings.__init__(
                object.__new__(django_util.OAuth2Settings),
                django.conf.settings)

    def test_storage_model(self):
        STORAGE_MODEL = {
            'model': 'tests.contrib.django_util.models.CredentialsModel',
            'user_property': 'user_id',
            'credentials_property': 'credentials'
        }
        django.conf.settings.GOOGLE_OAUTH2_STORAGE_MODEL = STORAGE_MODEL
        oauth2_settings = django_util.OAuth2Settings(django.conf.settings)
        self.assertEqual(oauth2_settings.storage_model, STORAGE_MODEL['model'])
        self.assertEqual(oauth2_settings.storage_model_user_property,
                         STORAGE_MODEL['user_property'])
        self.assertEqual(oauth2_settings.storage_model_credentials_property,
                         STORAGE_MODEL['credentials_property'])


class MockObjectWithSession(object):
    def __init__(self, session):
        self.session = session


class SessionStorageTest(TestWithDjangoEnvironment):

    def setUp(self):
        super(SessionStorageTest, self).setUp()
        self.save_settings = copy.deepcopy(django.conf.settings)
        reload_module(oauth2client.contrib.django_util)

    def tearDown(self):
        super(SessionStorageTest, self).tearDown()
        django.conf.settings = copy.deepcopy(self.save_settings)

    def test_session_delete(self):
        self.session[_CREDENTIALS_KEY] = "test_val"
        request = MockObjectWithSession(self.session)
        django_storage = get_storage(request)
        django_storage.delete()
        self.assertIsNone(self.session.get(_CREDENTIALS_KEY))

    def test_session_delete_nothing(self):
        request = MockObjectWithSession(self.session)
        django_storage = get_storage(request)
        django_storage.delete()


class TestUserOAuth2Object(TestWithDjangoEnvironment):

    def setUp(self):
        super(TestUserOAuth2Object, self).setUp()
        self.save_settings = copy.deepcopy(django.conf.settings)
        STORAGE_MODEL = {
            'model': 'tests.contrib.django_util.models.CredentialsModel',
            'user_property': 'user_id',
            'credentials_property': 'credentials'
        }
        django.conf.settings.GOOGLE_OAUTH2_STORAGE_MODEL = STORAGE_MODEL
        reload_module(oauth2client.contrib.django_util)

    def tearDown(self):
        super(TestUserOAuth2Object, self).tearDown()
        import django.conf
        django.conf.settings = copy.deepcopy(self.save_settings)

    def test_get_credentials_anon_user(self):
        request = self.factory.get('oauth2/oauth2authorize',
                                   data={'return_url': '/return_endpoint'})
        request.session = self.session
        request.user = AnonymousUser()
        oauth2 = UserOAuth2(request)
        self.assertIsNone(oauth2.credentials)