forked from googleads/google-ads-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_test.py
More file actions
1006 lines (827 loc) · 40.5 KB
/
client_test.py
File metadata and controls
1006 lines (827 loc) · 40.5 KB
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 2018 Google LLC
#
# 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
#
# https://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 for the Google Ads API client library."""
import os
import mock
import yaml
import json
import logging
from unittest import TestCase
from importlib import import_module
import grpc
from pyfakefs.fake_filesystem_unittest import TestCase as FileTestCase
from google.ads.google_ads import client as Client
from google.ads.google_ads.errors import GoogleAdsException
latest_version = Client._DEFAULT_VERSION
valid_versions = Client._VALID_API_VERSIONS
errors = import_module('google.ads.google_ads.%s.proto.errors' % latest_version)
error_protos = errors.errors_pb2
services = import_module('google.ads.google_ads.%s.proto.services' %
latest_version)
google_ads_service_pb2 = services.google_ads_service_pb2
class ModuleLevelTest(TestCase):
def test_parse_metadata_to_json(self):
mock_metadata = [
('x-goog-api-client',
'gl-python/123 grpc/123 gax/123'),
('developer-token', '0000000000'),
('login-customer-id', '9999999999')]
result = (Client._parse_metadata_to_json(mock_metadata))
self.assertEqual(result, '{\n'
' "developer-token": "REDACTED",\n'
' "login-customer-id": "9999999999",\n'
' "x-goog-api-client": "gl-python/123 '
'grpc/123 gax/123"\n'
'}')
def test_parse_metadata_to_json_with_none(self):
mock_metadata = None
result = (Client._parse_metadata_to_json(mock_metadata))
self.assertEqual(result, '{}')
def test_get_request_id_from_metadata(self):
"""Ensures request-id is retrieved from metadata tuple."""
mock_metadata = (('request-id', '123456'),)
result = (Client._get_request_id_from_metadata(mock_metadata))
self.assertEqual(result, '123456')
def test_get_request_id_no_id(self):
"""Ensures None is returned if metadata does't contain a request ID."""
mock_metadata = (('another-key', 'another-val'),)
result = (Client._get_request_id_from_metadata(mock_metadata))
self.assertEqual(result, None)
class GoogleAdsClientTest(FileTestCase):
"""Tests for the google.ads.googleads.client.GoogleAdsClient class."""
def _create_test_client(self, endpoint=None):
with mock.patch(
'google.ads.google_ads.client.Credentials') as mock_credentials:
mock_credentials_instance = mock_credentials.return_value
mock_credentials_instance.refresh_token = self.refresh_token
mock_credentials_instance.client_id = self.client_id
mock_credentials_instance.client_secret = self.client_secret
client = Client.GoogleAdsClient(mock_credentials_instance,
self.developer_token, endpoint=endpoint)
return client
def setUp(self):
self.setUpPyfakefs()
self.developer_token = 'abc123'
self.client_id = 'client_id_123456789'
self.client_secret = 'client_secret_987654321'
self.refresh_token = 'refresh'
self.login_customer_id = '1234567890'
def test_load_from_storage_login_customer_id(self):
config = {
'developer_token': self.developer_token,
'client_id': self.client_id,
'client_secret': self.client_secret,
'refresh_token': self.refresh_token,
'login_customer_id': self.login_customer_id
}
file_path = os.path.join(os.path.expanduser('~'), 'google-ads.yaml')
self.fs.create_file(file_path, contents=yaml.safe_dump(config))
with mock.patch('google.ads.google_ads.client.GoogleAdsClient'
'.__init__') as mock_client_init, \
mock.patch(
'google.ads.google_ads.client.Credentials') as mock_credentials:
mock_client_init.return_value = None
mock_credentials_instance = mock.Mock()
mock_credentials.return_value = mock_credentials_instance
Client.GoogleAdsClient.load_from_storage()
mock_client_init.assert_called_once_with(
credentials=mock_credentials_instance,
developer_token=self.developer_token,
endpoint=None,
login_customer_id=self.login_customer_id,
logging_config=None)
def test_load_from_storage_login_customer_id_as_None(self):
config = {
'developer_token': self.developer_token,
'client_id': self.client_id,
'client_secret': self.client_secret,
'refresh_token': self.refresh_token,
'login_customer_id': None
}
file_path = os.path.join(os.path.expanduser('~'), 'google-ads.yaml')
self.fs.create_file(file_path, contents=yaml.safe_dump(config))
with mock.patch('google.ads.google_ads.client.GoogleAdsClient'
'.__init__') as mock_client_init, \
mock.patch(
'google.ads.google_ads.client.Credentials') as mock_credentials:
mock_client_init.return_value = None
mock_credentials_instance = mock.Mock()
mock_credentials.return_value = mock_credentials_instance
Client.GoogleAdsClient.load_from_storage()
mock_client_init.assert_called_once_with(
credentials=mock_credentials_instance,
developer_token=self.developer_token,
endpoint=None,
login_customer_id=None,
logging_config=None)
def test_load_from_storage_invalid_login_customer_id(self):
config = {
'developer_token': self.developer_token,
'client_id': self.client_id,
'client_secret': self.client_secret,
'refresh_token': self.refresh_token,
'login_customer_id': '123-456-7890'
}
file_path = os.path.join(os.path.expanduser('~'), 'google-ads.yaml')
self.fs.create_file(file_path, contents=yaml.safe_dump(config))
with mock.patch(
'google.ads.google_ads.client.Credentials') as mock_credentials:
mock_credentials_instance = mock.Mock()
mock_credentials.return_value = mock_credentials_instance
self.assertRaises(
ValueError,
Client.GoogleAdsClient
.load_from_storage)
def test_load_from_storage_too_short_login_customer_id(self):
config = {
'developer_token': self.developer_token,
'client_id': self.client_id,
'client_secret': self.client_secret,
'refresh_token': self.refresh_token,
'login_customer_id': '123'
}
file_path = os.path.join(os.path.expanduser('~'), 'google-ads.yaml')
self.fs.create_file(file_path, contents=yaml.safe_dump(config))
with mock.patch(
'google.ads.google_ads.client.Credentials') as mock_credentials:
mock_credentials_instance = mock.Mock()
mock_credentials.return_value = mock_credentials_instance
self.assertRaises(
ValueError,
Client.GoogleAdsClient
.load_from_storage)
def test_load_from_storage(self):
config = {
'developer_token': self.developer_token,
'client_id': self.client_id,
'client_secret': self.client_secret,
'refresh_token': self.refresh_token
}
file_path = os.path.join(os.path.expanduser('~'), 'google-ads.yaml')
self.fs.create_file(file_path, contents=yaml.safe_dump(config))
with mock.patch('google.ads.google_ads.client.GoogleAdsClient'
'.__init__') as mock_client_init, \
mock.patch(
'google.ads.google_ads.client.Credentials') as mock_credentials:
mock_client_init.return_value = None
mock_credentials_instance = mock.Mock()
mock_credentials.return_value = mock_credentials_instance
Client.GoogleAdsClient.load_from_storage()
mock_client_init.assert_called_once_with(
credentials=mock_credentials_instance,
developer_token=self.developer_token,
endpoint=None,
login_customer_id=None,
logging_config=None)
def test_load_from_storage_custom_endpoint(self):
endpoint = 'alt.endpoint.com'
config = {
'developer_token': self.developer_token,
'client_id': self.client_id,
'client_secret': self.client_secret,
'refresh_token': self.refresh_token,
'endpoint': endpoint
}
file_path = os.path.join(os.path.expanduser('~'), 'google-ads.yaml')
self.fs.create_file(file_path, contents=yaml.safe_dump(config))
with mock.patch('google.ads.google_ads.client.GoogleAdsClient'
'.__init__') as mock_client_init, \
mock.patch(
'google.ads.google_ads.client.Credentials') as mock_credentials:
mock_client_init.return_value = None
mock_credentials_instance = mock.Mock()
mock_credentials.return_value = mock_credentials_instance
Client.GoogleAdsClient.load_from_storage()
mock_client_init.assert_called_once_with(
credentials=mock_credentials_instance,
developer_token=self.developer_token,
endpoint=endpoint,
login_customer_id=None,
logging_config=None)
def test_load_from_storage_custom_path(self):
config = {
'developer_token': self.developer_token,
'client_id': self.client_id,
'client_secret': self.client_secret,
'refresh_token': self.refresh_token
}
file_path = 'test/google-ads.yaml'
self.fs.create_file(file_path, contents=yaml.safe_dump(config))
with mock.patch('google.ads.google_ads.client.GoogleAdsClient'
'.__init__') as mock_client_init, \
mock.patch(
'google.ads.google_ads.client.Credentials') as mock_credentials:
mock_client_init.return_value = None
mock_credentials_instance = mock.Mock()
mock_credentials.return_value = mock_credentials_instance
Client.GoogleAdsClient.load_from_storage(path=file_path)
mock_client_init.assert_called_once_with(
credentials=mock_credentials_instance,
developer_token=self.developer_token,
endpoint=None,
login_customer_id=None,
logging_config=None)
def test_load_from_storage_file_not_found(self):
wrong_file_path = 'test/wrong-google-ads.yaml'
self.assertRaises(
IOError,
Client.GoogleAdsClient.load_from_storage,
path=wrong_file_path)
def test_load_from_storage_required_config_missing(self):
config = {
'client_id': self.client_id,
'client_secret': self.client_secret,
'refresh_token': self.refresh_token
}
file_path = 'test/google-ads.yaml'
self.fs.create_file(file_path, contents=yaml.safe_dump(config))
self.assertRaises(
ValueError,
Client.GoogleAdsClient.load_from_storage,
path=file_path)
def test_get_service(self):
# Retrieve service names for all defined service clients.
for ver in valid_versions:
services_path = 'google.ads.google_ads.%s' % ver
service_names = [
'%s%s' % (name.rsplit('ServiceClient')[0], 'Service')
for name in dir(import_module(services_path))
if 'ServiceClient' in name]
client = self._create_test_client()
# Iterate through retrieval of all service clients by name.
for service_name in service_names:
client.get_service(service_name)
def test_get_service_custom_endpoint(self):
service_name = 'GoogleAdsService'
service_module_base = 'google_ads_service'
grpc_transport_class_name = '%sGrpcTransport' % service_name
grpc_transport_module_name = '%s_grpc_transport' % service_module_base
transport_create_channel_path = (
'google.ads.google_ads.%s.services.transports.%s.%s.create_channel'
% (Client._DEFAULT_VERSION,
grpc_transport_module_name,
grpc_transport_class_name))
endpoint = 'alt.endpoint.com'
client = self._create_test_client(endpoint=endpoint)
# The GRPC transport's create_channel method is what allows the
# GoogleAdsClient to specify a custom endpoint. Here we mock the
# create_channel method in order to verify that it was given the
# endpoint specified by the client.
with mock.patch(transport_create_channel_path) as mock_create_channel:
# A new channel is created during initialization of the service
# client.
client.get_service(service_name)
mock_create_channel.assert_called_once_with(
address=endpoint, credentials=client.credentials)
def test_get_service_not_found(self):
client = self._create_test_client()
self.assertRaises(ValueError, client.get_service, 'BadService')
def test_get_service_invalid_version(self):
client = self._create_test_client()
self.assertRaises(ValueError, client.get_service, 'GoogleAdsService',
version='bad_version')
def test_get_service_with_version(self):
client = self._create_test_client()
try:
client.get_service('GoogleAdsService', version=latest_version)
except Exception:
self.fail('get_service with a valid version raised an error')
def test_get_type(self):
for ver in valid_versions:
# Retrieve names for all types defined in pb2 files.
type_path = 'google.ads.google_ads.%s.types' % ver
type_names = import_module(type_path).names
# Iterate through retrieval of all types by name.
for name in type_names:
Client.GoogleAdsClient.get_type(
name, version=ver)
def test_get_type_not_found(self):
self.assertRaises(
ValueError, Client.GoogleAdsClient.get_type,
'BadType')
def test_get_type_invalid_version(self):
self.assertRaises(
ValueError, Client.GoogleAdsClient.get_type,
'GoogleAdsFailure', version='bad_version')
class MetadataInterceptorTest(TestCase):
def setUp(self):
self.mock_developer_token = '1234567890'
self.mock_login_customer_id = '0987654321'
def test_init(self):
interceptor = Client.MetadataInterceptor(
self.mock_developer_token,
self.mock_login_customer_id)
self.assertEqual(
interceptor.developer_token_meta,
('developer-token', self.mock_developer_token))
self.assertEqual(
interceptor.login_customer_id_meta,
('login-customer-id', self.mock_login_customer_id)
)
def test_init_no_login_customer_id(self):
interceptor = Client.MetadataInterceptor(
self.mock_developer_token,
None)
self.assertEqual(
interceptor.developer_token_meta,
('developer-token', self.mock_developer_token))
self.assertEqual(
interceptor.login_customer_id_meta,
None
)
def test_update_client_call_details_metadata(self):
interceptor = Client.MetadataInterceptor(
self.mock_developer_token,
self.mock_login_customer_id)
mock_metadata = list([('test-key', 'test-value')])
mock_client_call_details = mock.Mock()
client_call_details = interceptor._update_client_call_details_metadata(
mock_client_call_details, mock_metadata)
self.assertEqual(client_call_details.metadata, mock_metadata)
def test_intercept_unary_unary(self):
interceptor = Client.MetadataInterceptor(
self.mock_developer_token,
self.mock_login_customer_id)
mock_continuation = mock.Mock(return_value=None)
mock_client_call_details = mock.Mock()
mock_client_call_details.method = 'test/method'
mock_client_call_details.timeout = 5
mock_client_call_details.metadata = [('apples', 'oranges')]
mock_request = mock.Mock()
with mock.patch.object(
interceptor,
'_update_client_call_details_metadata',
wraps=interceptor._update_client_call_details_metadata
) as mock_updater:
interceptor.intercept_unary_unary(
mock_continuation,
mock_client_call_details,
mock_request)
mock_updater.assert_called_once_with(
mock_client_call_details, [mock_client_call_details.metadata[0],
interceptor.developer_token_meta,
interceptor.login_customer_id_meta])
mock_continuation.assert_called_once()
class LoggingInterceptorTest(TestCase):
"""Tests for the google.ads.googleads.client.LoggingInterceptor class."""
_MOCK_CONFIG = {'test': True}
_MOCK_ENDPOINT = 'www.test-endpoint.com'
_MOCK_INITIAL_METADATA = [('developer-token', '123456'),
('header', 'value')]
_MOCK_CUSTOMER_ID = '123456'
_MOCK_REQUEST_ID = '654321xyz'
_MOCK_METHOD = 'test/method'
_MOCK_TRAILING_METADATA = (('request-id', _MOCK_REQUEST_ID),)
_MOCK_TRANSPORT_ERROR_METADATA = tuple()
_MOCK_ERROR_MESSAGE = 'Test error message'
_MOCK_TRANSPORT_ERROR_MESSAGE = u'Received RST_STREAM with error code 2'
_MOCK_DEBUG_ERROR_STRING = u'{"description":"Error received from peer"}'
_MOCK_RESPONSE_MSG = 'test response msg'
_MOCK_EXCEPTION = mock.Mock()
_MOCK_ERROR = mock.Mock()
_MOCK_FAILURE = mock.Mock()
def _create_test_interceptor(self, config=_MOCK_CONFIG,
endpoint=_MOCK_ENDPOINT):
"""Creates a LoggingInterceptor instance.
Accepts parameters that are used to override defaults when needed
for testing.
Returns:
A LoggingInterceptor instance.
Args:
config: A dict configuration
endpoint: A str representing an endpoint
"""
return Client.LoggingInterceptor(config, endpoint)
def _get_mock_client_call_details(self):
"""Generates a mock client_call_details object for use in tests.
Returns:
A Mock instance with "method" and "metadata" attributes.
"""
mock_client_call_details = mock.Mock()
mock_client_call_details.method = self._MOCK_METHOD
mock_client_call_details.metadata = self._MOCK_INITIAL_METADATA
return mock_client_call_details
def _get_mock_request(self):
"""Generates a mock request object for use in tests.
Returns:
A Mock instance with a "customer_id" attribute.
"""
mock_request = mock.Mock()
mock_request.customer_id = self._MOCK_CUSTOMER_ID
return mock_request
def _get_trailing_metadata_fn(self):
"""Generates a mock trailing_metadata function used for testing.
Returns:
A function that returns a tuple of mock metadata.
"""
def mock_trailing_metadata_fn():
return self._MOCK_TRAILING_METADATA
return mock_trailing_metadata_fn
def _get_mock_exception(self):
"""Generates a mock GoogleAdsException exception instance for testing.
Returns:
A Mock instance with the following attributes - "message",
"request_id", "failure", and "error." The "failure" attribute has an
"error" attribute that is an array of mock error objects, and the
"error" attribute is an object with a "trailing_metadata" method
that returns a tuble of mock metadata.
"""
exception = self._MOCK_EXCEPTION
error = self._MOCK_ERROR
error.message = self._MOCK_ERROR_MESSAGE
exception.request_id = self._MOCK_REQUEST_ID
exception.failure = self._MOCK_FAILURE
exception.failure.errors = [error]
exception.error = self._MOCK_ERROR
exception.error.trailing_metadata = self._get_trailing_metadata_fn()
return exception
def _get_mock_transport_exception(self):
"""Generates a mock gRPC transport error.
Specifically an error not generated by the Google Ads API and that
is not an instance of GoogleAdsException.
Returns:
A Mock instance with mock "debug_error_string," "details," and
"trailing_metadata" methods.
"""
def _mock_debug_error_string():
return self._MOCK_DEBUG_ERROR_STRING
def _mock_details():
return self._MOCK_TRANSPORT_ERROR_MESSAGE
def _mock_trailing_metadata():
return self._MOCK_TRANSPORT_ERROR_METADATA
exception = mock.Mock()
exception.debug_error_string = _mock_debug_error_string
exception.details = _mock_details
exception.trailing_metadata = _mock_trailing_metadata
# These attributes are explicitly deleted because they will otherwise
# get mocked automatically and not generate AttributeErrors that trigger
# default values in certain helper methods.
del exception.error
del exception.failure
del exception.request_id
return exception
def _get_mock_response(self, failed=False):
"""Generates a mock response object for use in tests.
Accepts a "failed" param that tells the returned mocked response to
mimic a failed response.
Returns:
A Mock instance with mock "exception" and "trailing_metadata"
methods
Args:
failed: a bool indicating whether the mock response should be in a
failed state or not. Default is False.
"""
def mock_exception_fn():
if failed:
return self._get_mock_exception()
return None
def mock_result_fn():
return self._MOCK_RESPONSE_MSG
mock_response = mock.Mock()
mock_response.exception = mock_exception_fn
mock_response.trailing_metadata = self._get_trailing_metadata_fn()
mock_response.result = mock_result_fn
return mock_response
def _get_mock_continuation_fn(self, fail=False):
"""Generates a mock continuation function for use in tests.
Accepts a "failed" param that tell the function to return a failed
mock response or not.
Returns:
A function that returns a mock response object.
Args:
failed: a bool indicating whether the function should return a
response that mocks a failure.
"""
def mock_continuation_fn(client_call_details, request):
mock_response = self._get_mock_response(fail)
return mock_response
return mock_continuation_fn
def test_init_no_config(self):
"""Unconfigured LoggingInterceptor should not call logging.dictConfig.
"""
with mock.patch('logging.config.dictConfig') as mock_dictConfig:
Client.LoggingInterceptor()
mock_dictConfig.assert_not_called()
def test_init_with_config(self):
"""Configured LoggingInterceptor should call logging.dictConfig.
"""
config = {'test': True}
with mock.patch('logging.config.dictConfig') as mock_dictConfig:
Client.LoggingInterceptor(config)
mock_dictConfig.assert_called_once_with(config)
def test_intercept_unary_unary_unconfigured(self):
"""No _logger methods should be called.
When intercepting requests, no logging methods should be called if
LoggingInterceptor was initialized without a configuration.
"""
mock_client_call_details = self._get_mock_client_call_details()
mock_continuation_fn = self._get_mock_continuation_fn()
mock_request = self._get_mock_request()
# Since logging configuration is global it needs to be reset here
# so that state from previous tests does not affect these assertions
logging.disable(logging.CRITICAL)
logger_spy = mock.Mock(wraps=Client._logger)
interceptor = Client.LoggingInterceptor()
interceptor.intercept_unary_unary(
mock_continuation_fn,
mock_client_call_details,
mock_request)
logger_spy.debug.assert_not_called()
logger_spy.info.assert_not_called()
logger_spy.warning.assert_not_called()
def test_intercept_unary_unary_successful_request(self):
"""_logger.info and _logger.debug should be called.
LoggingInterceptor should call _logger.info and _logger.debug with
a specific str parameter when a request succeeds.
"""
mock_client_call_details = self._get_mock_client_call_details()
mock_continuation_fn = self._get_mock_continuation_fn()
mock_request = self._get_mock_request()
mock_response = mock_continuation_fn(
mock_client_call_details, mock_request)
mock_trailing_metadata = mock_response.trailing_metadata()
with mock.patch('logging.config.dictConfig'), \
mock.patch('google.ads.google_ads.client._logger') as mock_logger:
interceptor = self._create_test_interceptor()
interceptor.intercept_unary_unary(
mock_continuation_fn,
mock_client_call_details,
mock_request)
mock_logger.info.assert_called_once_with(
interceptor._SUMMARY_LOG_LINE.format(
self._MOCK_CUSTOMER_ID, self._MOCK_ENDPOINT,
mock_client_call_details.method, self._MOCK_REQUEST_ID,
False, None))
initial_metadata = Client._parse_metadata_to_json(
mock_client_call_details.metadata)
trailing_metadata = Client._parse_metadata_to_json(
mock_trailing_metadata)
mock_logger.debug.assert_called_once_with(
interceptor._FULL_REQUEST_LOG_LINE.format(
self._MOCK_METHOD, self._MOCK_ENDPOINT, initial_metadata,
mock_request, trailing_metadata, mock_response.result()))
def test_intercept_unary_unary_failed_request(self):
"""_logger.warning and _logger.info should be called.
LoggingInterceptor should call _logger.warning and _logger.info with
a specific str parameter when a request fails.
"""
mock_client_call_details = self._get_mock_client_call_details()
mock_continuation_fn = self._get_mock_continuation_fn(fail=True)
mock_request = self._get_mock_request()
with mock.patch('logging.config.dictConfig'), \
mock.patch('google.ads.google_ads.client._logger') as mock_logger:
interceptor = self._create_test_interceptor()
mock_response = interceptor.intercept_unary_unary(
mock_continuation_fn,
mock_client_call_details,
mock_request)
mock_trailing_metadata = mock_response.trailing_metadata()
mock_logger.warning.assert_called_once_with(
interceptor._SUMMARY_LOG_LINE.format(
self._MOCK_CUSTOMER_ID, self._MOCK_ENDPOINT,
mock_client_call_details.method, self._MOCK_REQUEST_ID,
True, self._MOCK_ERROR_MESSAGE))
initial_metadata = Client._parse_metadata_to_json(
mock_client_call_details.metadata)
trailing_metadata = Client._parse_metadata_to_json(
mock_trailing_metadata)
mock_logger.info.assert_called_once_with(
interceptor._FULL_FAULT_LOG_LINE.format(
self._MOCK_METHOD, self._MOCK_ENDPOINT, initial_metadata,
mock_request, trailing_metadata,
mock_response.exception().failure))
def test_get_initial_metadata(self):
"""_Returns a tuple of metadata from client_call_details."""
with mock.patch('logging.config.dictConfig'):
mock_client_call_details = mock.Mock()
mock_client_call_details.metadata = self._MOCK_INITIAL_METADATA
interceptor = self._create_test_interceptor()
result = interceptor._get_initial_metadata(mock_client_call_details)
self.assertEqual(result, self._MOCK_INITIAL_METADATA)
def test_get_initial_metadata_none(self):
"""Returns an empty tuple if initial_metadata isn't present."""
with mock.patch('logging.config.dictConfig'):
mock_client_call_details = {}
interceptor = self._create_test_interceptor()
result = interceptor._get_initial_metadata(mock_client_call_details)
self.assertEqual(result, self._MOCK_TRANSPORT_ERROR_METADATA)
def test_get_call_method(self):
"""Returns a str of the call method from client_call_details"""
with mock.patch('logging.config.dictConfig'):
mock_client_call_details = mock.Mock()
mock_client_call_details.method = self._MOCK_METHOD
interceptor = self._create_test_interceptor()
result = interceptor._get_call_method(mock_client_call_details)
self.assertEqual(result, self._MOCK_METHOD)
def test_get_call_method_none(self):
"""Returns None if method is not present on client_call_details."""
with mock.patch('logging.config.dictConfig'):
mock_client_call_details = {}
interceptor = self._create_test_interceptor()
result = interceptor._get_call_method(mock_client_call_details)
self.assertEqual(result, None)
def test_parse_exception_to_str_transport_failure(self):
""" Calls _format_json_object with error obj's debug_error_string."""
with mock.patch('logging.config.dictConfig'), \
mock.patch(
'google.ads.google_ads.client._format_json_object'
) as mock_parser:
mock_exception = self._get_mock_transport_exception()
interceptor = self._create_test_interceptor()
interceptor._parse_exception_to_str(mock_exception)
mock_parser.assert_called_once_with(
json.loads(self._MOCK_DEBUG_ERROR_STRING))
def test_parse_exception_to_str_unknown_failure(self):
"""Returns an empty JSON string if nothing can be parsed to JSON."""
with mock.patch('logging.config.dictConfig'):
mock_exception = mock.Mock()
del mock_exception.failure
del mock_exception.debug_error_string
interceptor = self._create_test_interceptor()
result = interceptor._parse_exception_to_str(mock_exception)
self.assertEqual(result, '{}')
def test_get_trailing_metadata(self):
"""Retrieves metadata from a response object."""
with mock.patch('logging.config.dictConfig'):
mock_response = self._get_mock_response()
interceptor = self._create_test_interceptor()
result = interceptor._get_trailing_metadata(mock_response)
self.assertEqual(result, self._MOCK_TRAILING_METADATA)
def test_get_trailing_metadata_google_ads_failure(self):
"""Retrieves metadata from a failed response."""
with mock.patch('logging.config.dictConfig'):
mock_response = self._get_mock_response(failed=True)
del mock_response.trailing_metadata
interceptor = self._create_test_interceptor()
result = interceptor._get_trailing_metadata(mock_response)
self.assertEqual(result, self._MOCK_TRAILING_METADATA)
def test_get_trailing_metadata_transport_failure(self):
"""Retrieves metadata from a transport error."""
with mock.patch('logging.config.dictConfig'):
def mock_transport_exception():
return self._get_mock_transport_exception()
mock_response = mock.Mock()
del mock_response.trailing_metadata
mock_response.exception = mock_transport_exception
interceptor = self._create_test_interceptor()
result = interceptor._get_trailing_metadata(mock_response)
self.assertEqual(result, tuple())
def test_get_trailing_metadata_unknown_failure(self):
"""Returns an empty tuple if metadata cannot be found."""
with mock.patch('logging.config.dictConfig'):
def mock_unknown_exception():
# using a mock transport exception but deleting the
# trailing_metadata attribute to simulate an unknown error type
exception = self._get_mock_transport_exception()
del exception.trailing_metadata
return exception
mock_response = mock.Mock()
del mock_response.trailing_metadata
mock_response.exception = mock_unknown_exception
interceptor = self._create_test_interceptor()
result = interceptor._get_trailing_metadata(mock_response)
self.assertEqual(result, tuple())
def test_get_fault_message(self):
"""Returns None if an error message cannot be found."""
with mock.patch('logging.config.dictConfig'):
mock_exception = None
interceptor = self._create_test_interceptor()
result = interceptor._get_fault_message(mock_exception)
self.assertEqual(result, None)
def test_get_fault_message_google_ads_failure(self):
"""Retrieves an error message from a GoogleAdsException."""
with mock.patch('logging.config.dictConfig'):
mock_exception = self._get_mock_exception()
interceptor = self._create_test_interceptor()
result = interceptor._get_fault_message(mock_exception)
self.assertEqual(result, self._MOCK_ERROR_MESSAGE)
def test_get_fault_message_transport_failure(self):
"""Retrieves an error message from a transport error object."""
with mock.patch('logging.config.dictConfig'):
mock_exception = self._get_mock_transport_exception()
interceptor = self._create_test_interceptor()
result = interceptor._get_fault_message(mock_exception)
self.assertEqual(result, self._MOCK_TRANSPORT_ERROR_MESSAGE)
class ExceptionInterceptorTest(TestCase):
"""Tests for the google.ads.googleads.client.ExceptionInterceptor class."""
_MOCK_FAILURE_VALUE = b"\n \n\x02\x08\x10\x12\x1aInvalid customer ID '123'."
def _create_test_interceptor(self):
"""Creates and returns an ExceptionInterceptor instance
Returns:
An ExceptionInterceptor instance.
"""
return Client.ExceptionInterceptor()
def test_init_(self):
"""Tests that the interceptor initializes properly"""
interceptor = self._create_test_interceptor()
self.assertEqual(interceptor._RETRY_STATUS_CODES,
(grpc.StatusCode.INTERNAL,
grpc.StatusCode.RESOURCE_EXHAUSTED))
def test_get_google_ads_failure(self):
"""Obtains the content of a google ads failure from metadata."""
interceptor = self._create_test_interceptor()
mock_metadata = ((interceptor._failure_key, self._MOCK_FAILURE_VALUE),)
result = interceptor._get_google_ads_failure(mock_metadata)
self.assertIsInstance(result, error_protos.GoogleAdsFailure)
def test_get_google_ads_failure_decode_error(self):
"""Returns none if the google ads failure cannot be decoded."""
interceptor = self._create_test_interceptor()
mock_failure_value = self._MOCK_FAILURE_VALUE + b'1234'
mock_metadata = ((interceptor._failure_key, mock_failure_value),)
result = interceptor._get_google_ads_failure(mock_metadata)
self.assertEqual(result, None)
def test_get_google_ads_failure_no_failure_key(self):
"""Returns None if an error cannot be found in metadata."""
mock_metadata = (('another-key', 'another-val'),)
interceptor = self._create_test_interceptor()
result = interceptor._get_google_ads_failure(mock_metadata)
self.assertEqual(result, None)
def test_get_google_ads_failure_with_None(self):
"""Returns None if None is passed."""
interceptor = self._create_test_interceptor()
result = interceptor._get_google_ads_failure(None)
self.assertEqual(result, None)
def test_handle_grpc_failure(self):
"""Raises non-retryable GoogleAdsFailures as GoogleAdsExceptions."""
mock_error_message = self._MOCK_FAILURE_VALUE
class MockRpcErrorResponse(grpc.RpcError):
def code(self):
return grpc.StatusCode.INVALID_ARGUMENT
def trailing_metadata(self):
return ((interceptor._failure_key, mock_error_message),)
def exception(self):
return self
interceptor = self._create_test_interceptor()
self.assertRaises(GoogleAdsException,
interceptor._handle_grpc_failure,
MockRpcErrorResponse())
def test_handle_grpc_failure_retryable(self):
"""Raises retryable exceptions as-is."""
class MockRpcErrorResponse(grpc.RpcError):
def code(self):
return grpc.StatusCode.INTERNAL
def exception(self):
return self
interceptor = self._create_test_interceptor()
self.assertRaises(MockRpcErrorResponse,
interceptor._handle_grpc_failure,
MockRpcErrorResponse())
def test_handle_grpc_failure_not_google_ads_failure(self):
"""Raises as-is non-retryable non-GoogleAdsFailure exceptions."""
class MockRpcErrorResponse(grpc.RpcError):
def code(self):
return grpc.StatusCode.INVALID_ARGUMENT
def trailing_metadata(self):
return (('bad-failure-key', 'arbitrary-value'),)
def exception(self):
return self
interceptor = self._create_test_interceptor()
self.assertRaises(MockRpcErrorResponse,
interceptor._handle_grpc_failure,
MockRpcErrorResponse())
def test_intercept_unary_unary_response_is_exception(self):
"""If response.exception() is not None exception is handled."""
mock_exception = grpc.RpcError()
class MockResponse():
def exception(self):
return mock_exception
mock_request = mock.Mock()
mock_client_call_details = mock.Mock()
mock_response = MockResponse()
def mock_continuation(client_call_details, request):
del client_call_details
del request
return mock_response
interceptor = self._create_test_interceptor()
with mock.patch.object(interceptor, '_handle_grpc_failure'):
interceptor.intercept_unary_unary(
mock_continuation, mock_client_call_details, mock_request)
interceptor._handle_grpc_failure.assert_called_once_with(
mock_response)
def test_intercept_unary_unary_response_is_successful(self):
"""If response.exception() is None response is returned."""
class MockResponse():
def exception(self):
return None
mock_request = mock.Mock()
mock_client_call_details = mock.Mock()
mock_response = MockResponse()
def mock_continuation(client_call_details, request):
del client_call_details
del request
return mock_response