This repository has been archived by the owner on Jan 18, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 432
/
Copy pathtest_client.py
2383 lines (2037 loc) · 101 KB
/
test_client.py
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2014 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.
"""Unit tests for oauth2client.client."""
import base64
import contextlib
import copy
import datetime
import json
import os
import socket
import sys
import tempfile
import unittest
import mock
import six
from six.moves import http_client
from six.moves import urllib
import oauth2client
from oauth2client import _helpers
from oauth2client import client
from oauth2client import clientsecrets
from oauth2client import service_account
from oauth2client import transport
from tests import http_mock
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
def assertUrisEqual(testcase, expected, actual):
"""Test that URIs are the same, up to reordering of query parameters."""
expected = urllib.parse.urlparse(expected)
actual = urllib.parse.urlparse(actual)
testcase.assertEqual(expected.scheme, actual.scheme)
testcase.assertEqual(expected.netloc, actual.netloc)
testcase.assertEqual(expected.path, actual.path)
testcase.assertEqual(expected.params, actual.params)
testcase.assertEqual(expected.fragment, actual.fragment)
expected_query = urllib.parse.parse_qs(expected.query)
actual_query = urllib.parse.parse_qs(actual.query)
for name in expected_query.keys():
testcase.assertEqual(expected_query[name], actual_query[name])
for name in actual_query.keys():
testcase.assertEqual(expected_query[name], actual_query[name])
def datafile(filename):
return os.path.join(DATA_DIR, filename)
def load_and_cache(existing_file, fakename, cache_mock):
client_type, client_info = clientsecrets._loadfile(datafile(existing_file))
cache_mock.cache[fakename] = {client_type: client_info}
class CredentialsTests(unittest.TestCase):
def test_to_from_json(self):
credentials = client.Credentials()
json = credentials.to_json()
client.Credentials.new_from_json(json)
def test_authorize_abstract(self):
credentials = client.Credentials()
http = object()
with self.assertRaises(NotImplementedError):
credentials.authorize(http)
def test_refresh_abstract(self):
credentials = client.Credentials()
http = object()
with self.assertRaises(NotImplementedError):
credentials.refresh(http)
def test_revoke_abstract(self):
credentials = client.Credentials()
http = object()
with self.assertRaises(NotImplementedError):
credentials.revoke(http)
def test_apply_abstract(self):
credentials = client.Credentials()
headers = {}
with self.assertRaises(NotImplementedError):
credentials.apply(headers)
def test__to_json_basic(self):
credentials = client.Credentials()
json_payload = credentials._to_json([])
# str(bytes) in Python2 and str(unicode) in Python3
self.assertIsInstance(json_payload, str)
payload = json.loads(json_payload)
expected_payload = {
'_class': client.Credentials.__name__,
'_module': client.Credentials.__module__,
'token_expiry': None,
}
self.assertEqual(payload, expected_payload)
def test__to_json_with_strip(self):
credentials = client.Credentials()
credentials.foo = 'bar'
credentials.baz = 'quux'
to_strip = ['foo']
json_payload = credentials._to_json(to_strip)
# str(bytes) in Python2 and str(unicode) in Python3
self.assertIsInstance(json_payload, str)
payload = json.loads(json_payload)
expected_payload = {
'_class': client.Credentials.__name__,
'_module': client.Credentials.__module__,
'token_expiry': None,
'baz': credentials.baz,
}
self.assertEqual(payload, expected_payload)
def test__to_json_to_serialize(self):
credentials = client.Credentials()
to_serialize = {
'foo': b'bar',
'baz': u'quux',
'st': set(['a', 'b']),
}
orig_vals = to_serialize.copy()
json_payload = credentials._to_json([], to_serialize=to_serialize)
# str(bytes) in Python2 and str(unicode) in Python3
self.assertIsInstance(json_payload, str)
payload = json.loads(json_payload)
expected_payload = {
'_class': client.Credentials.__name__,
'_module': client.Credentials.__module__,
'token_expiry': None,
}
expected_payload.update(to_serialize)
# Special-case the set.
expected_payload['st'] = list(expected_payload['st'])
# Special-case the bytes.
expected_payload['foo'] = u'bar'
self.assertEqual(payload, expected_payload)
# Make sure the method call didn't modify our dictionary.
self.assertEqual(to_serialize, orig_vals)
@mock.patch.object(client.Credentials, '_to_json',
return_value=object())
def test_to_json(self, to_json):
credentials = client.Credentials()
self.assertEqual(credentials.to_json(), to_json.return_value)
to_json.assert_called_once_with(
client.Credentials.NON_SERIALIZED_MEMBERS)
def test_new_from_json_no_data(self):
creds_data = {}
json_data = json.dumps(creds_data)
with self.assertRaises(KeyError):
client.Credentials.new_from_json(json_data)
def test_new_from_json_basic_data(self):
creds_data = {
'_module': 'oauth2client.client',
'_class': 'Credentials',
}
json_data = json.dumps(creds_data)
credentials = client.Credentials.new_from_json(json_data)
self.assertIsInstance(credentials, client.Credentials)
def test_new_from_json_old_name(self):
creds_data = {
'_module': 'oauth2client.googleapiclient.client',
'_class': 'Credentials',
}
json_data = json.dumps(creds_data)
credentials = client.Credentials.new_from_json(json_data)
self.assertIsInstance(credentials, client.Credentials)
def test_new_from_json_bad_module(self):
creds_data = {
'_module': 'oauth2client.foobar',
'_class': 'Credentials',
}
json_data = json.dumps(creds_data)
with self.assertRaises(ImportError):
client.Credentials.new_from_json(json_data)
def test_new_from_json_bad_class(self):
creds_data = {
'_module': 'oauth2client.client',
'_class': 'NopeNotCredentials',
}
json_data = json.dumps(creds_data)
with self.assertRaises(AttributeError):
client.Credentials.new_from_json(json_data)
def test_from_json(self):
unused_data = {}
credentials = client.Credentials.from_json(unused_data)
self.assertIsInstance(credentials, client.Credentials)
self.assertEqual(credentials.__dict__, {})
class TestStorage(unittest.TestCase):
def test_locked_get_abstract(self):
storage = client.Storage()
with self.assertRaises(NotImplementedError):
storage.locked_get()
def test_locked_put_abstract(self):
storage = client.Storage()
credentials = object()
with self.assertRaises(NotImplementedError):
storage.locked_put(credentials)
def test_locked_delete_abstract(self):
storage = client.Storage()
with self.assertRaises(NotImplementedError):
storage.locked_delete()
@contextlib.contextmanager
def mock_module_import(module):
"""Place a dummy objects in sys.modules to mock an import test."""
parts = module.split('.')
entries = ['.'.join(parts[:i + 1]) for i in range(len(parts))]
for entry in entries:
sys.modules[entry] = object()
try:
yield
finally:
for entry in entries:
del sys.modules[entry]
class GoogleCredentialsTests(unittest.TestCase):
def setUp(self):
self.os_name = os.name
client.SETTINGS.env_name = None
def tearDown(self):
self.reset_env('SERVER_SOFTWARE')
self.reset_env(client.GOOGLE_APPLICATION_CREDENTIALS)
self.reset_env('APPDATA')
os.name = self.os_name
def reset_env(self, env):
"""Set the environment variable 'env' to 'value'."""
os.environ.pop(env, None)
def validate_service_account_credentials(self, credentials):
self.assertIsInstance(
credentials, service_account.ServiceAccountCredentials)
self.assertEqual('123', credentials.client_id)
self.assertEqual('[email protected]',
credentials._service_account_email)
self.assertEqual('ABCDEF', credentials._private_key_id)
self.assertEqual('', credentials._scopes)
def validate_google_credentials(self, credentials):
self.assertIsInstance(credentials, client.GoogleCredentials)
self.assertEqual(None, credentials.access_token)
self.assertEqual('123', credentials.client_id)
self.assertEqual('secret', credentials.client_secret)
self.assertEqual('alabalaportocala', credentials.refresh_token)
self.assertEqual(None, credentials.token_expiry)
self.assertEqual(oauth2client.GOOGLE_TOKEN_URI, credentials.token_uri)
self.assertEqual('Python client library', credentials.user_agent)
def get_a_google_credentials_object(self):
return client.GoogleCredentials(None, None, None, None,
None, None, None, None)
def test_create_scoped_required(self):
self.assertFalse(
self.get_a_google_credentials_object().create_scoped_required())
def test_create_scoped(self):
credentials = self.get_a_google_credentials_object()
self.assertEqual(credentials, credentials.create_scoped(None))
self.assertEqual(credentials,
credentials.create_scoped(['dummy_scope']))
@mock.patch.object(client.GoogleCredentials,
'_implicit_credentials_from_files',
return_value=None)
@mock.patch.object(client.GoogleCredentials,
'_implicit_credentials_from_gce')
@mock.patch.object(client, '_in_gae_environment',
return_value=True)
@mock.patch.object(client, '_get_application_default_credential_GAE',
return_value=object())
def test_get_application_default_in_gae(self, gae_adc, in_gae,
from_gce, from_files):
credentials = client.GoogleCredentials.get_application_default()
self.assertEqual(credentials, gae_adc.return_value)
from_files.assert_called_once_with()
in_gae.assert_called_once_with()
from_gce.assert_not_called()
@mock.patch.object(client.GoogleCredentials,
'_implicit_credentials_from_gae',
return_value=None)
@mock.patch.object(client.GoogleCredentials,
'_implicit_credentials_from_files',
return_value=None)
@mock.patch.object(client, '_in_gce_environment',
return_value=True)
@mock.patch.object(client, '_get_application_default_credential_GCE',
return_value=object())
def test_get_application_default_in_gce(self, gce_adc, in_gce,
from_files, from_gae):
credentials = client.GoogleCredentials.get_application_default()
self.assertEqual(credentials, gce_adc.return_value)
in_gce.assert_called_once_with()
from_gae.assert_called_once_with()
from_files.assert_called_once_with()
def test_environment_check_gae_production(self):
with mock_module_import('google.appengine'):
self._environment_check_gce_helper(
server_software='Google App Engine/XYZ')
def test_environment_check_gae_local(self):
with mock_module_import('google.appengine'):
self._environment_check_gce_helper(
server_software='Development/XYZ')
def test_environment_check_fastpath(self):
with mock_module_import('google.appengine'):
self._environment_check_gce_helper(
server_software='Development/XYZ')
def test_environment_caching(self):
os.environ['SERVER_SOFTWARE'] = 'Development/XYZ'
with mock_module_import('google.appengine'):
self.assertTrue(client._in_gae_environment())
os.environ['SERVER_SOFTWARE'] = ''
# Even though we no longer pass the environment check, it
# is cached.
self.assertTrue(client._in_gae_environment())
def _environment_check_gce_helper(self, status_ok=True,
server_software=''):
if status_ok:
headers = {'status': http_client.OK}
headers.update(client._GCE_HEADERS)
else:
headers = {'status': http_client.NOT_FOUND}
http = http_mock.HttpMock(headers=headers)
with mock.patch('oauth2client.client.os') as os_module:
os_module.environ = {client._SERVER_SOFTWARE: server_software}
with mock.patch('oauth2client.transport.get_http_object',
return_value=http) as new_http:
if server_software == '':
self.assertFalse(client._in_gae_environment())
else:
self.assertTrue(client._in_gae_environment())
if status_ok and server_software == '':
self.assertTrue(client._in_gce_environment())
else:
self.assertFalse(client._in_gce_environment())
# Verify mocks.
if server_software == '':
new_http.assert_called_once_with(
timeout=client.GCE_METADATA_TIMEOUT)
self.assertEqual(http.requests, 1)
self.assertEqual(http.uri, client._GCE_METADATA_URI)
self.assertEqual(http.method, 'GET')
self.assertIsNone(http.body)
self.assertEqual(http.headers, client._GCE_HEADERS)
else:
new_http.assert_not_called()
self.assertEqual(http.requests, 0)
def test_environment_check_gce_production(self):
self._environment_check_gce_helper(status_ok=True)
def test_environment_check_gce_prod_with_working_gae_imports(self):
with mock_module_import('google.appengine'):
self._environment_check_gce_helper(status_ok=True)
@mock.patch('oauth2client.client.os.environ',
new={client._SERVER_SOFTWARE: ''})
@mock.patch('oauth2client.transport.get_http_object',
return_value=object())
@mock.patch('oauth2client.transport.request',
side_effect=socket.timeout())
def test_environment_check_gce_timeout(self, mock_request, new_http):
self.assertFalse(client._in_gae_environment())
self.assertFalse(client._in_gce_environment())
# Verify mocks.
new_http.assert_called_once_with(timeout=client.GCE_METADATA_TIMEOUT)
mock_request.assert_called_once_with(
new_http.return_value, client._GCE_METADATA_URI,
headers=client._GCE_HEADERS)
def test_environ_check_gae_module_unknown(self):
with mock_module_import('google.appengine'):
self._environment_check_gce_helper(status_ok=False)
def test_environment_check_unknown(self):
self._environment_check_gce_helper(status_ok=False)
def test_get_environment_variable_file(self):
environment_variable_file = datafile(
os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE))
os.environ[client.GOOGLE_APPLICATION_CREDENTIALS] = (
environment_variable_file)
self.assertEqual(environment_variable_file,
client._get_environment_variable_file())
def test_get_environment_variable_file_error(self):
nonexistent_file = datafile('nonexistent')
os.environ[client.GOOGLE_APPLICATION_CREDENTIALS] = nonexistent_file
expected_err_msg = (
'File {0} \(pointed by {1} environment variable\) does not '
'exist!'.format(
nonexistent_file, client.GOOGLE_APPLICATION_CREDENTIALS))
with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError,
expected_err_msg):
client._get_environment_variable_file()
@mock.patch.dict(os.environ, {}, clear=True)
def test_get_environment_variable_file_without_env_var(self):
self.assertIsNone(client._get_environment_variable_file())
@mock.patch('os.name', new='nt')
@mock.patch.dict(os.environ, {'APPDATA': DATA_DIR}, clear=True)
def test_get_well_known_file_on_windows(self):
well_known_file = datafile(
os.path.join(client._CLOUDSDK_CONFIG_DIRECTORY,
client._WELL_KNOWN_CREDENTIALS_FILE))
self.assertEqual(well_known_file, client._get_well_known_file())
@mock.patch('os.name', new='nt')
@mock.patch.dict(os.environ, {'SystemDrive': 'G:'}, clear=True)
def test_get_well_known_file_on_windows_without_appdata(self):
well_known_file = os.path.join('G:', '\\',
client._CLOUDSDK_CONFIG_DIRECTORY,
client._WELL_KNOWN_CREDENTIALS_FILE)
self.assertEqual(well_known_file, client._get_well_known_file())
@mock.patch.dict(os.environ,
{client._CLOUDSDK_CONFIG_ENV_VAR: 'CUSTOM_DIR'},
clear=True)
def test_get_well_known_file_with_custom_config_dir(self):
CUSTOM_DIR = os.environ[client._CLOUDSDK_CONFIG_ENV_VAR]
EXPECTED_FILE = os.path.join(CUSTOM_DIR,
client._WELL_KNOWN_CREDENTIALS_FILE)
well_known_file = client._get_well_known_file()
self.assertEqual(well_known_file, EXPECTED_FILE)
def test_get_adc_from_file_service_account(self):
credentials_file = datafile(
os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE))
credentials = client._get_application_default_credential_from_file(
credentials_file)
self.validate_service_account_credentials(credentials)
def test_save_to_well_known_file_service_account(self):
credential_file = datafile(
os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE))
credentials = client._get_application_default_credential_from_file(
credential_file)
temp_credential_file = datafile(
os.path.join('gcloud',
'temp_well_known_file_service_account.json'))
client.save_to_well_known_file(credentials, temp_credential_file)
with open(temp_credential_file) as f:
d = json.load(f)
self.assertEqual('service_account', d['type'])
self.assertEqual('123', d['client_id'])
self.assertEqual('[email protected]', d['client_email'])
self.assertEqual('ABCDEF', d['private_key_id'])
os.remove(temp_credential_file)
@mock.patch('os.path.isdir', return_value=False)
def test_save_well_known_file_with_non_existent_config_dir(self,
isdir_mock):
credential_file = datafile(
os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE))
credentials = client._get_application_default_credential_from_file(
credential_file)
with self.assertRaises(OSError):
client.save_to_well_known_file(credentials)
config_dir = os.path.join(os.path.expanduser('~'), '.config', 'gcloud')
isdir_mock.assert_called_once_with(config_dir)
def test_get_adc_from_file_authorized_user(self):
credentials_file = datafile(os.path.join(
'gcloud',
'application_default_credentials_authorized_user.json'))
credentials = client._get_application_default_credential_from_file(
credentials_file)
self.validate_google_credentials(credentials)
def test_save_to_well_known_file_authorized_user(self):
credentials_file = datafile(os.path.join(
'gcloud',
'application_default_credentials_authorized_user.json'))
credentials = client._get_application_default_credential_from_file(
credentials_file)
temp_credential_file = datafile(
os.path.join('gcloud',
'temp_well_known_file_authorized_user.json'))
client.save_to_well_known_file(credentials, temp_credential_file)
with open(temp_credential_file) as f:
d = json.load(f)
self.assertEqual('authorized_user', d['type'])
self.assertEqual('123', d['client_id'])
self.assertEqual('secret', d['client_secret'])
self.assertEqual('alabalaportocala', d['refresh_token'])
os.remove(temp_credential_file)
def test_get_application_default_credential_from_malformed_file_1(self):
credentials_file = datafile(
os.path.join('gcloud',
'application_default_credentials_malformed_1.json'))
expected_err_msg = (
"'type' field should be defined \(and have one of the '{0}' or "
"'{1}' values\)".format(client.AUTHORIZED_USER,
client.SERVICE_ACCOUNT))
with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError,
expected_err_msg):
client._get_application_default_credential_from_file(
credentials_file)
def test_get_application_default_credential_from_malformed_file_2(self):
credentials_file = datafile(
os.path.join('gcloud',
'application_default_credentials_malformed_2.json'))
expected_err_msg = (
'The following field\(s\) must be defined: private_key_id')
with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError,
expected_err_msg):
client._get_application_default_credential_from_file(
credentials_file)
def test_get_application_default_credential_from_malformed_file_3(self):
credentials_file = datafile(
os.path.join('gcloud',
'application_default_credentials_malformed_3.json'))
with self.assertRaises(ValueError):
client._get_application_default_credential_from_file(
credentials_file)
def test_raise_exception_for_missing_fields(self):
missing_fields = ['first', 'second', 'third']
expected_err_msg = ('The following field\(s\) must be defined: ' +
', '.join(missing_fields))
with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError,
expected_err_msg):
client._raise_exception_for_missing_fields(missing_fields)
def test_raise_exception_for_reading_json(self):
credential_file = 'any_file'
extra_help = ' be good'
error = client.ApplicationDefaultCredentialsError('stuff happens')
expected_err_msg = ('An error was encountered while reading '
'json file: ' + credential_file +
extra_help + ': ' + str(error))
with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError,
expected_err_msg):
client._raise_exception_for_reading_json(
credential_file, extra_help, error)
@mock.patch('oauth2client.client._in_gce_environment')
@mock.patch('oauth2client.client._in_gae_environment', return_value=False)
@mock.patch('oauth2client.client._get_environment_variable_file')
@mock.patch('oauth2client.client._get_well_known_file')
def test_get_adc_from_env_var_service_account(self, *stubs):
# Set up stubs.
get_well_known, get_env_file, in_gae, in_gce = stubs
get_env_file.return_value = datafile(
os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE))
credentials = client.GoogleCredentials.get_application_default()
self.validate_service_account_credentials(credentials)
get_env_file.assert_called_once_with()
get_well_known.assert_not_called()
in_gae.assert_not_called()
in_gce.assert_not_called()
def test_env_name(self):
self.assertEqual(None, client.SETTINGS.env_name)
self.test_get_adc_from_env_var_service_account()
self.assertEqual(client.DEFAULT_ENV_NAME, client.SETTINGS.env_name)
@mock.patch('oauth2client.client._in_gce_environment')
@mock.patch('oauth2client.client._in_gae_environment', return_value=False)
@mock.patch('oauth2client.client._get_environment_variable_file')
@mock.patch('oauth2client.client._get_well_known_file')
def test_get_adc_from_env_var_authorized_user(self, *stubs):
# Set up stubs.
get_well_known, get_env_file, in_gae, in_gce = stubs
get_env_file.return_value = datafile(os.path.join(
'gcloud',
'application_default_credentials_authorized_user.json'))
credentials = client.GoogleCredentials.get_application_default()
self.validate_google_credentials(credentials)
get_env_file.assert_called_once_with()
get_well_known.assert_not_called()
in_gae.assert_not_called()
in_gce.assert_not_called()
@mock.patch('oauth2client.client._in_gce_environment')
@mock.patch('oauth2client.client._in_gae_environment', return_value=False)
@mock.patch('oauth2client.client._get_environment_variable_file')
@mock.patch('oauth2client.client._get_well_known_file')
def test_get_adc_from_env_var_malformed_file(self, *stubs):
# Set up stubs.
get_well_known, get_env_file, in_gae, in_gce = stubs
get_env_file.return_value = datafile(
os.path.join('gcloud',
'application_default_credentials_malformed_3.json'))
expected_err = client.ApplicationDefaultCredentialsError
with self.assertRaises(expected_err) as exc_manager:
client.GoogleCredentials.get_application_default()
self.assertTrue(str(exc_manager.exception).startswith(
'An error was encountered while reading json file: ' +
get_env_file.return_value + ' (pointed to by ' +
client.GOOGLE_APPLICATION_CREDENTIALS + ' environment variable):'))
get_env_file.assert_called_once_with()
get_well_known.assert_not_called()
in_gae.assert_not_called()
in_gce.assert_not_called()
@mock.patch('oauth2client.client._in_gce_environment', return_value=False)
@mock.patch('oauth2client.client._in_gae_environment', return_value=False)
@mock.patch('oauth2client.client._get_environment_variable_file',
return_value=None)
@mock.patch('oauth2client.client._get_well_known_file',
return_value='BOGUS_FILE')
def test_get_adc_env_not_set_up(self, *stubs):
# Unpack stubs.
get_well_known, get_env_file, in_gae, in_gce = stubs
# Make sure the well-known file actually doesn't exist.
self.assertFalse(os.path.exists(get_well_known.return_value))
expected_err = client.ApplicationDefaultCredentialsError
with self.assertRaises(expected_err) as exc_manager:
client.GoogleCredentials.get_application_default()
self.assertEqual(client.ADC_HELP_MSG, str(exc_manager.exception))
get_env_file.assert_called_once_with()
get_well_known.assert_called_once_with()
in_gae.assert_called_once_with()
in_gce.assert_called_once_with()
@mock.patch('oauth2client.client._in_gce_environment', return_value=False)
@mock.patch('oauth2client.client._in_gae_environment', return_value=False)
@mock.patch('oauth2client.client._get_environment_variable_file',
return_value=None)
@mock.patch('oauth2client.client._get_well_known_file')
def test_get_adc_env_from_well_known(self, *stubs):
# Unpack stubs.
get_well_known, get_env_file, in_gae, in_gce = stubs
# Make sure the well-known file is an actual file.
get_well_known.return_value = __file__
# Make sure the well-known file actually doesn't exist.
self.assertTrue(os.path.exists(get_well_known.return_value))
method_name = (
'oauth2client.client.'
'_get_application_default_credential_from_file')
result_creds = object()
with mock.patch(method_name,
return_value=result_creds) as get_from_file:
result = client.GoogleCredentials.get_application_default()
self.assertEqual(result, result_creds)
get_from_file.assert_called_once_with(__file__)
get_env_file.assert_called_once_with()
get_well_known.assert_called_once_with()
in_gae.assert_not_called()
in_gce.assert_not_called()
def test_from_stream_service_account(self):
credentials_file = datafile(
os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE))
credentials = self.get_a_google_credentials_object().from_stream(
credentials_file)
self.validate_service_account_credentials(credentials)
def test_from_stream_authorized_user(self):
credentials_file = datafile(os.path.join(
'gcloud',
'application_default_credentials_authorized_user.json'))
credentials = self.get_a_google_credentials_object().from_stream(
credentials_file)
self.validate_google_credentials(credentials)
def test_from_stream_missing_file(self):
credentials_filename = None
expected_err_msg = (r'The parameter passed to the from_stream\(\) '
r'method should point to a file.')
with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError,
expected_err_msg):
self.get_a_google_credentials_object().from_stream(
credentials_filename)
def test_from_stream_malformed_file_1(self):
credentials_file = datafile(
os.path.join('gcloud',
'application_default_credentials_malformed_1.json'))
expected_err_msg = (
'An error was encountered while reading json file: ' +
credentials_file +
' \(provided as parameter to the from_stream\(\) method\): ' +
"'type' field should be defined \(and have one of the '" +
client.AUTHORIZED_USER + "' or '" + client.SERVICE_ACCOUNT +
"' values\)")
with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError,
expected_err_msg):
self.get_a_google_credentials_object().from_stream(
credentials_file)
def test_from_stream_malformed_file_2(self):
credentials_file = datafile(
os.path.join('gcloud',
'application_default_credentials_malformed_2.json'))
expected_err_msg = (
'An error was encountered while reading json file: ' +
credentials_file +
' \(provided as parameter to the from_stream\(\) method\): '
'The following field\(s\) must be defined: '
'private_key_id')
with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError,
expected_err_msg):
self.get_a_google_credentials_object().from_stream(
credentials_file)
def test_from_stream_malformed_file_3(self):
credentials_file = datafile(
os.path.join('gcloud',
'application_default_credentials_malformed_3.json'))
with self.assertRaises(client.ApplicationDefaultCredentialsError):
self.get_a_google_credentials_object().from_stream(
credentials_file)
def test_to_from_json_authorized_user(self):
filename = 'application_default_credentials_authorized_user.json'
credentials_file = datafile(os.path.join('gcloud', filename))
creds = client.GoogleCredentials.from_stream(credentials_file)
json = creds.to_json()
creds2 = client.GoogleCredentials.from_json(json)
self.assertEqual(creds.__dict__, creds2.__dict__)
def test_to_from_json_service_account(self):
credentials_file = datafile(
os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE))
creds1 = client.GoogleCredentials.from_stream(credentials_file)
# Convert to and then back from json.
creds2 = client.GoogleCredentials.from_json(creds1.to_json())
creds1_vals = creds1.__dict__
creds1_vals.pop('_signer')
creds2_vals = creds2.__dict__
creds2_vals.pop('_signer')
self.assertEqual(creds1_vals, creds2_vals)
def test_to_from_json_service_account_scoped(self):
credentials_file = datafile(
os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE))
creds1 = client.GoogleCredentials.from_stream(credentials_file)
creds1 = creds1.create_scoped(['dummy_scope'])
# Convert to and then back from json.
creds2 = client.GoogleCredentials.from_json(creds1.to_json())
creds1_vals = creds1.__dict__
creds1_vals.pop('_signer')
creds2_vals = creds2.__dict__
creds2_vals.pop('_signer')
self.assertEqual(creds1_vals, creds2_vals)
def test_parse_expiry(self):
dt = datetime.datetime(2016, 1, 1)
parsed_expiry = client._parse_expiry(dt)
self.assertEqual('2016-01-01T00:00:00Z', parsed_expiry)
def test_bad_expiry(self):
dt = object()
parsed_expiry = client._parse_expiry(dt)
self.assertEqual(None, parsed_expiry)
class DummyDeleteStorage(client.Storage):
delete_called = False
def locked_delete(self):
self.delete_called = True
def _token_revoke_test_helper(testcase, revoke_raise, valid_bool_value,
token_attr, http_mock):
current_store = getattr(testcase.credentials, 'store', None)
dummy_store = DummyDeleteStorage()
testcase.credentials.set_store(dummy_store)
actual_do_revoke = testcase.credentials._do_revoke
testcase.token_from_revoke = None
def do_revoke_stub(http, token):
testcase.token_from_revoke = token
return actual_do_revoke(http, token)
testcase.credentials._do_revoke = do_revoke_stub
if revoke_raise:
testcase.assertRaises(client.TokenRevokeError,
testcase.credentials.revoke, http_mock)
else:
testcase.credentials.revoke(http_mock)
testcase.assertEqual(getattr(testcase.credentials, token_attr),
testcase.token_from_revoke)
testcase.assertEqual(valid_bool_value, testcase.credentials.invalid)
testcase.assertEqual(valid_bool_value, dummy_store.delete_called)
testcase.credentials.set_store(current_store)
class BasicCredentialsTests(unittest.TestCase):
def setUp(self):
access_token = 'foo'
client_id = 'some_client_id'
client_secret = 'cOuDdkfjxxnv+'
refresh_token = '1/0/a.df219fjls0'
token_expiry = datetime.datetime.utcnow()
user_agent = 'refresh_checker/1.0'
self.credentials = client.OAuth2Credentials(
access_token, client_id, client_secret,
refresh_token, token_expiry, oauth2client.GOOGLE_TOKEN_URI,
user_agent, revoke_uri=oauth2client.GOOGLE_REVOKE_URI,
scopes='foo', token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI)
# Provoke a failure if @_helpers.positional is not respected.
self.old_positional_enforcement = (
_helpers.positional_parameters_enforcement)
_helpers.positional_parameters_enforcement = (
_helpers.POSITIONAL_EXCEPTION)
def tearDown(self):
_helpers.positional_parameters_enforcement = (
self.old_positional_enforcement)
def test_token_refresh_success(self):
for status_code in client.REFRESH_STATUS_CODES:
token_response = {'access_token': '1/3w', 'expires_in': 3600}
json_resp = json.dumps(token_response).encode('utf-8')
http = http_mock.HttpMockSequence([
({'status': status_code}, b''),
({'status': http_client.OK}, json_resp),
({'status': http_client.OK}, 'echo_request_headers'),
])
http = self.credentials.authorize(http)
resp, content = transport.request(http, 'http://example.com')
self.assertEqual(b'Bearer 1/3w', content[b'Authorization'])
self.assertFalse(self.credentials.access_token_expired)
self.assertEqual(token_response, self.credentials.token_response)
def test_recursive_authorize(self):
# Tests that OAuth2Credentials doesn't introduce new method
# constraints. Formerly, OAuth2Credentials.authorize monkeypatched the
# request method of the passed in HTTP object with a wrapper annotated
# with @_helpers.positional(1). Since the original method has no such
# annotation, that meant that the wrapper was violating the contract of
# the original method by adding a new requirement to it. And in fact
# the wrapper itself doesn't even respect that requirement. So before
# the removal of the annotation, this test would fail.
token_response = {'access_token': '1/3w', 'expires_in': 3600}
encoded_response = json.dumps(token_response).encode('utf-8')
http = http_mock.HttpMock(data=encoded_response)
http = self.credentials.authorize(http)
http = self.credentials.authorize(http)
transport.request(http, 'http://example.com')
def test_token_refresh_failure(self):
for status_code in client.REFRESH_STATUS_CODES:
http = http_mock.HttpMockSequence([
({'status': status_code}, b''),
({'status': http_client.BAD_REQUEST},
b'{"error":"access_denied"}'),
])
http = self.credentials.authorize(http)
with self.assertRaises(
client.HttpAccessTokenRefreshError) as exc_manager:
transport.request(http, 'http://example.com')
self.assertEqual(http_client.BAD_REQUEST,
exc_manager.exception.status)
self.assertTrue(self.credentials.access_token_expired)
self.assertEqual(None, self.credentials.token_response)
def test_token_revoke_success(self):
http = http_mock.HttpMock(headers={'status': http_client.OK})
_token_revoke_test_helper(
self, revoke_raise=False, valid_bool_value=True,
token_attr='refresh_token', http_mock=http)
def test_token_revoke_failure(self):
http = http_mock.HttpMock(headers={'status': http_client.BAD_REQUEST})
_token_revoke_test_helper(
self, revoke_raise=True, valid_bool_value=False,
token_attr='refresh_token', http_mock=http)
def test_token_revoke_fallback(self):
original_credentials = self.credentials.to_json()
self.credentials.refresh_token = None
http = http_mock.HttpMock(headers={'status': http_client.OK})
_token_revoke_test_helper(
self, revoke_raise=False, valid_bool_value=True,
token_attr='access_token', http_mock=http)
self.credentials = self.credentials.from_json(original_credentials)
def test_token_revoke_405(self):
original_credentials = self.credentials.to_json()
self.credentials.refresh_token = None
http = http_mock.HttpMockSequence([
({'status': http_client.METHOD_NOT_ALLOWED}, b''),
({'status': http_client.OK}, b''),
])
_token_revoke_test_helper(
self, revoke_raise=False, valid_bool_value=True,
token_attr='access_token', http_mock=http)
self.credentials = self.credentials.from_json(original_credentials)
def test_non_401_error_response(self):
http = http_mock.HttpMock(headers={'status': http_client.BAD_REQUEST})
http = self.credentials.authorize(http)
resp, content = transport.request(http, 'http://example.com')
self.assertEqual(http_client.BAD_REQUEST, resp.status)
self.assertEqual(None, self.credentials.token_response)
def test_to_from_json(self):
json = self.credentials.to_json()
instance = client.OAuth2Credentials.from_json(json)
self.assertEqual(client.OAuth2Credentials, type(instance))
instance.token_expiry = None
self.credentials.token_expiry = None
self.assertEqual(instance.__dict__, self.credentials.__dict__)
def test_from_json_token_expiry(self):
data = json.loads(self.credentials.to_json())
data['token_expiry'] = None
instance = client.OAuth2Credentials.from_json(json.dumps(data))
self.assertIsInstance(instance, client.OAuth2Credentials)
def test_from_json_bad_token_expiry(self):
data = json.loads(self.credentials.to_json())
data['token_expiry'] = 'foobar'
instance = client.OAuth2Credentials.from_json(json.dumps(data))
self.assertIsInstance(instance, client.OAuth2Credentials)
def test_unicode_header_checks(self):
access_token = u'foo'
client_id = u'some_client_id'
client_secret = u'cOuDdkfjxxnv+'
refresh_token = u'1/0/a.df219fjls0'
token_expiry = str(datetime.datetime.utcnow())
token_uri = str(oauth2client.GOOGLE_TOKEN_URI)
revoke_uri = str(oauth2client.GOOGLE_REVOKE_URI)
user_agent = u'refresh_checker/1.0'
credentials = client.OAuth2Credentials(
access_token, client_id, client_secret, refresh_token,
token_expiry, token_uri, user_agent, revoke_uri=revoke_uri)
# First, test that we correctly encode basic objects, making sure
# to include a bytes object. Note that oauth2client will normalize