blob: 5c76cb202905061c9ed6ee9ef822f72fd6f470e9 [file] [log] [blame]
Jon Wayne Parrott10ec7e92016-10-17 10:46:38 -07001# Copyright 2016 Google Inc.
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
15import datetime
16
17import mock
18import pytest
19
20from google.auth import _helpers
21from google.oauth2 import credentials
22
23
24class TestCredentials(object):
25 TOKEN_URI = 'https://example.com/oauth2/token'
26 REFRESH_TOKEN = 'refresh_token'
27 CLIENT_ID = 'client_id'
28 CLIENT_SECRET = 'client_secret'
Danny Hermes97791812016-11-01 12:43:01 -070029 credentials = None
Jon Wayne Parrott10ec7e92016-10-17 10:46:38 -070030
31 @pytest.fixture(autouse=True)
Danny Hermes97791812016-11-01 12:43:01 -070032 def credentials_fixture(self):
Jon Wayne Parrott10ec7e92016-10-17 10:46:38 -070033 self.credentials = credentials.Credentials(
34 token=None, refresh_token=self.REFRESH_TOKEN,
35 token_uri=self.TOKEN_URI, client_id=self.CLIENT_ID,
36 client_secret=self.CLIENT_SECRET)
37
38 def test_default_state(self):
39 assert not self.credentials.valid
40 # Expiration hasn't been set yet
41 assert not self.credentials.expired
42 # Scopes aren't required for these credentials
43 assert not self.credentials.requires_scopes
44
45 def test_create_scoped(self):
46 with pytest.raises(NotImplementedError):
47 self.credentials.with_scopes(['email'])
48
49 @mock.patch('google.oauth2._client.refresh_grant')
50 @mock.patch(
51 'google.auth._helpers.utcnow', return_value=datetime.datetime.min)
52 def test_refresh_success(self, now_mock, refresh_grant_mock):
53 token = 'token'
54 expiry = _helpers.utcnow() + datetime.timedelta(seconds=500)
55 refresh_grant_mock.return_value = (
56 # Access token
57 token,
58 # New refresh token
59 None,
60 # Expiry,
61 expiry,
62 # Extra data
63 {})
64 request_mock = mock.Mock()
65
66 # Refresh credentials
67 self.credentials.refresh(request_mock)
68
69 # Check jwt grant call.
70 refresh_grant_mock.assert_called_with(
71 request_mock, self.TOKEN_URI, self.REFRESH_TOKEN, self.CLIENT_ID,
72 self.CLIENT_SECRET)
73
74 # Check that the credentials have the token and expiry
75 assert self.credentials.token == token
76 assert self.credentials.expiry == expiry
77
78 # Check that the credentials are valid (have a token and are not
79 # expired)
80 assert self.credentials.valid