Skip to content

Commit

Permalink
Add interface to inject external interceptors into service requests (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
BenRKarl authored Sep 10, 2019
1 parent 337f4ea commit 41440bc
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
17 changes: 11 additions & 6 deletions google/ads/google_ads/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# limitations under the License.
"""A client and common configurations for the Google Ads API."""

import grpc
from grpc import intercept_channel
from importlib import import_module
import logging.config

Expand Down Expand Up @@ -194,7 +194,7 @@ def __init__(self, credentials, developer_token, endpoint=None,
self.endpoint = endpoint
self.login_customer_id = login_customer_id

def get_service(self, name, version=_DEFAULT_VERSION):
def get_service(self, name, version=_DEFAULT_VERSION, interceptors=[]):
"""Returns a service client instance for the specified service_name.
Args:
Expand All @@ -203,6 +203,9 @@ def get_service(self, name, version=_DEFAULT_VERSION):
"CampaignService" to retrieve a CampaignServiceClient instance.
version: a str indicating the version of the Google Ads API to be
used.
interceptors: an optional list of interceptors to include in
requests. NOTE: this parameter is not intended for non-Google
use and is not officially supported.
Returns:
A service client instance associated with the given service_name.
Expand Down Expand Up @@ -234,12 +237,14 @@ def get_service(self, name, version=_DEFAULT_VERSION):
credentials=self.credentials,
options=_GRPC_CHANNEL_OPTIONS)

channel = grpc.intercept_channel(
channel,
interceptors = interceptors + [
MetadataInterceptor(self.developer_token, self.login_customer_id),
LoggingInterceptor(_logger, endpoint),
ExceptionInterceptor(version)
)
ExceptionInterceptor(version)]

channel = intercept_channel(
channel,
*interceptors)

service_transport = service_transport_class(channel=channel)

Expand Down
16 changes: 16 additions & 0 deletions tests/client_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,22 @@ def test_get_service_with_version(self):
except Exception:
self.fail('get_service with a valid version raised an error')

def test_get_service_with_interceptor(self):
client = self._create_test_client()

class Interceptor:
pass

interceptor = Interceptor()

with mock.patch.object(
Client,
'intercept_channel'
) as mock_intercept_channel:
client.get_service('GoogleAdsService', interceptors=[interceptor])
first_interceptor = mock_intercept_channel.call_args[0][1]
self.assertEqual(first_interceptor, interceptor)

def test_get_type(self):
for ver in valid_versions:
# Retrieve names for all types defined in pb2 files.
Expand Down

0 comments on commit 41440bc

Please sign in to comment.