diff --git a/.github/sync-repo-settings.yaml b/.github/sync-repo-settings.yaml index 201ee10..b23ea95 100644 --- a/.github/sync-repo-settings.yaml +++ b/.github/sync-repo-settings.yaml @@ -17,11 +17,6 @@ branchProtectionRules: - 'unit (3.9)' - 'unit (3.10)' - 'cover' - - 'Samples - Lint' - - 'Samples - Python 3.7' - - 'Samples - Python 3.8' - - 'Samples - Python 3.9' - - 'Samples - Python 3.10' permissionRules: - team: actools-python permission: admin diff --git a/google/cloud/iam_credentials_v1/gapic_metadata.json b/google/cloud/iam_credentials_v1/gapic_metadata.json index 7ec643e..47932c3 100644 --- a/google/cloud/iam_credentials_v1/gapic_metadata.json +++ b/google/cloud/iam_credentials_v1/gapic_metadata.json @@ -56,6 +56,31 @@ ] } } + }, + "rest": { + "libraryClient": "IAMCredentialsClient", + "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/iam_credentials/client.py b/google/cloud/iam_credentials_v1/services/iam_credentials/client.py index 18369cd..5168692 100644 --- a/google/cloud/iam_credentials_v1/services/iam_credentials/client.py +++ b/google/cloud/iam_credentials_v1/services/iam_credentials/client.py @@ -54,6 +54,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport from .transports.grpc import IAMCredentialsGrpcTransport from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport +from .transports.rest import IAMCredentialsRestTransport class IAMCredentialsClientMeta(type): @@ -69,6 +70,7 @@ class IAMCredentialsClientMeta(type): ) # type: Dict[str, Type[IAMCredentialsTransport]] _transport_registry["grpc"] = IAMCredentialsGrpcTransport _transport_registry["grpc_asyncio"] = IAMCredentialsGrpcAsyncIOTransport + _transport_registry["rest"] = IAMCredentialsRestTransport def get_transport_class( cls, 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 eeb276a..db274bf 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 @@ -19,14 +19,18 @@ from .base import IAMCredentialsTransport from .grpc import IAMCredentialsGrpcTransport from .grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport +from .rest import IAMCredentialsRestInterceptor, IAMCredentialsRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[IAMCredentialsTransport]] _transport_registry["grpc"] = IAMCredentialsGrpcTransport _transport_registry["grpc_asyncio"] = IAMCredentialsGrpcAsyncIOTransport +_transport_registry["rest"] = IAMCredentialsRestTransport __all__ = ( "IAMCredentialsTransport", "IAMCredentialsGrpcTransport", "IAMCredentialsGrpcAsyncIOTransport", + "IAMCredentialsRestTransport", + "IAMCredentialsRestInterceptor", ) diff --git a/google/cloud/iam_credentials_v1/services/iam_credentials/transports/rest.py b/google/cloud/iam_credentials_v1/services/iam_credentials/transports/rest.py new file mode 100644 index 0000000..009049b --- /dev/null +++ b/google/cloud/iam_credentials_v1/services/iam_credentials/transports/rest.py @@ -0,0 +1,718 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.iam_credentials_v1.types import common + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import IAMCredentialsTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class IAMCredentialsRestInterceptor: + """Interceptor for IAMCredentials. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the IAMCredentialsRestTransport. + + .. code-block:: python + class MyCustomIAMCredentialsInterceptor(IAMCredentialsRestInterceptor): + def pre_generate_access_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_access_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_id_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_id_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_sign_blob(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_sign_blob(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_sign_jwt(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_sign_jwt(self, response): + logging.log(f"Received response: {response}") + return response + + transport = IAMCredentialsRestTransport(interceptor=MyCustomIAMCredentialsInterceptor()) + client = IAMCredentialsClient(transport=transport) + + + """ + + def pre_generate_access_token( + self, + request: common.GenerateAccessTokenRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[common.GenerateAccessTokenRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_access_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the IAMCredentials server. + """ + return request, metadata + + def post_generate_access_token( + self, response: common.GenerateAccessTokenResponse + ) -> common.GenerateAccessTokenResponse: + """Post-rpc interceptor for generate_access_token + + Override in a subclass to manipulate the response + after it is returned by the IAMCredentials server but before + it is returned to user code. + """ + return response + + def pre_generate_id_token( + self, + request: common.GenerateIdTokenRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[common.GenerateIdTokenRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_id_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the IAMCredentials server. + """ + return request, metadata + + def post_generate_id_token( + self, response: common.GenerateIdTokenResponse + ) -> common.GenerateIdTokenResponse: + """Post-rpc interceptor for generate_id_token + + Override in a subclass to manipulate the response + after it is returned by the IAMCredentials server but before + it is returned to user code. + """ + return response + + def pre_sign_blob( + self, request: common.SignBlobRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[common.SignBlobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for sign_blob + + Override in a subclass to manipulate the request or metadata + before they are sent to the IAMCredentials server. + """ + return request, metadata + + def post_sign_blob( + self, response: common.SignBlobResponse + ) -> common.SignBlobResponse: + """Post-rpc interceptor for sign_blob + + Override in a subclass to manipulate the response + after it is returned by the IAMCredentials server but before + it is returned to user code. + """ + return response + + def pre_sign_jwt( + self, request: common.SignJwtRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[common.SignJwtRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for sign_jwt + + Override in a subclass to manipulate the request or metadata + before they are sent to the IAMCredentials server. + """ + return request, metadata + + def post_sign_jwt(self, response: common.SignJwtResponse) -> common.SignJwtResponse: + """Post-rpc interceptor for sign_jwt + + Override in a subclass to manipulate the response + after it is returned by the IAMCredentials server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class IAMCredentialsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: IAMCredentialsRestInterceptor + + +class IAMCredentialsRestTransport(IAMCredentialsTransport): + """REST backend transport for IAMCredentials. + + A service account is a special type of Google account that + belongs to your application or a virtual machine (VM), instead + of to an individual end user. Your application assumes the + identity of the service account to call Google APIs, so that the + users aren't directly involved. + + Service account credentials are used to temporarily assume the + identity of the service account. Supported credential types + include OAuth 2.0 access tokens, OpenID Connect ID tokens, + self-signed JSON Web Tokens (JWTs), and more. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "iamcredentials.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[IAMCredentialsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + 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 + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or IAMCredentialsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GenerateAccessToken(IAMCredentialsRestStub): + def __hash__(self): + return hash("GenerateAccessToken") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: common.GenerateAccessTokenRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> common.GenerateAccessTokenResponse: + r"""Call the generate access token method over HTTP. + + Args: + request (~.common.GenerateAccessTokenRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.common.GenerateAccessTokenResponse: + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/serviceAccounts/*}:generateAccessToken", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_generate_access_token( + request, metadata + ) + pb_request = common.GenerateAccessTokenRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = common.GenerateAccessTokenResponse() + pb_resp = common.GenerateAccessTokenResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_access_token(resp) + return resp + + class _GenerateIdToken(IAMCredentialsRestStub): + def __hash__(self): + return hash("GenerateIdToken") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: common.GenerateIdTokenRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> common.GenerateIdTokenResponse: + r"""Call the generate id token method over HTTP. + + Args: + request (~.common.GenerateIdTokenRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.common.GenerateIdTokenResponse: + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/serviceAccounts/*}:generateIdToken", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_generate_id_token( + request, metadata + ) + pb_request = common.GenerateIdTokenRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = common.GenerateIdTokenResponse() + pb_resp = common.GenerateIdTokenResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_id_token(resp) + return resp + + class _SignBlob(IAMCredentialsRestStub): + def __hash__(self): + return hash("SignBlob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: common.SignBlobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> common.SignBlobResponse: + r"""Call the sign blob method over HTTP. + + Args: + request (~.common.SignBlobRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.common.SignBlobResponse: + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/serviceAccounts/*}:signBlob", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_sign_blob(request, metadata) + pb_request = common.SignBlobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = common.SignBlobResponse() + pb_resp = common.SignBlobResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_sign_blob(resp) + return resp + + class _SignJwt(IAMCredentialsRestStub): + def __hash__(self): + return hash("SignJwt") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: common.SignJwtRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> common.SignJwtResponse: + r"""Call the sign jwt method over HTTP. + + Args: + request (~.common.SignJwtRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.common.SignJwtResponse: + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/serviceAccounts/*}:signJwt", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_sign_jwt(request, metadata) + pb_request = common.SignJwtRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = common.SignJwtResponse() + pb_resp = common.SignJwtResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_sign_jwt(resp) + return resp + + @property + def generate_access_token( + self, + ) -> Callable[ + [common.GenerateAccessTokenRequest], common.GenerateAccessTokenResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_id_token( + self, + ) -> Callable[[common.GenerateIdTokenRequest], common.GenerateIdTokenResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateIdToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def sign_blob(self) -> Callable[[common.SignBlobRequest], common.SignBlobResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SignBlob(self._session, self._host, self._interceptor) # type: ignore + + @property + def sign_jwt(self) -> Callable[[common.SignJwtRequest], common.SignJwtResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SignJwt(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("IAMCredentialsRestTransport",) diff --git a/google/cloud/iam_v2/gapic_metadata.json b/google/cloud/iam_v2/gapic_metadata.json index 9179600..ccdb1fd 100644 --- a/google/cloud/iam_v2/gapic_metadata.json +++ b/google/cloud/iam_v2/gapic_metadata.json @@ -66,6 +66,36 @@ ] } } + }, + "rest": { + "libraryClient": "PoliciesClient", + "rpcs": { + "CreatePolicy": { + "methods": [ + "create_policy" + ] + }, + "DeletePolicy": { + "methods": [ + "delete_policy" + ] + }, + "GetPolicy": { + "methods": [ + "get_policy" + ] + }, + "ListPolicies": { + "methods": [ + "list_policies" + ] + }, + "UpdatePolicy": { + "methods": [ + "update_policy" + ] + } + } } } } diff --git a/google/cloud/iam_v2/services/policies/client.py b/google/cloud/iam_v2/services/policies/client.py index 22c063a..1b0748d 100644 --- a/google/cloud/iam_v2/services/policies/client.py +++ b/google/cloud/iam_v2/services/policies/client.py @@ -58,6 +58,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, PoliciesTransport from .transports.grpc import PoliciesGrpcTransport from .transports.grpc_asyncio import PoliciesGrpcAsyncIOTransport +from .transports.rest import PoliciesRestTransport class PoliciesClientMeta(type): @@ -71,6 +72,7 @@ class PoliciesClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[PoliciesTransport]] _transport_registry["grpc"] = PoliciesGrpcTransport _transport_registry["grpc_asyncio"] = PoliciesGrpcAsyncIOTransport + _transport_registry["rest"] = PoliciesRestTransport def get_transport_class( cls, diff --git a/google/cloud/iam_v2/services/policies/transports/__init__.py b/google/cloud/iam_v2/services/policies/transports/__init__.py index 1b3a90a..01bca2e 100644 --- a/google/cloud/iam_v2/services/policies/transports/__init__.py +++ b/google/cloud/iam_v2/services/policies/transports/__init__.py @@ -19,14 +19,18 @@ from .base import PoliciesTransport from .grpc import PoliciesGrpcTransport from .grpc_asyncio import PoliciesGrpcAsyncIOTransport +from .rest import PoliciesRestInterceptor, PoliciesRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[PoliciesTransport]] _transport_registry["grpc"] = PoliciesGrpcTransport _transport_registry["grpc_asyncio"] = PoliciesGrpcAsyncIOTransport +_transport_registry["rest"] = PoliciesRestTransport __all__ = ( "PoliciesTransport", "PoliciesGrpcTransport", "PoliciesGrpcAsyncIOTransport", + "PoliciesRestTransport", + "PoliciesRestInterceptor", ) diff --git a/google/cloud/iam_v2/services/policies/transports/rest.py b/google/cloud/iam_v2/services/policies/transports/rest.py new file mode 100644 index 0000000..bff84f5 --- /dev/null +++ b/google/cloud/iam_v2/services/policies/transports/rest.py @@ -0,0 +1,947 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import ( + gapic_v1, + operations_v1, + path_template, + rest_helpers, + rest_streaming, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.iam_v2.types import policy +from google.cloud.iam_v2.types import policy as gi_policy + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import PoliciesTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class PoliciesRestInterceptor: + """Interceptor for Policies. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the PoliciesRestTransport. + + .. code-block:: python + class MyCustomPoliciesInterceptor(PoliciesRestInterceptor): + def pre_create_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_policy(self, response): + logging.log(f"Received response: {response}") + return response + + transport = PoliciesRestTransport(interceptor=MyCustomPoliciesInterceptor()) + client = PoliciesClient(transport=transport) + + + """ + + def pre_create_policy( + self, + request: gi_policy.CreatePolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gi_policy.CreatePolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Policies server. + """ + return request, metadata + + def post_create_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_policy + + Override in a subclass to manipulate the response + after it is returned by the Policies server but before + it is returned to user code. + """ + return response + + def pre_delete_policy( + self, request: policy.DeletePolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[policy.DeletePolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Policies server. + """ + return request, metadata + + def post_delete_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_policy + + Override in a subclass to manipulate the response + after it is returned by the Policies server but before + it is returned to user code. + """ + return response + + def pre_get_policy( + self, request: policy.GetPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[policy.GetPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Policies server. + """ + return request, metadata + + def post_get_policy(self, response: policy.Policy) -> policy.Policy: + """Post-rpc interceptor for get_policy + + Override in a subclass to manipulate the response + after it is returned by the Policies server but before + it is returned to user code. + """ + return response + + def pre_list_policies( + self, request: policy.ListPoliciesRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[policy.ListPoliciesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the Policies server. + """ + return request, metadata + + def post_list_policies( + self, response: policy.ListPoliciesResponse + ) -> policy.ListPoliciesResponse: + """Post-rpc interceptor for list_policies + + Override in a subclass to manipulate the response + after it is returned by the Policies server but before + it is returned to user code. + """ + return response + + def pre_update_policy( + self, request: policy.UpdatePolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[policy.UpdatePolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Policies server. + """ + return request, metadata + + def post_update_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_policy + + Override in a subclass to manipulate the response + after it is returned by the Policies server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> operations_pb2.Operation: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Policies server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.GetOperationRequest + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Policies server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class PoliciesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: PoliciesRestInterceptor + + +class PoliciesRestTransport(PoliciesTransport): + """REST backend transport for Policies. + + An interface for managing Identity and Access Management + (IAM) policies. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[PoliciesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + 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 + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or PoliciesRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v2/{name=policies/*/*/*/operations/*}", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v2", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreatePolicy(PoliciesRestStub): + def __hash__(self): + return hash("CreatePolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: gi_policy.CreatePolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create policy method over HTTP. + + Args: + request (~.gi_policy.CreatePolicyRequest): + The request object. Request message for ``CreatePolicy``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=policies/*/*}", + "body": "policy", + }, + ] + request, metadata = self._interceptor.pre_create_policy(request, metadata) + pb_request = gi_policy.CreatePolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_policy(resp) + return resp + + class _DeletePolicy(PoliciesRestStub): + def __hash__(self): + return hash("DeletePolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: policy.DeletePolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete policy method over HTTP. + + Args: + request (~.policy.DeletePolicyRequest): + The request object. Request message for ``DeletePolicy``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=policies/*/*/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_policy(request, metadata) + pb_request = policy.DeletePolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_policy(resp) + return resp + + class _GetPolicy(PoliciesRestStub): + def __hash__(self): + return hash("GetPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: policy.GetPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Call the get policy method over HTTP. + + Args: + request (~.policy.GetPolicyRequest): + The request object. Request message for ``GetPolicy``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Data for an IAM policy. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=policies/*/*/*}", + }, + ] + request, metadata = self._interceptor.pre_get_policy(request, metadata) + pb_request = policy.GetPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy.Policy() + pb_resp = policy.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_policy(resp) + return resp + + class _ListPolicies(PoliciesRestStub): + def __hash__(self): + return hash("ListPolicies") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: policy.ListPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.ListPoliciesResponse: + r"""Call the list policies method over HTTP. + + Args: + request (~.policy.ListPoliciesRequest): + The request object. Request message for ``ListPolicies``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.ListPoliciesResponse: + Response message for ``ListPolicies``. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=policies/*/*}", + }, + ] + request, metadata = self._interceptor.pre_list_policies(request, metadata) + pb_request = policy.ListPoliciesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy.ListPoliciesResponse() + pb_resp = policy.ListPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_policies(resp) + return resp + + class _UpdatePolicy(PoliciesRestStub): + def __hash__(self): + return hash("UpdatePolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: policy.UpdatePolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update policy method over HTTP. + + Args: + request (~.policy.UpdatePolicyRequest): + The request object. Request message for ``UpdatePolicy``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "put", + "uri": "/v2/{policy.name=policies/*/*/*}", + "body": "policy", + }, + ] + request, metadata = self._interceptor.pre_update_policy(request, metadata) + pb_request = policy.UpdatePolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_policy(resp) + return resp + + @property + def create_policy( + self, + ) -> Callable[[gi_policy.CreatePolicyRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreatePolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_policy( + self, + ) -> Callable[[policy.DeletePolicyRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeletePolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_policy(self) -> Callable[[policy.GetPolicyRequest], policy.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_policies( + self, + ) -> Callable[[policy.ListPoliciesRequest], policy.ListPoliciesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPolicies(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_policy( + self, + ) -> Callable[[policy.UpdatePolicyRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdatePolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(PoliciesRestStub): + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=policies/*/*/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("PoliciesRestTransport",) diff --git a/tests/unit/gapic/iam_credentials_v1/test_iam_credentials.py b/tests/unit/gapic/iam_credentials_v1/test_iam_credentials.py index 1bb7d75..35bc4fa 100644 --- a/tests/unit/gapic/iam_credentials_v1/test_iam_credentials.py +++ b/tests/unit/gapic/iam_credentials_v1/test_iam_credentials.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -32,12 +34,15 @@ from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.iam_credentials_v1.services.iam_credentials import ( IAMCredentialsAsyncClient, @@ -96,6 +101,7 @@ def test__get_default_mtls_endpoint(): [ (IAMCredentialsClient, "grpc"), (IAMCredentialsAsyncClient, "grpc_asyncio"), + (IAMCredentialsClient, "rest"), ], ) def test_iam_credentials_client_from_service_account_info(client_class, transport_name): @@ -109,7 +115,11 @@ def test_iam_credentials_client_from_service_account_info(client_class, transpor assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("iamcredentials.googleapis.com:443") + assert client.transport._host == ( + "iamcredentials.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://iamcredentials.googleapis.com" + ) @pytest.mark.parametrize( @@ -117,6 +127,7 @@ def test_iam_credentials_client_from_service_account_info(client_class, transpor [ (transports.IAMCredentialsGrpcTransport, "grpc"), (transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.IAMCredentialsRestTransport, "rest"), ], ) def test_iam_credentials_client_service_account_always_use_jwt( @@ -142,6 +153,7 @@ def test_iam_credentials_client_service_account_always_use_jwt( [ (IAMCredentialsClient, "grpc"), (IAMCredentialsAsyncClient, "grpc_asyncio"), + (IAMCredentialsClient, "rest"), ], ) def test_iam_credentials_client_from_service_account_file(client_class, transport_name): @@ -162,13 +174,18 @@ def test_iam_credentials_client_from_service_account_file(client_class, transpor assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("iamcredentials.googleapis.com:443") + assert client.transport._host == ( + "iamcredentials.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://iamcredentials.googleapis.com" + ) def test_iam_credentials_client_get_transport_class(): transport = IAMCredentialsClient.get_transport_class() available_transports = [ transports.IAMCredentialsGrpcTransport, + transports.IAMCredentialsRestTransport, ] assert transport in available_transports @@ -185,6 +202,7 @@ def test_iam_credentials_client_get_transport_class(): transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio", ), + (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest"), ], ) @mock.patch.object( @@ -330,6 +348,8 @@ def test_iam_credentials_client_client_options( "grpc_asyncio", "false", ), + (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest", "true"), + (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -529,6 +549,7 @@ def test_iam_credentials_client_get_mtls_endpoint_and_cert_source(client_class): transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio", ), + (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest"), ], ) def test_iam_credentials_client_client_options_scopes( @@ -569,6 +590,7 @@ def test_iam_credentials_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest", None), ], ) def test_iam_credentials_client_client_options_credentials_file( @@ -1745,6 +1767,1144 @@ async def test_sign_jwt_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + common.GenerateAccessTokenRequest, + dict, + ], +) +def test_generate_access_token_rest(request_type): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/serviceAccounts/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = common.GenerateAccessTokenResponse( + access_token="access_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = common.GenerateAccessTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.generate_access_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, common.GenerateAccessTokenResponse) + assert response.access_token == "access_token_value" + + +def test_generate_access_token_rest_required_fields( + request_type=common.GenerateAccessTokenRequest, +): + transport_class = transports.IAMCredentialsRestTransport + + request_init = {} + request_init["name"] = "" + request_init["scope"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_access_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["scope"] = "scope_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_access_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "scope" in jsonified_request + assert jsonified_request["scope"] == "scope_value" + + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = common.GenerateAccessTokenResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = common.GenerateAccessTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.generate_access_token(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_generate_access_token_rest_unset_required_fields(): + transport = transports.IAMCredentialsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.generate_access_token._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "scope", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_access_token_rest_interceptors(null_interceptor): + transport = transports.IAMCredentialsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.IAMCredentialsRestInterceptor(), + ) + client = IAMCredentialsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.IAMCredentialsRestInterceptor, "post_generate_access_token" + ) as post, mock.patch.object( + transports.IAMCredentialsRestInterceptor, "pre_generate_access_token" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = common.GenerateAccessTokenRequest.pb( + common.GenerateAccessTokenRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = common.GenerateAccessTokenResponse.to_json( + common.GenerateAccessTokenResponse() + ) + + request = common.GenerateAccessTokenRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = common.GenerateAccessTokenResponse() + + client.generate_access_token( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_access_token_rest_bad_request( + transport: str = "rest", request_type=common.GenerateAccessTokenRequest +): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/serviceAccounts/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.generate_access_token(request) + + +def test_generate_access_token_rest_flattened(): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = common.GenerateAccessTokenResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/serviceAccounts/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + delegates=["delegates_value"], + scope=["scope_value"], + lifetime=duration_pb2.Duration(seconds=751), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = common.GenerateAccessTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.generate_access_token(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/serviceAccounts/*}:generateAccessToken" + % client.transport._host, + args[1], + ) + + +def test_generate_access_token_rest_flattened_error(transport: str = "rest"): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_access_token( + common.GenerateAccessTokenRequest(), + name="name_value", + delegates=["delegates_value"], + scope=["scope_value"], + lifetime=duration_pb2.Duration(seconds=751), + ) + + +def test_generate_access_token_rest_error(): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + common.GenerateIdTokenRequest, + dict, + ], +) +def test_generate_id_token_rest(request_type): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/serviceAccounts/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = common.GenerateIdTokenResponse( + token="token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = common.GenerateIdTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.generate_id_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, common.GenerateIdTokenResponse) + assert response.token == "token_value" + + +def test_generate_id_token_rest_required_fields( + request_type=common.GenerateIdTokenRequest, +): + transport_class = transports.IAMCredentialsRestTransport + + request_init = {} + request_init["name"] = "" + request_init["audience"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_id_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["audience"] = "audience_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_id_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "audience" in jsonified_request + assert jsonified_request["audience"] == "audience_value" + + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = common.GenerateIdTokenResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = common.GenerateIdTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.generate_id_token(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_generate_id_token_rest_unset_required_fields(): + transport = transports.IAMCredentialsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.generate_id_token._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "audience", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_id_token_rest_interceptors(null_interceptor): + transport = transports.IAMCredentialsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.IAMCredentialsRestInterceptor(), + ) + client = IAMCredentialsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.IAMCredentialsRestInterceptor, "post_generate_id_token" + ) as post, mock.patch.object( + transports.IAMCredentialsRestInterceptor, "pre_generate_id_token" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = common.GenerateIdTokenRequest.pb(common.GenerateIdTokenRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = common.GenerateIdTokenResponse.to_json( + common.GenerateIdTokenResponse() + ) + + request = common.GenerateIdTokenRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = common.GenerateIdTokenResponse() + + client.generate_id_token( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_id_token_rest_bad_request( + transport: str = "rest", request_type=common.GenerateIdTokenRequest +): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/serviceAccounts/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.generate_id_token(request) + + +def test_generate_id_token_rest_flattened(): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = common.GenerateIdTokenResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/serviceAccounts/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + delegates=["delegates_value"], + audience="audience_value", + include_email=True, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = common.GenerateIdTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.generate_id_token(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/serviceAccounts/*}:generateIdToken" + % client.transport._host, + args[1], + ) + + +def test_generate_id_token_rest_flattened_error(transport: str = "rest"): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_id_token( + common.GenerateIdTokenRequest(), + name="name_value", + delegates=["delegates_value"], + audience="audience_value", + include_email=True, + ) + + +def test_generate_id_token_rest_error(): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + common.SignBlobRequest, + dict, + ], +) +def test_sign_blob_rest(request_type): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/serviceAccounts/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = common.SignBlobResponse( + key_id="key_id_value", + signed_blob=b"signed_blob_blob", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = common.SignBlobResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.sign_blob(request) + + # 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" + + +def test_sign_blob_rest_required_fields(request_type=common.SignBlobRequest): + transport_class = transports.IAMCredentialsRestTransport + + request_init = {} + request_init["name"] = "" + request_init["payload"] = b"" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).sign_blob._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["payload"] = b"payload_blob" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).sign_blob._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "payload" in jsonified_request + assert jsonified_request["payload"] == b"payload_blob" + + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = common.SignBlobResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = common.SignBlobResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.sign_blob(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_sign_blob_rest_unset_required_fields(): + transport = transports.IAMCredentialsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.sign_blob._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "payload", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_sign_blob_rest_interceptors(null_interceptor): + transport = transports.IAMCredentialsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.IAMCredentialsRestInterceptor(), + ) + client = IAMCredentialsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.IAMCredentialsRestInterceptor, "post_sign_blob" + ) as post, mock.patch.object( + transports.IAMCredentialsRestInterceptor, "pre_sign_blob" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = common.SignBlobRequest.pb(common.SignBlobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = common.SignBlobResponse.to_json( + common.SignBlobResponse() + ) + + request = common.SignBlobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = common.SignBlobResponse() + + client.sign_blob( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_sign_blob_rest_bad_request( + transport: str = "rest", request_type=common.SignBlobRequest +): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/serviceAccounts/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.sign_blob(request) + + +def test_sign_blob_rest_flattened(): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = common.SignBlobResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/serviceAccounts/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + delegates=["delegates_value"], + payload=b"payload_blob", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = common.SignBlobResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.sign_blob(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/serviceAccounts/*}:signBlob" + % client.transport._host, + args[1], + ) + + +def test_sign_blob_rest_flattened_error(transport: str = "rest"): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.sign_blob( + common.SignBlobRequest(), + name="name_value", + delegates=["delegates_value"], + payload=b"payload_blob", + ) + + +def test_sign_blob_rest_error(): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + common.SignJwtRequest, + dict, + ], +) +def test_sign_jwt_rest(request_type): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/serviceAccounts/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = common.SignJwtResponse( + key_id="key_id_value", + signed_jwt="signed_jwt_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = common.SignJwtResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.sign_jwt(request) + + # 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" + + +def test_sign_jwt_rest_required_fields(request_type=common.SignJwtRequest): + transport_class = transports.IAMCredentialsRestTransport + + request_init = {} + request_init["name"] = "" + request_init["payload"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).sign_jwt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["payload"] = "payload_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).sign_jwt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "payload" in jsonified_request + assert jsonified_request["payload"] == "payload_value" + + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = common.SignJwtResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = common.SignJwtResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.sign_jwt(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_sign_jwt_rest_unset_required_fields(): + transport = transports.IAMCredentialsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.sign_jwt._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "payload", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_sign_jwt_rest_interceptors(null_interceptor): + transport = transports.IAMCredentialsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.IAMCredentialsRestInterceptor(), + ) + client = IAMCredentialsClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.IAMCredentialsRestInterceptor, "post_sign_jwt" + ) as post, mock.patch.object( + transports.IAMCredentialsRestInterceptor, "pre_sign_jwt" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = common.SignJwtRequest.pb(common.SignJwtRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = common.SignJwtResponse.to_json( + common.SignJwtResponse() + ) + + request = common.SignJwtRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = common.SignJwtResponse() + + client.sign_jwt( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_sign_jwt_rest_bad_request( + transport: str = "rest", request_type=common.SignJwtRequest +): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/serviceAccounts/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.sign_jwt(request) + + +def test_sign_jwt_rest_flattened(): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = common.SignJwtResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/serviceAccounts/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + delegates=["delegates_value"], + payload="payload_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = common.SignJwtResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.sign_jwt(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/serviceAccounts/*}:signJwt" + % client.transport._host, + args[1], + ) + + +def test_sign_jwt_rest_flattened_error(transport: str = "rest"): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.sign_jwt( + common.SignJwtRequest(), + name="name_value", + delegates=["delegates_value"], + payload="payload_value", + ) + + +def test_sign_jwt_rest_error(): + client = IAMCredentialsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.IAMCredentialsGrpcTransport( @@ -1826,6 +2986,7 @@ def test_transport_get_channel(): [ transports.IAMCredentialsGrpcTransport, transports.IAMCredentialsGrpcAsyncIOTransport, + transports.IAMCredentialsRestTransport, ], ) def test_transport_adc(transport_class): @@ -1840,6 +3001,7 @@ def test_transport_adc(transport_class): "transport_name", [ "grpc", + "rest", ], ) def test_transport_kind(transport_name): @@ -1972,6 +3134,7 @@ def test_iam_credentials_transport_auth_adc(transport_class): [ transports.IAMCredentialsGrpcTransport, transports.IAMCredentialsGrpcAsyncIOTransport, + transports.IAMCredentialsRestTransport, ], ) def test_iam_credentials_transport_auth_gdch_credentials(transport_class): @@ -2069,11 +3232,23 @@ def test_iam_credentials_grpc_transport_client_cert_source_for_mtls(transport_cl ) +def test_iam_credentials_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.IAMCredentialsRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_iam_credentials_host_no_port(transport_name): @@ -2084,7 +3259,11 @@ def test_iam_credentials_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("iamcredentials.googleapis.com:443") + assert client.transport._host == ( + "iamcredentials.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://iamcredentials.googleapis.com" + ) @pytest.mark.parametrize( @@ -2092,6 +3271,7 @@ def test_iam_credentials_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_iam_credentials_host_with_port(transport_name): @@ -2102,7 +3282,42 @@ def test_iam_credentials_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("iamcredentials.googleapis.com:8000") + assert client.transport._host == ( + "iamcredentials.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://iamcredentials.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_iam_credentials_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = IAMCredentialsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = IAMCredentialsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.generate_access_token._session + session2 = client2.transport.generate_access_token._session + assert session1 != session2 + session1 = client1.transport.generate_id_token._session + session2 = client2.transport.generate_id_token._session + assert session1 != session2 + session1 = client1.transport.sign_blob._session + session2 = client2.transport.sign_blob._session + assert session1 != session2 + session1 = client1.transport.sign_jwt._session + session2 = client2.transport.sign_jwt._session + assert session1 != session2 def test_iam_credentials_grpc_transport_channel(): @@ -2396,6 +3611,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -2413,6 +3629,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/iam_v2/test_policies.py b/tests/unit/gapic/iam_v2/test_policies.py index f053031..6d6c471 100644 --- a/tests/unit/gapic/iam_v2/test_policies.py +++ b/tests/unit/gapic/iam_v2/test_policies.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import ( @@ -41,6 +43,7 @@ from google.auth.exceptions import MutualTLSChannelError from google.longrunning import operations_pb2 from google.oauth2 import service_account +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore from google.type import expr_pb2 # type: ignore import grpc @@ -48,6 +51,8 @@ from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.iam_v2.services.policies import ( PoliciesAsyncClient, @@ -104,6 +109,7 @@ def test__get_default_mtls_endpoint(): [ (PoliciesClient, "grpc"), (PoliciesAsyncClient, "grpc_asyncio"), + (PoliciesClient, "rest"), ], ) def test_policies_client_from_service_account_info(client_class, transport_name): @@ -117,7 +123,11 @@ def test_policies_client_from_service_account_info(client_class, transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("iam.googleapis.com:443") + assert client.transport._host == ( + "iam.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://iam.googleapis.com" + ) @pytest.mark.parametrize( @@ -125,6 +135,7 @@ def test_policies_client_from_service_account_info(client_class, transport_name) [ (transports.PoliciesGrpcTransport, "grpc"), (transports.PoliciesGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.PoliciesRestTransport, "rest"), ], ) def test_policies_client_service_account_always_use_jwt( @@ -150,6 +161,7 @@ def test_policies_client_service_account_always_use_jwt( [ (PoliciesClient, "grpc"), (PoliciesAsyncClient, "grpc_asyncio"), + (PoliciesClient, "rest"), ], ) def test_policies_client_from_service_account_file(client_class, transport_name): @@ -170,13 +182,18 @@ def test_policies_client_from_service_account_file(client_class, transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("iam.googleapis.com:443") + assert client.transport._host == ( + "iam.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://iam.googleapis.com" + ) def test_policies_client_get_transport_class(): transport = PoliciesClient.get_transport_class() available_transports = [ transports.PoliciesGrpcTransport, + transports.PoliciesRestTransport, ] assert transport in available_transports @@ -189,6 +206,7 @@ def test_policies_client_get_transport_class(): [ (PoliciesClient, transports.PoliciesGrpcTransport, "grpc"), (PoliciesAsyncClient, transports.PoliciesGrpcAsyncIOTransport, "grpc_asyncio"), + (PoliciesClient, transports.PoliciesRestTransport, "rest"), ], ) @mock.patch.object( @@ -330,6 +348,8 @@ def test_policies_client_client_options(client_class, transport_class, transport "grpc_asyncio", "false", ), + (PoliciesClient, transports.PoliciesRestTransport, "rest", "true"), + (PoliciesClient, transports.PoliciesRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -519,6 +539,7 @@ def test_policies_client_get_mtls_endpoint_and_cert_source(client_class): [ (PoliciesClient, transports.PoliciesGrpcTransport, "grpc"), (PoliciesAsyncClient, transports.PoliciesGrpcAsyncIOTransport, "grpc_asyncio"), + (PoliciesClient, transports.PoliciesRestTransport, "rest"), ], ) def test_policies_client_client_options_scopes( @@ -554,6 +575,7 @@ def test_policies_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (PoliciesClient, transports.PoliciesRestTransport, "rest", None), ], ) def test_policies_client_client_options_credentials_file( @@ -1943,138 +1965,1627 @@ async def test_delete_policy_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PoliciesGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + policy.ListPoliciesRequest, + dict, + ], +) +def test_list_policies_rest(request_type): + client = PoliciesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = PoliciesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {"parent": "policies/sample1/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy.ListPoliciesResponse( + next_page_token="next_page_token_value", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.PoliciesGrpcTransport( + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = policy.ListPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPoliciesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_policies_rest_required_fields(request_type=policy.ListPoliciesRequest): + transport_class = transports.PoliciesRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_policies._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_policies._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = PoliciesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = PoliciesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy.ListPoliciesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = policy.ListPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_policies(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_policies_rest_unset_required_fields(): + transport = transports.PoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_policies._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) ) + & set(("parent",)) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.PoliciesGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_policies_rest_interceptors(null_interceptor): + transport = transports.PoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PoliciesRestInterceptor(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PoliciesClient( - client_options=options, - transport=transport, + client = PoliciesClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.PoliciesRestInterceptor, "post_list_policies" + ) as post, mock.patch.object( + transports.PoliciesRestInterceptor, "pre_list_policies" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = policy.ListPoliciesRequest.pb(policy.ListPoliciesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = policy.ListPoliciesResponse.to_json( + policy.ListPoliciesResponse() ) - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PoliciesClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + request = policy.ListPoliciesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy.ListPoliciesResponse() + + client.list_policies( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # It is an error to provide scopes and a transport instance. - transport = transports.PoliciesGrpcTransport( + pre.assert_called_once() + post.assert_called_once() + + +def test_list_policies_rest_bad_request( + transport: str = "rest", request_type=policy.ListPoliciesRequest +): + client = PoliciesClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - with pytest.raises(ValueError): - client = PoliciesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # send a request that will satisfy transcoding + request_init = {"parent": "policies/sample1/sample2"} + request = request_type(**request_init) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PoliciesGrpcTransport( + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_policies(request) + + +def test_list_policies_rest_flattened(): + client = PoliciesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = PoliciesClient(transport=transport) - assert client.transport is transport + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy.ListPoliciesResponse() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PoliciesGrpcTransport( + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "policies/sample1/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = policy.ListPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_policies(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=policies/*/*}" % client.transport._host, args[1] + ) + + +def test_list_policies_rest_flattened_error(transport: str = "rest"): + client = PoliciesClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel - transport = transports.PoliciesGrpcAsyncIOTransport( + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_policies( + policy.ListPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_policies_rest_pager(transport: str = "rest"): + client = PoliciesClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + policy.ListPoliciesResponse( + policies=[ + policy.Policy(), + policy.Policy(), + policy.Policy(), + ], + next_page_token="abc", + ), + policy.ListPoliciesResponse( + policies=[], + next_page_token="def", + ), + policy.ListPoliciesResponse( + policies=[ + policy.Policy(), + ], + next_page_token="ghi", + ), + policy.ListPoliciesResponse( + policies=[ + policy.Policy(), + policy.Policy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(policy.ListPoliciesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values -@pytest.mark.parametrize( - "transport_class", - [ - transports.PoliciesGrpcTransport, - transports.PoliciesGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + sample_request = {"parent": "policies/sample1/sample2"} + + pager = client.list_policies(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, policy.Policy) for i in results) + + pages = list(client.list_policies(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + policy.GetPolicyRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = PoliciesClient.get_transport_class(transport_name)( +def test_get_policy_rest(request_type): + client = PoliciesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"name": "policies/sample1/sample2/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy.Policy( + name="name_value", + uid="uid_value", + kind="kind_value", + display_name="display_name_value", + etag="etag_value", + managing_authority="managing_authority_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = policy.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.kind == "kind_value" + assert response.display_name == "display_name_value" + assert response.etag == "etag_value" + assert response.managing_authority == "managing_authority_value" + + +def test_get_policy_rest_required_fields(request_type=policy.GetPolicyRequest): + transport_class = transports.PoliciesRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = PoliciesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.PoliciesGrpcTransport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = policy.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_policy_rest_unset_required_fields(): + transport = transports.PoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.get_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_policies_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PoliciesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_policy_rest_interceptors(null_interceptor): + transport = transports.PoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PoliciesRestInterceptor(), + ) + client = PoliciesClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.PoliciesRestInterceptor, "post_get_policy" + ) as post, mock.patch.object( + transports.PoliciesRestInterceptor, "pre_get_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = policy.GetPolicyRequest.pb(policy.GetPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = policy.Policy.to_json(policy.Policy()) + + request = policy.GetPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy.Policy() -def test_policies_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.iam_v2.services.policies.transports.PoliciesTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.PoliciesTransport( - credentials=ga_credentials.AnonymousCredentials(), + client.get_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_policy_rest_bad_request( + transport: str = "rest", request_type=policy.GetPolicyRequest +): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "policies/sample1/sample2/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_policy(request) + + +def test_get_policy_rest_flattened(): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "policies/sample1/sample2/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = policy.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=policies/*/*/*}" % client.transport._host, args[1] + ) + + +def test_get_policy_rest_flattened_error(transport: str = "rest"): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_policy( + policy.GetPolicyRequest(), + name="name_value", + ) + + +def test_get_policy_rest_error(): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gi_policy.CreatePolicyRequest, + dict, + ], +) +def test_create_policy_rest(request_type): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "policies/sample1/sample2"} + request_init["policy"] = { + "name": "name_value", + "uid": "uid_value", + "kind": "kind_value", + "display_name": "display_name_value", + "annotations": {}, + "etag": "etag_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "rules": [ + { + "deny_rule": { + "denied_principals": [ + "denied_principals_value1", + "denied_principals_value2", + ], + "exception_principals": [ + "exception_principals_value1", + "exception_principals_value2", + ], + "denied_permissions": [ + "denied_permissions_value1", + "denied_permissions_value2", + ], + "exception_permissions": [ + "exception_permissions_value1", + "exception_permissions_value2", + ], + "denial_condition": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + }, + "description": "description_value", + } + ], + "managing_authority": "managing_authority_value", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_policy(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_policy_rest_required_fields(request_type=gi_policy.CreatePolicyRequest): + transport_class = transports.PoliciesRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("policy_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_policy_rest_unset_required_fields(): + transport = transports.PoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("policyId",)) + & set( + ( + "parent", + "policy", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_policy_rest_interceptors(null_interceptor): + transport = transports.PoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PoliciesRestInterceptor(), + ) + client = PoliciesClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.PoliciesRestInterceptor, "post_create_policy" + ) as post, mock.patch.object( + transports.PoliciesRestInterceptor, "pre_create_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gi_policy.CreatePolicyRequest.pb(gi_policy.CreatePolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = gi_policy.CreatePolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_policy_rest_bad_request( + transport: str = "rest", request_type=gi_policy.CreatePolicyRequest +): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "policies/sample1/sample2"} + request_init["policy"] = { + "name": "name_value", + "uid": "uid_value", + "kind": "kind_value", + "display_name": "display_name_value", + "annotations": {}, + "etag": "etag_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "rules": [ + { + "deny_rule": { + "denied_principals": [ + "denied_principals_value1", + "denied_principals_value2", + ], + "exception_principals": [ + "exception_principals_value1", + "exception_principals_value2", + ], + "denied_permissions": [ + "denied_permissions_value1", + "denied_permissions_value2", + ], + "exception_permissions": [ + "exception_permissions_value1", + "exception_permissions_value2", + ], + "denial_condition": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + }, + "description": "description_value", + } + ], + "managing_authority": "managing_authority_value", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_policy(request) + + +def test_create_policy_rest_flattened(): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "policies/sample1/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + policy=gi_policy.Policy(name="name_value"), + policy_id="policy_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=policies/*/*}" % client.transport._host, args[1] + ) + + +def test_create_policy_rest_flattened_error(transport: str = "rest"): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_policy( + gi_policy.CreatePolicyRequest(), + parent="parent_value", + policy=gi_policy.Policy(name="name_value"), + policy_id="policy_id_value", + ) + + +def test_create_policy_rest_error(): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + policy.UpdatePolicyRequest, + dict, + ], +) +def test_update_policy_rest(request_type): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"policy": {"name": "policies/sample1/sample2/sample3"}} + request_init["policy"] = { + "name": "policies/sample1/sample2/sample3", + "uid": "uid_value", + "kind": "kind_value", + "display_name": "display_name_value", + "annotations": {}, + "etag": "etag_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "rules": [ + { + "deny_rule": { + "denied_principals": [ + "denied_principals_value1", + "denied_principals_value2", + ], + "exception_principals": [ + "exception_principals_value1", + "exception_principals_value2", + ], + "denied_permissions": [ + "denied_permissions_value1", + "denied_permissions_value2", + ], + "exception_permissions": [ + "exception_permissions_value1", + "exception_permissions_value2", + ], + "denial_condition": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + }, + "description": "description_value", + } + ], + "managing_authority": "managing_authority_value", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_policy(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_policy_rest_required_fields(request_type=policy.UpdatePolicyRequest): + transport_class = transports.PoliciesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "put", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_policy_rest_unset_required_fields(): + transport = transports.PoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("policy",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_policy_rest_interceptors(null_interceptor): + transport = transports.PoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PoliciesRestInterceptor(), + ) + client = PoliciesClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.PoliciesRestInterceptor, "post_update_policy" + ) as post, mock.patch.object( + transports.PoliciesRestInterceptor, "pre_update_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = policy.UpdatePolicyRequest.pb(policy.UpdatePolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = policy.UpdatePolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_policy_rest_bad_request( + transport: str = "rest", request_type=policy.UpdatePolicyRequest +): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"policy": {"name": "policies/sample1/sample2/sample3"}} + request_init["policy"] = { + "name": "policies/sample1/sample2/sample3", + "uid": "uid_value", + "kind": "kind_value", + "display_name": "display_name_value", + "annotations": {}, + "etag": "etag_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "rules": [ + { + "deny_rule": { + "denied_principals": [ + "denied_principals_value1", + "denied_principals_value2", + ], + "exception_principals": [ + "exception_principals_value1", + "exception_principals_value2", + ], + "denied_permissions": [ + "denied_permissions_value1", + "denied_permissions_value2", + ], + "exception_permissions": [ + "exception_permissions_value1", + "exception_permissions_value2", + ], + "denial_condition": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + }, + "description": "description_value", + } + ], + "managing_authority": "managing_authority_value", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_policy(request) + + +def test_update_policy_rest_error(): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + policy.DeletePolicyRequest, + dict, + ], +) +def test_delete_policy_rest(request_type): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "policies/sample1/sample2/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_policy(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_policy_rest_required_fields(request_type=policy.DeletePolicyRequest): + transport_class = transports.PoliciesRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_policy_rest_unset_required_fields(): + transport = transports.PoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag",)) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_policy_rest_interceptors(null_interceptor): + transport = transports.PoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PoliciesRestInterceptor(), + ) + client = PoliciesClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.PoliciesRestInterceptor, "post_delete_policy" + ) as post, mock.patch.object( + transports.PoliciesRestInterceptor, "pre_delete_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = policy.DeletePolicyRequest.pb(policy.DeletePolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = policy.DeletePolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_policy_rest_bad_request( + transport: str = "rest", request_type=policy.DeletePolicyRequest +): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "policies/sample1/sample2/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_policy(request) + + +def test_delete_policy_rest_flattened(): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "policies/sample1/sample2/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=policies/*/*/*}" % client.transport._host, args[1] + ) + + +def test_delete_policy_rest_flattened_error(transport: str = "rest"): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_policy( + policy.DeletePolicyRequest(), + name="name_value", + ) + + +def test_delete_policy_rest_error(): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PoliciesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PoliciesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PoliciesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PoliciesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PoliciesClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PoliciesClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PoliciesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PoliciesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PoliciesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PoliciesClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PoliciesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PoliciesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PoliciesGrpcTransport, + transports.PoliciesGrpcAsyncIOTransport, + transports.PoliciesRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = PoliciesClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PoliciesGrpcTransport, + ) + + +def test_policies_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PoliciesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_policies_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.iam_v2.services.policies.transports.PoliciesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.PoliciesTransport( + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2177,6 +3688,7 @@ def test_policies_transport_auth_adc(transport_class): [ transports.PoliciesGrpcTransport, transports.PoliciesGrpcAsyncIOTransport, + transports.PoliciesRestTransport, ], ) def test_policies_transport_auth_gdch_credentials(transport_class): @@ -2271,11 +3783,40 @@ def test_policies_grpc_transport_client_cert_source_for_mtls(transport_class): ) +def test_policies_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.PoliciesRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_policies_rest_lro_client(): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_policies_host_no_port(transport_name): @@ -2284,7 +3825,11 @@ def test_policies_host_no_port(transport_name): client_options=client_options.ClientOptions(api_endpoint="iam.googleapis.com"), transport=transport_name, ) - assert client.transport._host == ("iam.googleapis.com:443") + assert client.transport._host == ( + "iam.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://iam.googleapis.com" + ) @pytest.mark.parametrize( @@ -2292,6 +3837,7 @@ def test_policies_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_policies_host_with_port(transport_name): @@ -2302,7 +3848,45 @@ def test_policies_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("iam.googleapis.com:8000") + assert client.transport._host == ( + "iam.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://iam.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_policies_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = PoliciesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = PoliciesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_policies._session + session2 = client2.transport.list_policies._session + assert session1 != session2 + session1 = client1.transport.get_policy._session + session2 = client2.transport.get_policy._session + assert session1 != session2 + session1 = client1.transport.create_policy._session + session2 = client2.transport.create_policy._session + assert session1 != session2 + session1 = client1.transport.update_policy._session + session2 = client2.transport.update_policy._session + assert session1 != session2 + session1 = client1.transport.delete_policy._session + session2 = client2.transport.delete_policy._session + assert session1 != session2 def test_policies_grpc_transport_channel(): @@ -2597,6 +4181,64 @@ async def test_transport_close_async(): close.assert_called_once() +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "policies/sample1/sample2/sample3/operations/sample4"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = PoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "policies/sample1/sample2/sample3/operations/sample4"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + def test_get_operation(transport: str = "grpc"): client = PoliciesClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2744,6 +4386,7 @@ async def test_get_operation_from_dict_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -2761,6 +4404,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: