blob: 173bb00f7ff41ebab921e2280c362af042499383 [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'
29
30 @pytest.fixture(autouse=True)
31 def credentials(self):
32 self.credentials = credentials.Credentials(
33 token=None, refresh_token=self.REFRESH_TOKEN,
34 token_uri=self.TOKEN_URI, client_id=self.CLIENT_ID,
35 client_secret=self.CLIENT_SECRET)
36
37 def test_default_state(self):
38 assert not self.credentials.valid
39 # Expiration hasn't been set yet
40 assert not self.credentials.expired
41 # Scopes aren't required for these credentials
42 assert not self.credentials.requires_scopes
43
44 def test_create_scoped(self):
45 with pytest.raises(NotImplementedError):
46 self.credentials.with_scopes(['email'])
47
48 @mock.patch('google.oauth2._client.refresh_grant')
49 @mock.patch(
50 'google.auth._helpers.utcnow', return_value=datetime.datetime.min)
51 def test_refresh_success(self, now_mock, refresh_grant_mock):
52 token = 'token'
53 expiry = _helpers.utcnow() + datetime.timedelta(seconds=500)
54 refresh_grant_mock.return_value = (
55 # Access token
56 token,
57 # New refresh token
58 None,
59 # Expiry,
60 expiry,
61 # Extra data
62 {})
63 request_mock = mock.Mock()
64
65 # Refresh credentials
66 self.credentials.refresh(request_mock)
67
68 # Check jwt grant call.
69 refresh_grant_mock.assert_called_with(
70 request_mock, self.TOKEN_URI, self.REFRESH_TOKEN, self.CLIENT_ID,
71 self.CLIENT_SECRET)
72
73 # Check that the credentials have the token and expiry
74 assert self.credentials.token == token
75 assert self.credentials.expiry == expiry
76
77 # Check that the credentials are valid (have a token and are not
78 # expired)
79 assert self.credentials.valid