• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2015 Google Inc. All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Tests the initialization logic of django_util."""
16
17import copy
18
19import django.conf
20from django.conf.urls import include, url
21from django.contrib.auth.models import AnonymousUser
22from django.core import exceptions
23import mock
24from six.moves import reload_module
25from tests.contrib.django_util import TestWithDjangoEnvironment
26import unittest2
27
28from oauth2client.contrib import django_util
29import oauth2client.contrib.django_util
30from oauth2client.contrib.django_util import (
31    _CREDENTIALS_KEY, get_storage, site, UserOAuth2)
32
33
34urlpatterns = [
35    url(r'^oauth2/', include(site.urls))
36]
37
38
39class OAuth2SetupTest(unittest2.TestCase):
40
41    def setUp(self):
42        self.save_settings = copy.deepcopy(django.conf.settings)
43        # OAuth2 Settings gets configured based on Django settings
44        # at import time, so in order for us to reload the settings
45        # we need to reload the module
46        reload_module(oauth2client.contrib.django_util)
47
48    def tearDown(self):
49        django.conf.settings = copy.deepcopy(self.save_settings)
50
51    @mock.patch("oauth2client.contrib.django_util.clientsecrets")
52    def test_settings_initialize(self, clientsecrets):
53        django.conf.settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = 'file.json'
54        clientsecrets.loadfile.return_value = (
55            clientsecrets.TYPE_WEB,
56            {
57                'client_id': 'myid',
58                'client_secret': 'hunter2'
59            }
60        )
61
62        oauth2_settings = django_util.OAuth2Settings(django.conf.settings)
63        self.assertTrue(clientsecrets.loadfile.called)
64        self.assertEqual(oauth2_settings.client_id, 'myid')
65        self.assertEqual(oauth2_settings.client_secret, 'hunter2')
66        django.conf.settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = None
67
68    @mock.patch("oauth2client.contrib.django_util.clientsecrets")
69    def test_settings_initialize_invalid_type(self, clientsecrets):
70        django.conf.settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = 'file.json'
71        clientsecrets.loadfile.return_value = (
72            "wrong_type",
73            {
74                'client_id': 'myid',
75                'client_secret': 'hunter2'
76            }
77        )
78
79        with self.assertRaises(ValueError):
80            django_util.OAuth2Settings.__init__(
81                object.__new__(django_util.OAuth2Settings),
82                django.conf.settings)
83
84    @mock.patch("oauth2client.contrib.django_util.clientsecrets")
85    def test_no_settings(self, clientsecrets):
86        django.conf.settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = None
87        django.conf.settings.GOOGLE_OAUTH2_CLIENT_SECRET = None
88        django.conf.settings.GOOGLE_OAUTH2_CLIENT_ID = None
89
90        with self.assertRaises(exceptions.ImproperlyConfigured):
91            django_util.OAuth2Settings.__init__(
92                object.__new__(django_util.OAuth2Settings),
93                django.conf.settings)
94
95    @mock.patch("oauth2client.contrib.django_util.clientsecrets")
96    def test_no_session_middleware(self, clientsecrets):
97        django.conf.settings.MIDDLEWARE_CLASSES = ()
98
99        with self.assertRaises(exceptions.ImproperlyConfigured):
100            django_util.OAuth2Settings.__init__(
101                object.__new__(django_util.OAuth2Settings),
102                django.conf.settings)
103
104    def test_storage_model(self):
105        STORAGE_MODEL = {
106            'model': 'tests.contrib.django_util.models.CredentialsModel',
107            'user_property': 'user_id',
108            'credentials_property': 'credentials'
109        }
110        django.conf.settings.GOOGLE_OAUTH2_STORAGE_MODEL = STORAGE_MODEL
111        oauth2_settings = django_util.OAuth2Settings(django.conf.settings)
112        self.assertEqual(oauth2_settings.storage_model, STORAGE_MODEL['model'])
113        self.assertEqual(oauth2_settings.storage_model_user_property,
114                         STORAGE_MODEL['user_property'])
115        self.assertEqual(oauth2_settings.storage_model_credentials_property,
116                         STORAGE_MODEL['credentials_property'])
117
118
119class MockObjectWithSession(object):
120    def __init__(self, session):
121        self.session = session
122
123
124class SessionStorageTest(TestWithDjangoEnvironment):
125
126    def setUp(self):
127        super(SessionStorageTest, self).setUp()
128        self.save_settings = copy.deepcopy(django.conf.settings)
129        reload_module(oauth2client.contrib.django_util)
130
131    def tearDown(self):
132        super(SessionStorageTest, self).tearDown()
133        django.conf.settings = copy.deepcopy(self.save_settings)
134
135    def test_session_delete(self):
136        self.session[_CREDENTIALS_KEY] = "test_val"
137        request = MockObjectWithSession(self.session)
138        django_storage = get_storage(request)
139        django_storage.delete()
140        self.assertIsNone(self.session.get(_CREDENTIALS_KEY))
141
142    def test_session_delete_nothing(self):
143        request = MockObjectWithSession(self.session)
144        django_storage = get_storage(request)
145        django_storage.delete()
146
147
148class TestUserOAuth2Object(TestWithDjangoEnvironment):
149
150    def setUp(self):
151        super(TestUserOAuth2Object, self).setUp()
152        self.save_settings = copy.deepcopy(django.conf.settings)
153        STORAGE_MODEL = {
154            'model': 'tests.contrib.django_util.models.CredentialsModel',
155            'user_property': 'user_id',
156            'credentials_property': 'credentials'
157        }
158        django.conf.settings.GOOGLE_OAUTH2_STORAGE_MODEL = STORAGE_MODEL
159        reload_module(oauth2client.contrib.django_util)
160
161    def tearDown(self):
162        super(TestUserOAuth2Object, self).tearDown()
163        import django.conf
164        django.conf.settings = copy.deepcopy(self.save_settings)
165
166    def test_get_credentials_anon_user(self):
167        request = self.factory.get('oauth2/oauth2authorize',
168                                   data={'return_url': '/return_endpoint'})
169        request.session = self.session
170        request.user = AnonymousUser()
171        oauth2 = UserOAuth2(request)
172        self.assertIsNone(oauth2.credentials)
173