From 50ca9becf959a2872e8a33b9afc00766dbfaa196 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 20 May 2021 15:53:19 -0600 Subject: [PATCH] chore: upgrade gapic-generator-python to 0.46.3 (#76) feat: support self-signed JWT flow for service accounts fix: add async client to %name_%version/init.py chore: add autogenerated snippets chore: remove auth, policy, and options from the reserved names list chore: enable GAPIC metadata generation chore: sort subpackages in %namespace/%name/init.py --- google/cloud/iam_credentials/__init__.py | 12 +- google/cloud/iam_credentials_v1/__init__.py | 7 +- .../iam_credentials_v1/gapic_metadata.json | 63 +++ .../iam_credentials_v1/services/__init__.py | 1 - .../services/iam_credentials/__init__.py | 2 - .../services/iam_credentials/async_client.py | 54 +- .../services/iam_credentials/client.py | 79 ++- .../iam_credentials/transports/__init__.py | 2 - .../iam_credentials/transports/base.py | 133 +++-- .../iam_credentials/transports/grpc.py | 22 +- .../transports/grpc_asyncio.py | 23 +- .../iam_credentials_v1/types/__init__.py | 2 - .../cloud/iam_credentials_v1/types/common.py | 70 +-- .../types/iamcredentials.py | 1 - owlbot.py | 10 +- scripts/fixup_credentials_v1_keywords.py | 13 +- setup.py | 1 + testing/constraints-3.6.txt | 2 + tests/__init__.py | 15 + tests/unit/__init__.py | 15 + tests/unit/gapic/__init__.py | 15 + tests/unit/gapic/credentials_v1/__init__.py | 1 - .../credentials_v1/test_iam_credentials.py | 485 ++++++++++++------ 23 files changed, 647 insertions(+), 381 deletions(-) create mode 100644 google/cloud/iam_credentials_v1/gapic_metadata.json create mode 100644 tests/__init__.py create mode 100644 tests/unit/__init__.py create mode 100644 tests/unit/gapic/__init__.py diff --git a/google/cloud/iam_credentials/__init__.py b/google/cloud/iam_credentials/__init__.py index b9e9538..a68b3ae 100644 --- a/google/cloud/iam_credentials/__init__.py +++ b/google/cloud/iam_credentials/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,12 +14,13 @@ # limitations under the License. # -from google.cloud.iam_credentials_v1.services.iam_credentials.async_client import ( - IAMCredentialsAsyncClient, -) from google.cloud.iam_credentials_v1.services.iam_credentials.client import ( IAMCredentialsClient, ) +from google.cloud.iam_credentials_v1.services.iam_credentials.async_client import ( + IAMCredentialsAsyncClient, +) + from google.cloud.iam_credentials_v1.types.common import GenerateAccessTokenRequest from google.cloud.iam_credentials_v1.types.common import GenerateAccessTokenResponse from google.cloud.iam_credentials_v1.types.common import GenerateIdTokenRequest @@ -31,12 +31,12 @@ from google.cloud.iam_credentials_v1.types.common import SignJwtResponse __all__ = ( + "IAMCredentialsClient", + "IAMCredentialsAsyncClient", "GenerateAccessTokenRequest", "GenerateAccessTokenResponse", "GenerateIdTokenRequest", "GenerateIdTokenResponse", - "IAMCredentialsAsyncClient", - "IAMCredentialsClient", "SignBlobRequest", "SignBlobResponse", "SignJwtRequest", diff --git a/google/cloud/iam_credentials_v1/__init__.py b/google/cloud/iam_credentials_v1/__init__.py index aaf7fed..cd37f9c 100644 --- a/google/cloud/iam_credentials_v1/__init__.py +++ b/google/cloud/iam_credentials_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +15,8 @@ # from .services.iam_credentials import IAMCredentialsClient +from .services.iam_credentials import IAMCredentialsAsyncClient + from .types.common import GenerateAccessTokenRequest from .types.common import GenerateAccessTokenResponse from .types.common import GenerateIdTokenRequest @@ -25,15 +26,15 @@ from .types.common import SignJwtRequest from .types.common import SignJwtResponse - __all__ = ( + "IAMCredentialsAsyncClient", "GenerateAccessTokenRequest", "GenerateAccessTokenResponse", "GenerateIdTokenRequest", "GenerateIdTokenResponse", + "IAMCredentialsClient", "SignBlobRequest", "SignBlobResponse", "SignJwtRequest", "SignJwtResponse", - "IAMCredentialsClient", ) diff --git a/google/cloud/iam_credentials_v1/gapic_metadata.json b/google/cloud/iam_credentials_v1/gapic_metadata.json new file mode 100644 index 0000000..82b1d8a --- /dev/null +++ b/google/cloud/iam_credentials_v1/gapic_metadata.json @@ -0,0 +1,63 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.iam.credentials_v1", + "protoPackage": "google.iam.credentials.v1", + "schema": "1.0", + "services": { + "IAMCredentials": { + "clients": { + "grpc": { + "libraryClient": "IAMCredentialsClient", + "rpcs": { + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GenerateIdToken": { + "methods": [ + "generate_id_token" + ] + }, + "SignBlob": { + "methods": [ + "sign_blob" + ] + }, + "SignJwt": { + "methods": [ + "sign_jwt" + ] + } + } + }, + "grpc-async": { + "libraryClient": "IAMCredentialsAsyncClient", + "rpcs": { + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GenerateIdToken": { + "methods": [ + "generate_id_token" + ] + }, + "SignBlob": { + "methods": [ + "sign_blob" + ] + }, + "SignJwt": { + "methods": [ + "sign_jwt" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/iam_credentials_v1/services/__init__.py b/google/cloud/iam_credentials_v1/services/__init__.py index 42ffdf2..4de6597 100644 --- a/google/cloud/iam_credentials_v1/services/__init__.py +++ b/google/cloud/iam_credentials_v1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/iam_credentials_v1/services/iam_credentials/__init__.py b/google/cloud/iam_credentials_v1/services/iam_credentials/__init__.py index 7ac7578..3408a00 100644 --- a/google/cloud/iam_credentials_v1/services/iam_credentials/__init__.py +++ b/google/cloud/iam_credentials_v1/services/iam_credentials/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import IAMCredentialsClient from .async_client import IAMCredentialsAsyncClient diff --git a/google/cloud/iam_credentials_v1/services/iam_credentials/async_client.py b/google/cloud/iam_credentials_v1/services/iam_credentials/async_client.py index 443628e..14d5cbd 100644 --- a/google/cloud/iam_credentials_v1/services/iam_credentials/async_client.py +++ b/google/cloud/iam_credentials_v1/services/iam_credentials/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,16 +20,15 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.iam_credentials_v1.types import common -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport from .client import IAMCredentialsClient @@ -59,31 +56,26 @@ class IAMCredentialsAsyncClient: parse_service_account_path = staticmethod( IAMCredentialsClient.parse_service_account_path ) - common_billing_account_path = staticmethod( IAMCredentialsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( IAMCredentialsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(IAMCredentialsClient.common_folder_path) parse_common_folder_path = staticmethod( IAMCredentialsClient.parse_common_folder_path ) - common_organization_path = staticmethod( IAMCredentialsClient.common_organization_path ) parse_common_organization_path = staticmethod( IAMCredentialsClient.parse_common_organization_path ) - common_project_path = staticmethod(IAMCredentialsClient.common_project_path) parse_common_project_path = staticmethod( IAMCredentialsClient.parse_common_project_path ) - common_location_path = staticmethod(IAMCredentialsClient.common_location_path) parse_common_location_path = staticmethod( IAMCredentialsClient.parse_common_location_path @@ -91,7 +83,8 @@ class IAMCredentialsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -106,7 +99,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -123,7 +116,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> IAMCredentialsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: IAMCredentialsTransport: The transport used by the client instance. @@ -137,12 +130,12 @@ def transport(self) -> IAMCredentialsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, IAMCredentialsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the iam credentials client. + """Instantiates the iam credentials client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -174,7 +167,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = IAMCredentialsClient( credentials=credentials, transport=transport, @@ -189,7 +181,7 @@ async def generate_access_token( name: str = None, delegates: Sequence[str] = None, scope: Sequence[str] = None, - lifetime: duration.Duration = None, + lifetime: duration_pb2.Duration = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -251,7 +243,6 @@ async def generate_access_token( This corresponds to the ``lifetime`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -276,12 +267,10 @@ async def generate_access_token( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if lifetime is not None: request.lifetime = lifetime - if delegates: request.delegates.extend(delegates) if scope: @@ -296,7 +285,8 @@ async def generate_access_token( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -379,7 +369,6 @@ async def generate_id_token( This corresponds to the ``include_email`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -404,14 +393,12 @@ async def generate_id_token( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if audience is not None: request.audience = audience if include_email is not None: request.include_email = include_email - if delegates: request.delegates.extend(delegates) @@ -424,7 +411,8 @@ async def generate_id_token( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -495,7 +483,6 @@ async def sign_blob( This corresponds to the ``payload`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -520,12 +507,10 @@ async def sign_blob( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if payload is not None: request.payload = payload - if delegates: request.delegates.extend(delegates) @@ -538,7 +523,8 @@ async def sign_blob( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -612,7 +598,6 @@ async def sign_jwt( This corresponds to the ``payload`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -637,12 +622,10 @@ async def sign_jwt( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if payload is not None: request.payload = payload - if delegates: request.delegates.extend(delegates) @@ -655,7 +638,8 @@ async def sign_jwt( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), diff --git a/google/cloud/iam_credentials_v1/services/iam_credentials/client.py b/google/cloud/iam_credentials_v1/services/iam_credentials/client.py index 1261fb9..ad4b498 100644 --- a/google/cloud/iam_credentials_v1/services/iam_credentials/client.py +++ b/google/cloud/iam_credentials_v1/services/iam_credentials/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,19 +21,18 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.iam_credentials_v1.types import common -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import IAMCredentialsGrpcTransport from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport @@ -56,7 +53,7 @@ class IAMCredentialsClientMeta(type): _transport_registry["grpc_asyncio"] = IAMCredentialsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[IAMCredentialsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -89,7 +86,8 @@ class IAMCredentialsClient(metaclass=IAMCredentialsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -123,7 +121,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -140,7 +139,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -159,23 +158,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> IAMCredentialsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - IAMCredentialsTransport: The transport used by the client instance. + IAMCredentialsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def service_account_path(project: str, service_account: str,) -> str: - """Return a fully-qualified service_account string.""" + """Returns a fully-qualified service_account string.""" return "projects/{project}/serviceAccounts/{service_account}".format( project=project, service_account=service_account, ) @staticmethod def parse_service_account_path(path: str) -> Dict[str, str]: - """Parse a service_account path into its component segments.""" + """Parses a service_account path into its component segments.""" m = re.match( r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", path, @@ -184,7 +184,7 @@ def parse_service_account_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -197,7 +197,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -208,7 +208,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -219,7 +219,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -230,7 +230,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -244,12 +244,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, IAMCredentialsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the iam credentials client. + """Instantiates the iam credentials client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -304,9 +304,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -318,12 +319,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -338,8 +341,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -361,7 +364,7 @@ def generate_access_token( name: str = None, delegates: Sequence[str] = None, scope: Sequence[str] = None, - lifetime: duration.Duration = None, + lifetime: duration_pb2.Duration = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -423,7 +426,6 @@ def generate_access_token( This corresponds to the ``lifetime`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -450,10 +452,8 @@ def generate_access_token( # there are no flattened fields. if not isinstance(request, common.GenerateAccessTokenRequest): request = common.GenerateAccessTokenRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if delegates is not None: @@ -542,7 +542,6 @@ def generate_id_token( This corresponds to the ``include_email`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -569,10 +568,8 @@ def generate_id_token( # there are no flattened fields. if not isinstance(request, common.GenerateIdTokenRequest): request = common.GenerateIdTokenRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if delegates is not None: @@ -649,7 +646,6 @@ def sign_blob( This corresponds to the ``payload`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -676,10 +672,8 @@ def sign_blob( # there are no flattened fields. if not isinstance(request, common.SignBlobRequest): request = common.SignBlobRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if delegates is not None: @@ -757,7 +751,6 @@ def sign_jwt( This corresponds to the ``payload`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -784,10 +777,8 @@ def sign_jwt( # there are no flattened fields. if not isinstance(request, common.SignJwtRequest): request = common.SignJwtRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if delegates is not None: diff --git a/google/cloud/iam_credentials_v1/services/iam_credentials/transports/__init__.py b/google/cloud/iam_credentials_v1/services/iam_credentials/transports/__init__.py index 10aacfc..31e19cf 100644 --- a/google/cloud/iam_credentials_v1/services/iam_credentials/transports/__init__.py +++ b/google/cloud/iam_credentials_v1/services/iam_credentials/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/iam_credentials_v1/services/iam_credentials/transports/base.py b/google/cloud/iam_credentials_v1/services/iam_credentials/transports/base.py index 7b87338..7eeca28 100644 --- a/google/cloud/iam_credentials_v1/services/iam_credentials/transports/base.py +++ b/google/cloud/iam_credentials_v1/services/iam_credentials/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.iam_credentials_v1.types import common - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-iam",).version, @@ -35,27 +34,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class IAMCredentialsTransport(abc.ABC): """Abstract transport class for IAMCredentials.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "iamcredentials.googleapis.com" + def __init__( self, *, - host: str = "iamcredentials.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -64,7 +77,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -78,29 +91,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -111,7 +171,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -125,7 +186,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -139,7 +201,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -153,7 +216,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -165,11 +229,11 @@ def _prep_wrapped_messages(self, client_info): @property def generate_access_token( self, - ) -> typing.Callable[ + ) -> Callable[ [common.GenerateAccessTokenRequest], - typing.Union[ + Union[ common.GenerateAccessTokenResponse, - typing.Awaitable[common.GenerateAccessTokenResponse], + Awaitable[common.GenerateAccessTokenResponse], ], ]: raise NotImplementedError() @@ -177,11 +241,10 @@ def generate_access_token( @property def generate_id_token( self, - ) -> typing.Callable[ + ) -> Callable[ [common.GenerateIdTokenRequest], - typing.Union[ - common.GenerateIdTokenResponse, - typing.Awaitable[common.GenerateIdTokenResponse], + Union[ + common.GenerateIdTokenResponse, Awaitable[common.GenerateIdTokenResponse] ], ]: raise NotImplementedError() @@ -189,20 +252,18 @@ def generate_id_token( @property def sign_blob( self, - ) -> typing.Callable[ + ) -> Callable[ [common.SignBlobRequest], - typing.Union[ - common.SignBlobResponse, typing.Awaitable[common.SignBlobResponse] - ], + Union[common.SignBlobResponse, Awaitable[common.SignBlobResponse]], ]: raise NotImplementedError() @property def sign_jwt( self, - ) -> typing.Callable[ + ) -> Callable[ [common.SignJwtRequest], - typing.Union[common.SignJwtResponse, typing.Awaitable[common.SignJwtResponse]], + Union[common.SignJwtResponse, Awaitable[common.SignJwtResponse]], ]: raise NotImplementedError() diff --git a/google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc.py b/google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc.py index a60ed7f..6510b14 100644 --- a/google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc.py +++ b/google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.iam_credentials_v1.types import common - from .base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO @@ -59,7 +56,7 @@ def __init__( self, *, host: str = "iamcredentials.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -73,7 +70,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -183,7 +181,7 @@ def __init__( def create_channel( cls, host: str = "iamcredentials.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -214,13 +212,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) diff --git a/google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc_asyncio.py b/google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc_asyncio.py index 026460d..aceaf50 100644 --- a/google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc_asyncio.py +++ b/google/cloud/iam_credentials_v1/services/iam_credentials/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.iam_credentials_v1.types import common - from .base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO from .grpc import IAMCredentialsGrpcTransport @@ -62,7 +59,7 @@ class IAMCredentialsGrpcAsyncIOTransport(IAMCredentialsTransport): def create_channel( cls, host: str = "iamcredentials.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -89,13 +86,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -103,7 +102,7 @@ def __init__( self, *, host: str = "iamcredentials.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -117,7 +116,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -175,7 +175,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/iam_credentials_v1/types/__init__.py b/google/cloud/iam_credentials_v1/types/__init__.py index dbdc3bb..5562856 100644 --- a/google/cloud/iam_credentials_v1/types/__init__.py +++ b/google/cloud/iam_credentials_v1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .common import ( GenerateAccessTokenRequest, GenerateAccessTokenResponse, diff --git a/google/cloud/iam_credentials_v1/types/common.py b/google/cloud/iam_credentials_v1/types/common.py index eb8fa59..5124bbc 100644 --- a/google/cloud/iam_credentials_v1/types/common.py +++ b/google/cloud/iam_credentials_v1/types/common.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -39,7 +36,6 @@ class GenerateAccessTokenRequest(proto.Message): r""" - Attributes: name (str): Required. The resource name of the service account for which @@ -75,18 +71,14 @@ class GenerateAccessTokenRequest(proto.Message): to a default value of one hour. """ - name = proto.Field(proto.STRING, number=1) - - delegates = proto.RepeatedField(proto.STRING, number=2) - - scope = proto.RepeatedField(proto.STRING, number=4) - - lifetime = proto.Field(proto.MESSAGE, number=7, message=duration.Duration,) + name = proto.Field(proto.STRING, number=1,) + delegates = proto.RepeatedField(proto.STRING, number=2,) + scope = proto.RepeatedField(proto.STRING, number=4,) + lifetime = proto.Field(proto.MESSAGE, number=7, message=duration_pb2.Duration,) class GenerateAccessTokenResponse(proto.Message): r""" - Attributes: access_token (str): The OAuth 2.0 access token. @@ -95,14 +87,12 @@ class GenerateAccessTokenResponse(proto.Message): The expiration time is always set. """ - access_token = proto.Field(proto.STRING, number=1) - - expire_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + access_token = proto.Field(proto.STRING, number=1,) + expire_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) class SignBlobRequest(proto.Message): r""" - Attributes: name (str): Required. The resource name of the service account for which @@ -128,16 +118,13 @@ class SignBlobRequest(proto.Message): Required. The bytes to sign. """ - name = proto.Field(proto.STRING, number=1) - - delegates = proto.RepeatedField(proto.STRING, number=3) - - payload = proto.Field(proto.BYTES, number=5) + name = proto.Field(proto.STRING, number=1,) + delegates = proto.RepeatedField(proto.STRING, number=3,) + payload = proto.Field(proto.BYTES, number=5,) class SignBlobResponse(proto.Message): r""" - Attributes: key_id (str): The ID of the key used to sign the blob. @@ -145,14 +132,12 @@ class SignBlobResponse(proto.Message): The signed blob. """ - key_id = proto.Field(proto.STRING, number=1) - - signed_blob = proto.Field(proto.BYTES, number=4) + key_id = proto.Field(proto.STRING, number=1,) + signed_blob = proto.Field(proto.BYTES, number=4,) class SignJwtRequest(proto.Message): r""" - Attributes: name (str): Required. The resource name of the service account for which @@ -179,16 +164,13 @@ class SignJwtRequest(proto.Message): object that contains a JWT Claims Set. """ - name = proto.Field(proto.STRING, number=1) - - delegates = proto.RepeatedField(proto.STRING, number=3) - - payload = proto.Field(proto.STRING, number=5) + name = proto.Field(proto.STRING, number=1,) + delegates = proto.RepeatedField(proto.STRING, number=3,) + payload = proto.Field(proto.STRING, number=5,) class SignJwtResponse(proto.Message): r""" - Attributes: key_id (str): The ID of the key used to sign the JWT. @@ -196,14 +178,12 @@ class SignJwtResponse(proto.Message): The signed JWT. """ - key_id = proto.Field(proto.STRING, number=1) - - signed_jwt = proto.Field(proto.STRING, number=2) + key_id = proto.Field(proto.STRING, number=1,) + signed_jwt = proto.Field(proto.STRING, number=2,) class GenerateIdTokenRequest(proto.Message): r""" - Attributes: name (str): Required. The resource name of the service account for which @@ -235,24 +215,20 @@ class GenerateIdTokenRequest(proto.Message): ``email_verified`` claims. """ - name = proto.Field(proto.STRING, number=1) - - delegates = proto.RepeatedField(proto.STRING, number=2) - - audience = proto.Field(proto.STRING, number=3) - - include_email = proto.Field(proto.BOOL, number=4) + name = proto.Field(proto.STRING, number=1,) + delegates = proto.RepeatedField(proto.STRING, number=2,) + audience = proto.Field(proto.STRING, number=3,) + include_email = proto.Field(proto.BOOL, number=4,) class GenerateIdTokenResponse(proto.Message): r""" - Attributes: token (str): The OpenId Connect ID token. """ - token = proto.Field(proto.STRING, number=1) + token = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/iam_credentials_v1/types/iamcredentials.py b/google/cloud/iam_credentials_v1/types/iamcredentials.py index 64cd49a..37adbe2 100644 --- a/google/cloud/iam_credentials_v1/types/iamcredentials.py +++ b/google/cloud/iam_credentials_v1/types/iamcredentials.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/owlbot.py b/owlbot.py index 1b0a047..283c069 100644 --- a/owlbot.py +++ b/owlbot.py @@ -47,6 +47,14 @@ "google-cloud-iam" ) + # Comment out broken assertion in unit test + # https://github.com/googleapis/gapic-generator-python/issues/897 + s.replace( + library / "tests/**/*.py", + "assert args\[0\]\.lifetime == duration_pb2\.Duration\(seconds=751\)", + "# assert args[0].lifetime == duration_pb2.Duration(seconds=751)" + ) + s.move(library / "google/iam/credentials/", "google/cloud/iam_credentials") s.move(library / "google/iam/credentials_v1", "google/cloud/iam_credentials_v1") s.move(library / "tests") @@ -69,4 +77,4 @@ # TODO(busunkim): Use latest sphinx after microgenerator transition s.replace("noxfile.py", """['"]sphinx['"]""", '"sphinx<3.0.0"') -s.shell.run(["nox", "-s", "blacken"], hide_output=False) \ No newline at end of file +s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/scripts/fixup_credentials_v1_keywords.py b/scripts/fixup_credentials_v1_keywords.py index acac0cb..f9e0141 100644 --- a/scripts/fixup_credentials_v1_keywords.py +++ b/scripts/fixup_credentials_v1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,11 +39,10 @@ def partition( class credentialsCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'generate_access_token': ('name', 'scope', 'delegates', 'lifetime', ), - 'generate_id_token': ('name', 'audience', 'delegates', 'include_email', ), - 'sign_blob': ('name', 'payload', 'delegates', ), - 'sign_jwt': ('name', 'payload', 'delegates', ), - + 'generate_access_token': ('name', 'scope', 'delegates', 'lifetime', ), + 'generate_id_token': ('name', 'audience', 'delegates', 'include_email', ), + 'sign_blob': ('name', 'payload', 'delegates', ), + 'sign_jwt': ('name', 'payload', 'delegates', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -76,7 +73,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/setup.py b/setup.py index b1cf4db..a66ebc5 100644 --- a/setup.py +++ b/setup.py @@ -30,6 +30,7 @@ dependencies = [ "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "proto-plus >= 0.4.0", + "packaging >= 14.3", ] package_root = os.path.abspath(os.path.dirname(__file__)) diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 105594f..61870e6 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -7,3 +7,5 @@ # Then this file should have foo==1.14.0 google-api-core==1.22.2 proto-plus==0.4.0 +packaging==14.3 +google-auth==1.24.0 # TODO: remove when google-api-core>=1.25.0 is required transitively through google-api-core diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..4de6597 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 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 +# +# 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. +# diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000..4de6597 --- /dev/null +++ b/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 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 +# +# 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. +# diff --git a/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..4de6597 --- /dev/null +++ b/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 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 +# +# 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. +# diff --git a/tests/unit/gapic/credentials_v1/__init__.py b/tests/unit/gapic/credentials_v1/__init__.py index 42ffdf2..4de6597 100644 --- a/tests/unit/gapic/credentials_v1/__init__.py +++ b/tests/unit/gapic/credentials_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/credentials_v1/test_iam_credentials.py b/tests/unit/gapic/credentials_v1/test_iam_credentials.py index e6fba4a..de36a81 100644 --- a/tests/unit/gapic/credentials_v1/test_iam_credentials.py +++ b/tests/unit/gapic/credentials_v1/test_iam_credentials.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.iam_credentials_v1.services.iam_credentials import ( IAMCredentialsAsyncClient, @@ -39,10 +38,40 @@ IAMCredentialsClient, ) from google.cloud.iam_credentials_v1.services.iam_credentials import transports +from google.cloud.iam_credentials_v1.services.iam_credentials.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.iam_credentials_v1.services.iam_credentials.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.iam_credentials_v1.types import common from google.oauth2 import service_account -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -93,7 +122,7 @@ def test__get_default_mtls_endpoint(): "client_class", [IAMCredentialsClient, IAMCredentialsAsyncClient,] ) def test_iam_credentials_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -110,7 +139,7 @@ def test_iam_credentials_client_from_service_account_info(client_class): "client_class", [IAMCredentialsClient, IAMCredentialsAsyncClient,] ) def test_iam_credentials_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -163,7 +192,7 @@ def test_iam_credentials_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(IAMCredentialsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -451,7 +480,7 @@ def test_generate_access_token( transport: str = "grpc", request_type=common.GenerateAccessTokenRequest ): client = IAMCredentialsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -466,19 +495,15 @@ def test_generate_access_token( call.return_value = common.GenerateAccessTokenResponse( access_token="access_token_value", ) - response = client.generate_access_token(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == common.GenerateAccessTokenRequest() # Establish that the response is the type that we expect. - assert isinstance(response, common.GenerateAccessTokenResponse) - assert response.access_token == "access_token_value" @@ -490,7 +515,7 @@ def test_generate_access_token_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IAMCredentialsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -500,7 +525,6 @@ def test_generate_access_token_empty_call(): client.generate_access_token() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == common.GenerateAccessTokenRequest() @@ -509,7 +533,7 @@ async def test_generate_access_token_async( transport: str = "grpc_asyncio", request_type=common.GenerateAccessTokenRequest ): client = IAMCredentialsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -524,18 +548,15 @@ async def test_generate_access_token_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( common.GenerateAccessTokenResponse(access_token="access_token_value",) ) - response = await client.generate_access_token(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == common.GenerateAccessTokenRequest() # Establish that the response is the type that we expect. assert isinstance(response, common.GenerateAccessTokenResponse) - assert response.access_token == "access_token_value" @@ -545,11 +566,12 @@ async def test_generate_access_token_async_from_dict(): def test_generate_access_token_field_headers(): - client = IAMCredentialsClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = common.GenerateAccessTokenRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -557,7 +579,6 @@ def test_generate_access_token_field_headers(): type(client.transport.generate_access_token), "__call__" ) as call: call.return_value = common.GenerateAccessTokenResponse() - client.generate_access_token(request) # Establish that the underlying gRPC stub method was called. @@ -572,11 +593,14 @@ def test_generate_access_token_field_headers(): @pytest.mark.asyncio async def test_generate_access_token_field_headers_async(): - client = IAMCredentialsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = common.GenerateAccessTokenRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -586,7 +610,6 @@ async def test_generate_access_token_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( common.GenerateAccessTokenResponse() ) - await client.generate_access_token(request) # Establish that the underlying gRPC stub method was called. @@ -600,7 +623,7 @@ async def test_generate_access_token_field_headers_async(): def test_generate_access_token_flattened(): - client = IAMCredentialsClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -608,34 +631,27 @@ def test_generate_access_token_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = common.GenerateAccessTokenResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.generate_access_token( name="name_value", delegates=["delegates_value"], scope=["scope_value"], - lifetime=duration.Duration(seconds=751), + lifetime=duration_pb2.Duration(seconds=751), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].delegates == ["delegates_value"] - assert args[0].scope == ["scope_value"] - - assert DurationRule().to_proto(args[0].lifetime) == duration.Duration( - seconds=751 - ) + # assert args[0].lifetime == duration_pb2.Duration(seconds=751) def test_generate_access_token_flattened_error(): - client = IAMCredentialsClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -645,13 +661,15 @@ def test_generate_access_token_flattened_error(): name="name_value", delegates=["delegates_value"], scope=["scope_value"], - lifetime=duration.Duration(seconds=751), + lifetime=duration_pb2.Duration(seconds=751), ) @pytest.mark.asyncio async def test_generate_access_token_flattened_async(): - client = IAMCredentialsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -669,28 +687,24 @@ async def test_generate_access_token_flattened_async(): name="name_value", delegates=["delegates_value"], scope=["scope_value"], - lifetime=duration.Duration(seconds=751), + lifetime=duration_pb2.Duration(seconds=751), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].delegates == ["delegates_value"] - assert args[0].scope == ["scope_value"] - - assert DurationRule().to_proto(args[0].lifetime) == duration.Duration( - seconds=751 - ) + # assert args[0].lifetime == duration_pb2.Duration(seconds=751) @pytest.mark.asyncio async def test_generate_access_token_flattened_error_async(): - client = IAMCredentialsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -700,7 +714,7 @@ async def test_generate_access_token_flattened_error_async(): name="name_value", delegates=["delegates_value"], scope=["scope_value"], - lifetime=duration.Duration(seconds=751), + lifetime=duration_pb2.Duration(seconds=751), ) @@ -708,7 +722,7 @@ def test_generate_id_token( transport: str = "grpc", request_type=common.GenerateIdTokenRequest ): client = IAMCredentialsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -721,19 +735,15 @@ def test_generate_id_token( ) as call: # Designate an appropriate return value for the call. call.return_value = common.GenerateIdTokenResponse(token="token_value",) - response = client.generate_id_token(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == common.GenerateIdTokenRequest() # Establish that the response is the type that we expect. - assert isinstance(response, common.GenerateIdTokenResponse) - assert response.token == "token_value" @@ -745,7 +755,7 @@ def test_generate_id_token_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IAMCredentialsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -755,7 +765,6 @@ def test_generate_id_token_empty_call(): client.generate_id_token() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == common.GenerateIdTokenRequest() @@ -764,7 +773,7 @@ async def test_generate_id_token_async( transport: str = "grpc_asyncio", request_type=common.GenerateIdTokenRequest ): client = IAMCredentialsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -779,18 +788,15 @@ async def test_generate_id_token_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( common.GenerateIdTokenResponse(token="token_value",) ) - response = await client.generate_id_token(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == common.GenerateIdTokenRequest() # Establish that the response is the type that we expect. assert isinstance(response, common.GenerateIdTokenResponse) - assert response.token == "token_value" @@ -800,11 +806,12 @@ async def test_generate_id_token_async_from_dict(): def test_generate_id_token_field_headers(): - client = IAMCredentialsClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = common.GenerateIdTokenRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -812,7 +819,6 @@ def test_generate_id_token_field_headers(): type(client.transport.generate_id_token), "__call__" ) as call: call.return_value = common.GenerateIdTokenResponse() - client.generate_id_token(request) # Establish that the underlying gRPC stub method was called. @@ -827,11 +833,14 @@ def test_generate_id_token_field_headers(): @pytest.mark.asyncio async def test_generate_id_token_field_headers_async(): - client = IAMCredentialsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = common.GenerateIdTokenRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -841,7 +850,6 @@ async def test_generate_id_token_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( common.GenerateIdTokenResponse() ) - await client.generate_id_token(request) # Establish that the underlying gRPC stub method was called. @@ -855,7 +863,7 @@ async def test_generate_id_token_field_headers_async(): def test_generate_id_token_flattened(): - client = IAMCredentialsClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -863,7 +871,6 @@ def test_generate_id_token_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = common.GenerateIdTokenResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.generate_id_token( @@ -877,18 +884,14 @@ def test_generate_id_token_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].delegates == ["delegates_value"] - assert args[0].audience == "audience_value" - assert args[0].include_email == True def test_generate_id_token_flattened_error(): - client = IAMCredentialsClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -904,7 +907,9 @@ def test_generate_id_token_flattened_error(): @pytest.mark.asyncio async def test_generate_id_token_flattened_async(): - client = IAMCredentialsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -929,19 +934,17 @@ async def test_generate_id_token_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].delegates == ["delegates_value"] - assert args[0].audience == "audience_value" - assert args[0].include_email == True @pytest.mark.asyncio async def test_generate_id_token_flattened_error_async(): - client = IAMCredentialsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -957,7 +960,7 @@ async def test_generate_id_token_flattened_error_async(): def test_sign_blob(transport: str = "grpc", request_type=common.SignBlobRequest): client = IAMCredentialsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -970,21 +973,16 @@ def test_sign_blob(transport: str = "grpc", request_type=common.SignBlobRequest) call.return_value = common.SignBlobResponse( key_id="key_id_value", signed_blob=b"signed_blob_blob", ) - response = client.sign_blob(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == common.SignBlobRequest() # Establish that the response is the type that we expect. - assert isinstance(response, common.SignBlobResponse) - assert response.key_id == "key_id_value" - assert response.signed_blob == b"signed_blob_blob" @@ -996,7 +994,7 @@ def test_sign_blob_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IAMCredentialsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1004,7 +1002,6 @@ def test_sign_blob_empty_call(): client.sign_blob() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == common.SignBlobRequest() @@ -1013,7 +1010,7 @@ async def test_sign_blob_async( transport: str = "grpc_asyncio", request_type=common.SignBlobRequest ): client = IAMCredentialsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1028,20 +1025,16 @@ async def test_sign_blob_async( key_id="key_id_value", signed_blob=b"signed_blob_blob", ) ) - response = await client.sign_blob(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == common.SignBlobRequest() # Establish that the response is the type that we expect. assert isinstance(response, common.SignBlobResponse) - assert response.key_id == "key_id_value" - assert response.signed_blob == b"signed_blob_blob" @@ -1051,17 +1044,17 @@ async def test_sign_blob_async_from_dict(): def test_sign_blob_field_headers(): - client = IAMCredentialsClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = common.SignBlobRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: call.return_value = common.SignBlobResponse() - client.sign_blob(request) # Establish that the underlying gRPC stub method was called. @@ -1076,11 +1069,14 @@ def test_sign_blob_field_headers(): @pytest.mark.asyncio async def test_sign_blob_field_headers_async(): - client = IAMCredentialsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = common.SignBlobRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1088,7 +1084,6 @@ async def test_sign_blob_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( common.SignBlobResponse() ) - await client.sign_blob(request) # Establish that the underlying gRPC stub method was called. @@ -1102,13 +1097,12 @@ async def test_sign_blob_field_headers_async(): def test_sign_blob_flattened(): - client = IAMCredentialsClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = common.SignBlobResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.sign_blob( @@ -1119,16 +1113,13 @@ def test_sign_blob_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].delegates == ["delegates_value"] - assert args[0].payload == b"payload_blob" def test_sign_blob_flattened_error(): - client = IAMCredentialsClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1143,7 +1134,9 @@ def test_sign_blob_flattened_error(): @pytest.mark.asyncio async def test_sign_blob_flattened_async(): - client = IAMCredentialsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: @@ -1163,17 +1156,16 @@ async def test_sign_blob_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].delegates == ["delegates_value"] - assert args[0].payload == b"payload_blob" @pytest.mark.asyncio async def test_sign_blob_flattened_error_async(): - client = IAMCredentialsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1188,7 +1180,7 @@ async def test_sign_blob_flattened_error_async(): def test_sign_jwt(transport: str = "grpc", request_type=common.SignJwtRequest): client = IAMCredentialsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1201,21 +1193,16 @@ def test_sign_jwt(transport: str = "grpc", request_type=common.SignJwtRequest): call.return_value = common.SignJwtResponse( key_id="key_id_value", signed_jwt="signed_jwt_value", ) - response = client.sign_jwt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == common.SignJwtRequest() # Establish that the response is the type that we expect. - assert isinstance(response, common.SignJwtResponse) - assert response.key_id == "key_id_value" - assert response.signed_jwt == "signed_jwt_value" @@ -1227,7 +1214,7 @@ def test_sign_jwt_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = IAMCredentialsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1235,7 +1222,6 @@ def test_sign_jwt_empty_call(): client.sign_jwt() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == common.SignJwtRequest() @@ -1244,7 +1230,7 @@ async def test_sign_jwt_async( transport: str = "grpc_asyncio", request_type=common.SignJwtRequest ): client = IAMCredentialsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1259,20 +1245,16 @@ async def test_sign_jwt_async( key_id="key_id_value", signed_jwt="signed_jwt_value", ) ) - response = await client.sign_jwt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == common.SignJwtRequest() # Establish that the response is the type that we expect. assert isinstance(response, common.SignJwtResponse) - assert response.key_id == "key_id_value" - assert response.signed_jwt == "signed_jwt_value" @@ -1282,17 +1264,17 @@ async def test_sign_jwt_async_from_dict(): def test_sign_jwt_field_headers(): - client = IAMCredentialsClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = common.SignJwtRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: call.return_value = common.SignJwtResponse() - client.sign_jwt(request) # Establish that the underlying gRPC stub method was called. @@ -1307,11 +1289,14 @@ def test_sign_jwt_field_headers(): @pytest.mark.asyncio async def test_sign_jwt_field_headers_async(): - client = IAMCredentialsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = common.SignJwtRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1319,7 +1304,6 @@ async def test_sign_jwt_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( common.SignJwtResponse() ) - await client.sign_jwt(request) # Establish that the underlying gRPC stub method was called. @@ -1333,13 +1317,12 @@ async def test_sign_jwt_field_headers_async(): def test_sign_jwt_flattened(): - client = IAMCredentialsClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = common.SignJwtResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.sign_jwt( @@ -1350,16 +1333,13 @@ def test_sign_jwt_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].delegates == ["delegates_value"] - assert args[0].payload == "payload_value" def test_sign_jwt_flattened_error(): - client = IAMCredentialsClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1374,7 +1354,9 @@ def test_sign_jwt_flattened_error(): @pytest.mark.asyncio async def test_sign_jwt_flattened_async(): - client = IAMCredentialsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: @@ -1394,17 +1376,16 @@ async def test_sign_jwt_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].delegates == ["delegates_value"] - assert args[0].payload == "payload_value" @pytest.mark.asyncio async def test_sign_jwt_flattened_error_async(): - client = IAMCredentialsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1420,16 +1401,16 @@ async def test_sign_jwt_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.IAMCredentialsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = IAMCredentialsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.IAMCredentialsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = IAMCredentialsClient( @@ -1439,7 +1420,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.IAMCredentialsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = IAMCredentialsClient( @@ -1450,7 +1431,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.IAMCredentialsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = IAMCredentialsClient(transport=transport) assert client.transport is transport @@ -1459,13 +1440,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.IAMCredentialsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.IAMCredentialsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1480,23 +1461,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = IAMCredentialsClient(credentials=credentials.AnonymousCredentials(),) + client = IAMCredentialsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.IAMCredentialsGrpcTransport,) def test_iam_credentials_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.IAMCredentialsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1508,7 +1489,7 @@ def test_iam_credentials_base_transport(): ) as Transport: Transport.return_value = None transport = transports.IAMCredentialsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1524,15 +1505,37 @@ def test_iam_credentials_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_iam_credentials_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.iam_credentials_v1.services.iam_credentials.transports.IAMCredentialsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IAMCredentialsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_iam_credentials_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.iam_credentials_v1.services.iam_credentials.transports.IAMCredentialsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.IAMCredentialsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1545,19 +1548,33 @@ def test_iam_credentials_base_transport_with_credentials_file(): def test_iam_credentials_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.iam_credentials_v1.services.iam_credentials.transports.IAMCredentialsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.IAMCredentialsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_iam_credentials_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + IAMCredentialsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_iam_credentials_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) IAMCredentialsClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -1565,20 +1582,156 @@ def test_iam_credentials_auth_adc(): ) -def test_iam_credentials_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.IAMCredentialsGrpcTransport, + transports.IAMCredentialsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_iam_credentials_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.IAMCredentialsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.IAMCredentialsGrpcTransport, + transports.IAMCredentialsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_iam_credentials_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IAMCredentialsGrpcTransport, grpc_helpers), + (transports.IAMCredentialsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_iam_credentials_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "iamcredentials.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="iamcredentials.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IAMCredentialsGrpcTransport, grpc_helpers), + (transports.IAMCredentialsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_iam_credentials_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "iamcredentials.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IAMCredentialsGrpcTransport, grpc_helpers), + (transports.IAMCredentialsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_iam_credentials_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "iamcredentials.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1587,7 +1740,7 @@ def test_iam_credentials_transport_auth_adc(): ], ) def test_iam_credentials_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1626,7 +1779,7 @@ def test_iam_credentials_grpc_transport_client_cert_source_for_mtls(transport_cl def test_iam_credentials_host_no_port(): client = IAMCredentialsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="iamcredentials.googleapis.com" ), @@ -1636,7 +1789,7 @@ def test_iam_credentials_host_no_port(): def test_iam_credentials_host_with_port(): client = IAMCredentialsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="iamcredentials.googleapis.com:8000" ), @@ -1692,9 +1845,9 @@ def test_iam_credentials_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1771,7 +1924,6 @@ def test_iam_credentials_transport_channel_mtls_with_adc(transport_class): def test_service_account_path(): project = "squid" service_account = "clam" - expected = "projects/{project}/serviceAccounts/{service_account}".format( project=project, service_account=service_account, ) @@ -1793,7 +1945,6 @@ def test_parse_service_account_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1814,7 +1965,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = IAMCredentialsClient.common_folder_path(folder) assert expected == actual @@ -1833,7 +1983,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = IAMCredentialsClient.common_organization_path(organization) assert expected == actual @@ -1852,7 +2001,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = IAMCredentialsClient.common_project_path(project) assert expected == actual @@ -1872,7 +2020,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1899,7 +2046,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.IAMCredentialsTransport, "_prep_wrapped_messages" ) as prep: client = IAMCredentialsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1908,6 +2055,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = IAMCredentialsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info)