From 52d228011c8102e50a412e342d9b4ec7fecc5c05 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 9 Feb 2023 06:33:39 -0500 Subject: [PATCH] feat: enable "rest" transport in Python for services supporting numeric enums (#202) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: enable "rest" transport in Python for services supporting numeric enums PiperOrigin-RevId: 508143576 Source-Link: https://github.com/googleapis/googleapis/commit/7a702a989db3b413f39ff8994ca53fb38b6928c2 Source-Link: https://github.com/googleapis/googleapis-gen/commit/6ad1279c0e7aa787ac6b66c9fd4a210692edffcd Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNmFkMTI3OWMwZTdhYTc4N2FjNmI2NmM5ZmQ0YTIxMDY5MmVkZmZjZCJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot --- .../cloud/apigateway_v1/gapic_metadata.json | 80 + .../services/api_gateway_service/client.py | 2 + .../transports/__init__.py | 4 + .../api_gateway_service/transports/rest.py | 2197 ++++++++ .../apigateway_v1/test_api_gateway_service.py | 4753 ++++++++++++++++- 5 files changed, 6951 insertions(+), 85 deletions(-) create mode 100644 packages/google-cloud-api-gateway/google/cloud/apigateway_v1/services/api_gateway_service/transports/rest.py diff --git a/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/gapic_metadata.json b/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/gapic_metadata.json index 2e0703607d44..cb0a3e0b730f 100644 --- a/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/gapic_metadata.json +++ b/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/gapic_metadata.json @@ -166,6 +166,86 @@ ] } } + }, + "rest": { + "libraryClient": "ApiGatewayServiceClient", + "rpcs": { + "CreateApi": { + "methods": [ + "create_api" + ] + }, + "CreateApiConfig": { + "methods": [ + "create_api_config" + ] + }, + "CreateGateway": { + "methods": [ + "create_gateway" + ] + }, + "DeleteApi": { + "methods": [ + "delete_api" + ] + }, + "DeleteApiConfig": { + "methods": [ + "delete_api_config" + ] + }, + "DeleteGateway": { + "methods": [ + "delete_gateway" + ] + }, + "GetApi": { + "methods": [ + "get_api" + ] + }, + "GetApiConfig": { + "methods": [ + "get_api_config" + ] + }, + "GetGateway": { + "methods": [ + "get_gateway" + ] + }, + "ListApiConfigs": { + "methods": [ + "list_api_configs" + ] + }, + "ListApis": { + "methods": [ + "list_apis" + ] + }, + "ListGateways": { + "methods": [ + "list_gateways" + ] + }, + "UpdateApi": { + "methods": [ + "update_api" + ] + }, + "UpdateApiConfig": { + "methods": [ + "update_api_config" + ] + }, + "UpdateGateway": { + "methods": [ + "update_gateway" + ] + } + } } } } diff --git a/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/services/api_gateway_service/client.py b/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/services/api_gateway_service/client.py index bbc0c584927e..3ccaa8f14d22 100644 --- a/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/services/api_gateway_service/client.py +++ b/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/services/api_gateway_service/client.py @@ -58,6 +58,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, ApiGatewayServiceTransport from .transports.grpc import ApiGatewayServiceGrpcTransport from .transports.grpc_asyncio import ApiGatewayServiceGrpcAsyncIOTransport +from .transports.rest import ApiGatewayServiceRestTransport class ApiGatewayServiceClientMeta(type): @@ -73,6 +74,7 @@ class ApiGatewayServiceClientMeta(type): ) # type: Dict[str, Type[ApiGatewayServiceTransport]] _transport_registry["grpc"] = ApiGatewayServiceGrpcTransport _transport_registry["grpc_asyncio"] = ApiGatewayServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ApiGatewayServiceRestTransport def get_transport_class( cls, diff --git a/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/services/api_gateway_service/transports/__init__.py b/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/services/api_gateway_service/transports/__init__.py index 80f23e0e662b..a3267ee9c21a 100644 --- a/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/services/api_gateway_service/transports/__init__.py +++ b/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/services/api_gateway_service/transports/__init__.py @@ -19,14 +19,18 @@ from .base import ApiGatewayServiceTransport from .grpc import ApiGatewayServiceGrpcTransport from .grpc_asyncio import ApiGatewayServiceGrpcAsyncIOTransport +from .rest import ApiGatewayServiceRestInterceptor, ApiGatewayServiceRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[ApiGatewayServiceTransport]] _transport_registry["grpc"] = ApiGatewayServiceGrpcTransport _transport_registry["grpc_asyncio"] = ApiGatewayServiceGrpcAsyncIOTransport +_transport_registry["rest"] = ApiGatewayServiceRestTransport __all__ = ( "ApiGatewayServiceTransport", "ApiGatewayServiceGrpcTransport", "ApiGatewayServiceGrpcAsyncIOTransport", + "ApiGatewayServiceRestTransport", + "ApiGatewayServiceRestInterceptor", ) diff --git a/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/services/api_gateway_service/transports/rest.py b/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/services/api_gateway_service/transports/rest.py new file mode 100644 index 000000000000..5e4a3f48bea5 --- /dev/null +++ b/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/services/api_gateway_service/transports/rest.py @@ -0,0 +1,2197 @@ +# -*- 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.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.apigateway_v1.types import apigateway + +from .base import ApiGatewayServiceTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ApiGatewayServiceRestInterceptor: + """Interceptor for ApiGatewayService. + + 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 ApiGatewayServiceRestTransport. + + .. code-block:: python + class MyCustomApiGatewayServiceInterceptor(ApiGatewayServiceRestInterceptor): + def pre_create_api(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_api(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_api_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_api_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_gateway(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_gateway(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_api(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_api(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_api_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_api_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_gateway(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_gateway(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_api(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_api(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_api_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_api_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_gateway(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_gateway(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_api_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_api_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_apis(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_apis(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_gateways(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_gateways(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_api(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_api(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_api_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_api_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_gateway(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_gateway(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ApiGatewayServiceRestTransport(interceptor=MyCustomApiGatewayServiceInterceptor()) + client = ApiGatewayServiceClient(transport=transport) + + + """ + + def pre_create_api( + self, request: apigateway.CreateApiRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[apigateway.CreateApiRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_api + + Override in a subclass to manipulate the request or metadata + before they are sent to the ApiGatewayService server. + """ + return request, metadata + + def post_create_api( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_api + + Override in a subclass to manipulate the response + after it is returned by the ApiGatewayService server but before + it is returned to user code. + """ + return response + + def pre_create_api_config( + self, + request: apigateway.CreateApiConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[apigateway.CreateApiConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_api_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the ApiGatewayService server. + """ + return request, metadata + + def post_create_api_config( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_api_config + + Override in a subclass to manipulate the response + after it is returned by the ApiGatewayService server but before + it is returned to user code. + """ + return response + + def pre_create_gateway( + self, + request: apigateway.CreateGatewayRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[apigateway.CreateGatewayRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_gateway + + Override in a subclass to manipulate the request or metadata + before they are sent to the ApiGatewayService server. + """ + return request, metadata + + def post_create_gateway( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_gateway + + Override in a subclass to manipulate the response + after it is returned by the ApiGatewayService server but before + it is returned to user code. + """ + return response + + def pre_delete_api( + self, request: apigateway.DeleteApiRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[apigateway.DeleteApiRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_api + + Override in a subclass to manipulate the request or metadata + before they are sent to the ApiGatewayService server. + """ + return request, metadata + + def post_delete_api( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_api + + Override in a subclass to manipulate the response + after it is returned by the ApiGatewayService server but before + it is returned to user code. + """ + return response + + def pre_delete_api_config( + self, + request: apigateway.DeleteApiConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[apigateway.DeleteApiConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_api_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the ApiGatewayService server. + """ + return request, metadata + + def post_delete_api_config( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_api_config + + Override in a subclass to manipulate the response + after it is returned by the ApiGatewayService server but before + it is returned to user code. + """ + return response + + def pre_delete_gateway( + self, + request: apigateway.DeleteGatewayRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[apigateway.DeleteGatewayRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_gateway + + Override in a subclass to manipulate the request or metadata + before they are sent to the ApiGatewayService server. + """ + return request, metadata + + def post_delete_gateway( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_gateway + + Override in a subclass to manipulate the response + after it is returned by the ApiGatewayService server but before + it is returned to user code. + """ + return response + + def pre_get_api( + self, request: apigateway.GetApiRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[apigateway.GetApiRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_api + + Override in a subclass to manipulate the request or metadata + before they are sent to the ApiGatewayService server. + """ + return request, metadata + + def post_get_api(self, response: apigateway.Api) -> apigateway.Api: + """Post-rpc interceptor for get_api + + Override in a subclass to manipulate the response + after it is returned by the ApiGatewayService server but before + it is returned to user code. + """ + return response + + def pre_get_api_config( + self, + request: apigateway.GetApiConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[apigateway.GetApiConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_api_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the ApiGatewayService server. + """ + return request, metadata + + def post_get_api_config( + self, response: apigateway.ApiConfig + ) -> apigateway.ApiConfig: + """Post-rpc interceptor for get_api_config + + Override in a subclass to manipulate the response + after it is returned by the ApiGatewayService server but before + it is returned to user code. + """ + return response + + def pre_get_gateway( + self, request: apigateway.GetGatewayRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[apigateway.GetGatewayRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_gateway + + Override in a subclass to manipulate the request or metadata + before they are sent to the ApiGatewayService server. + """ + return request, metadata + + def post_get_gateway(self, response: apigateway.Gateway) -> apigateway.Gateway: + """Post-rpc interceptor for get_gateway + + Override in a subclass to manipulate the response + after it is returned by the ApiGatewayService server but before + it is returned to user code. + """ + return response + + def pre_list_api_configs( + self, + request: apigateway.ListApiConfigsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[apigateway.ListApiConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_api_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the ApiGatewayService server. + """ + return request, metadata + + def post_list_api_configs( + self, response: apigateway.ListApiConfigsResponse + ) -> apigateway.ListApiConfigsResponse: + """Post-rpc interceptor for list_api_configs + + Override in a subclass to manipulate the response + after it is returned by the ApiGatewayService server but before + it is returned to user code. + """ + return response + + def pre_list_apis( + self, request: apigateway.ListApisRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[apigateway.ListApisRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_apis + + Override in a subclass to manipulate the request or metadata + before they are sent to the ApiGatewayService server. + """ + return request, metadata + + def post_list_apis( + self, response: apigateway.ListApisResponse + ) -> apigateway.ListApisResponse: + """Post-rpc interceptor for list_apis + + Override in a subclass to manipulate the response + after it is returned by the ApiGatewayService server but before + it is returned to user code. + """ + return response + + def pre_list_gateways( + self, + request: apigateway.ListGatewaysRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[apigateway.ListGatewaysRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_gateways + + Override in a subclass to manipulate the request or metadata + before they are sent to the ApiGatewayService server. + """ + return request, metadata + + def post_list_gateways( + self, response: apigateway.ListGatewaysResponse + ) -> apigateway.ListGatewaysResponse: + """Post-rpc interceptor for list_gateways + + Override in a subclass to manipulate the response + after it is returned by the ApiGatewayService server but before + it is returned to user code. + """ + return response + + def pre_update_api( + self, request: apigateway.UpdateApiRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[apigateway.UpdateApiRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_api + + Override in a subclass to manipulate the request or metadata + before they are sent to the ApiGatewayService server. + """ + return request, metadata + + def post_update_api( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_api + + Override in a subclass to manipulate the response + after it is returned by the ApiGatewayService server but before + it is returned to user code. + """ + return response + + def pre_update_api_config( + self, + request: apigateway.UpdateApiConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[apigateway.UpdateApiConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_api_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the ApiGatewayService server. + """ + return request, metadata + + def post_update_api_config( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_api_config + + Override in a subclass to manipulate the response + after it is returned by the ApiGatewayService server but before + it is returned to user code. + """ + return response + + def pre_update_gateway( + self, + request: apigateway.UpdateGatewayRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[apigateway.UpdateGatewayRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_gateway + + Override in a subclass to manipulate the request or metadata + before they are sent to the ApiGatewayService server. + """ + return request, metadata + + def post_update_gateway( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_gateway + + Override in a subclass to manipulate the response + after it is returned by the ApiGatewayService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ApiGatewayServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ApiGatewayServiceRestInterceptor + + +class ApiGatewayServiceRestTransport(ApiGatewayServiceTransport): + """REST backend transport for ApiGatewayService. + + The API Gateway Service is the interface for managing API + Gateways. + + 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 = "apigateway.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[ApiGatewayServiceRestInterceptor] = 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 ApiGatewayServiceRestInterceptor() + 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]]] = {} + + 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="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateApi(ApiGatewayServiceRestStub): + def __hash__(self): + return hash("CreateApi") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "apiId": "", + } + + @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: apigateway.CreateApiRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create api method over HTTP. + + Args: + request (~.apigateway.CreateApiRequest): + The request object. Request message for + ApiGatewayService.CreateApi + + 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": "/v1/{parent=projects/*/locations/*}/apis", + "body": "api", + }, + ] + request, metadata = self._interceptor.pre_create_api(request, metadata) + pb_request = apigateway.CreateApiRequest.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_api(resp) + return resp + + class _CreateApiConfig(ApiGatewayServiceRestStub): + def __hash__(self): + return hash("CreateApiConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "apiConfigId": "", + } + + @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: apigateway.CreateApiConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create api config method over HTTP. + + Args: + request (~.apigateway.CreateApiConfigRequest): + The request object. Request message for + ApiGatewayService.CreateApiConfig + + 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": "/v1/{parent=projects/*/locations/*/apis/*}/configs", + "body": "api_config", + }, + ] + request, metadata = self._interceptor.pre_create_api_config( + request, metadata + ) + pb_request = apigateway.CreateApiConfigRequest.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_api_config(resp) + return resp + + class _CreateGateway(ApiGatewayServiceRestStub): + def __hash__(self): + return hash("CreateGateway") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "gatewayId": "", + } + + @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: apigateway.CreateGatewayRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create gateway method over HTTP. + + Args: + request (~.apigateway.CreateGatewayRequest): + The request object. Request message for + ApiGatewayService.CreateGateway + + 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": "/v1/{parent=projects/*/locations/*}/gateways", + "body": "gateway", + }, + ] + request, metadata = self._interceptor.pre_create_gateway(request, metadata) + pb_request = apigateway.CreateGatewayRequest.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_gateway(resp) + return resp + + class _DeleteApi(ApiGatewayServiceRestStub): + def __hash__(self): + return hash("DeleteApi") + + __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: apigateway.DeleteApiRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete api method over HTTP. + + Args: + request (~.apigateway.DeleteApiRequest): + The request object. Request message for + ApiGatewayService.DeleteApi + + 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": "/v1/{name=projects/*/locations/*/apis/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_api(request, metadata) + pb_request = apigateway.DeleteApiRequest.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_api(resp) + return resp + + class _DeleteApiConfig(ApiGatewayServiceRestStub): + def __hash__(self): + return hash("DeleteApiConfig") + + __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: apigateway.DeleteApiConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete api config method over HTTP. + + Args: + request (~.apigateway.DeleteApiConfigRequest): + The request object. Request message for + ApiGatewayService.DeleteApiConfig + + 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": "/v1/{name=projects/*/locations/*/apis/*/configs/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_api_config( + request, metadata + ) + pb_request = apigateway.DeleteApiConfigRequest.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_api_config(resp) + return resp + + class _DeleteGateway(ApiGatewayServiceRestStub): + def __hash__(self): + return hash("DeleteGateway") + + __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: apigateway.DeleteGatewayRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete gateway method over HTTP. + + Args: + request (~.apigateway.DeleteGatewayRequest): + The request object. Request message for + ApiGatewayService.DeleteGateway + + 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": "/v1/{name=projects/*/locations/*/gateways/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_gateway(request, metadata) + pb_request = apigateway.DeleteGatewayRequest.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_gateway(resp) + return resp + + class _GetApi(ApiGatewayServiceRestStub): + def __hash__(self): + return hash("GetApi") + + __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: apigateway.GetApiRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> apigateway.Api: + r"""Call the get api method over HTTP. + + Args: + request (~.apigateway.GetApiRequest): + The request object. Request message for + ApiGatewayService.GetApi + + 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: + ~.apigateway.Api: + An API that can be served by one or + more Gateways. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/apis/*}", + }, + ] + request, metadata = self._interceptor.pre_get_api(request, metadata) + pb_request = apigateway.GetApiRequest.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 = apigateway.Api() + pb_resp = apigateway.Api.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_api(resp) + return resp + + class _GetApiConfig(ApiGatewayServiceRestStub): + def __hash__(self): + return hash("GetApiConfig") + + __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: apigateway.GetApiConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> apigateway.ApiConfig: + r"""Call the get api config method over HTTP. + + Args: + request (~.apigateway.GetApiConfigRequest): + The request object. Request message for + ApiGatewayService.GetApiConfig + + 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: + ~.apigateway.ApiConfig: + An API Configuration is a combination + of settings for both the Managed Service + and Gateways serving this API Config. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/apis/*/configs/*}", + }, + ] + request, metadata = self._interceptor.pre_get_api_config(request, metadata) + pb_request = apigateway.GetApiConfigRequest.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 = apigateway.ApiConfig() + pb_resp = apigateway.ApiConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_api_config(resp) + return resp + + class _GetGateway(ApiGatewayServiceRestStub): + def __hash__(self): + return hash("GetGateway") + + __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: apigateway.GetGatewayRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> apigateway.Gateway: + r"""Call the get gateway method over HTTP. + + Args: + request (~.apigateway.GetGatewayRequest): + The request object. Request message for + ApiGatewayService.GetGateway + + 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: + ~.apigateway.Gateway: + A Gateway is an API-aware HTTP proxy. + It performs API-Method and/or + API-Consumer specific actions based on + an API Config such as authentication, + policy enforcement, and backend + selection. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/gateways/*}", + }, + ] + request, metadata = self._interceptor.pre_get_gateway(request, metadata) + pb_request = apigateway.GetGatewayRequest.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 = apigateway.Gateway() + pb_resp = apigateway.Gateway.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_gateway(resp) + return resp + + class _ListApiConfigs(ApiGatewayServiceRestStub): + def __hash__(self): + return hash("ListApiConfigs") + + __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: apigateway.ListApiConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> apigateway.ListApiConfigsResponse: + r"""Call the list api configs method over HTTP. + + Args: + request (~.apigateway.ListApiConfigsRequest): + The request object. Request message for + ApiGatewayService.ListApiConfigs + + 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: + ~.apigateway.ListApiConfigsResponse: + Response message for + ApiGatewayService.ListApiConfigs + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/apis/*}/configs", + }, + ] + request, metadata = self._interceptor.pre_list_api_configs( + request, metadata + ) + pb_request = apigateway.ListApiConfigsRequest.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 = apigateway.ListApiConfigsResponse() + pb_resp = apigateway.ListApiConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_api_configs(resp) + return resp + + class _ListApis(ApiGatewayServiceRestStub): + def __hash__(self): + return hash("ListApis") + + __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: apigateway.ListApisRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> apigateway.ListApisResponse: + r"""Call the list apis method over HTTP. + + Args: + request (~.apigateway.ListApisRequest): + The request object. Request message for + ApiGatewayService.ListApis + + 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: + ~.apigateway.ListApisResponse: + Response message for + ApiGatewayService.ListApis + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/apis", + }, + ] + request, metadata = self._interceptor.pre_list_apis(request, metadata) + pb_request = apigateway.ListApisRequest.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 = apigateway.ListApisResponse() + pb_resp = apigateway.ListApisResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_apis(resp) + return resp + + class _ListGateways(ApiGatewayServiceRestStub): + def __hash__(self): + return hash("ListGateways") + + __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: apigateway.ListGatewaysRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> apigateway.ListGatewaysResponse: + r"""Call the list gateways method over HTTP. + + Args: + request (~.apigateway.ListGatewaysRequest): + The request object. Request message for + ApiGatewayService.ListGateways + + 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: + ~.apigateway.ListGatewaysResponse: + Response message for + ApiGatewayService.ListGateways + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/gateways", + }, + ] + request, metadata = self._interceptor.pre_list_gateways(request, metadata) + pb_request = apigateway.ListGatewaysRequest.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 = apigateway.ListGatewaysResponse() + pb_resp = apigateway.ListGatewaysResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_gateways(resp) + return resp + + class _UpdateApi(ApiGatewayServiceRestStub): + def __hash__(self): + return hash("UpdateApi") + + __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: apigateway.UpdateApiRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update api method over HTTP. + + Args: + request (~.apigateway.UpdateApiRequest): + The request object. Request message for + ApiGatewayService.UpdateApi + + 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": "patch", + "uri": "/v1/{api.name=projects/*/locations/*/apis/*}", + "body": "api", + }, + ] + request, metadata = self._interceptor.pre_update_api(request, metadata) + pb_request = apigateway.UpdateApiRequest.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_api(resp) + return resp + + class _UpdateApiConfig(ApiGatewayServiceRestStub): + def __hash__(self): + return hash("UpdateApiConfig") + + __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: apigateway.UpdateApiConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update api config method over HTTP. + + Args: + request (~.apigateway.UpdateApiConfigRequest): + The request object. Request message for + ApiGatewayService.UpdateApiConfig + + 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": "patch", + "uri": "/v1/{api_config.name=projects/*/locations/*/apis/*/configs/*}", + "body": "api_config", + }, + ] + request, metadata = self._interceptor.pre_update_api_config( + request, metadata + ) + pb_request = apigateway.UpdateApiConfigRequest.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_api_config(resp) + return resp + + class _UpdateGateway(ApiGatewayServiceRestStub): + def __hash__(self): + return hash("UpdateGateway") + + __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: apigateway.UpdateGatewayRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update gateway method over HTTP. + + Args: + request (~.apigateway.UpdateGatewayRequest): + The request object. Request message for + ApiGatewayService.UpdateGateway + + 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": "patch", + "uri": "/v1/{gateway.name=projects/*/locations/*/gateways/*}", + "body": "gateway", + }, + ] + request, metadata = self._interceptor.pre_update_gateway(request, metadata) + pb_request = apigateway.UpdateGatewayRequest.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_gateway(resp) + return resp + + @property + def create_api( + self, + ) -> Callable[[apigateway.CreateApiRequest], 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._CreateApi(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_api_config( + self, + ) -> Callable[[apigateway.CreateApiConfigRequest], 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._CreateApiConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_gateway( + self, + ) -> Callable[[apigateway.CreateGatewayRequest], 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._CreateGateway(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_api( + self, + ) -> Callable[[apigateway.DeleteApiRequest], 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._DeleteApi(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_api_config( + self, + ) -> Callable[[apigateway.DeleteApiConfigRequest], 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._DeleteApiConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_gateway( + self, + ) -> Callable[[apigateway.DeleteGatewayRequest], 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._DeleteGateway(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_api(self) -> Callable[[apigateway.GetApiRequest], apigateway.Api]: + # 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._GetApi(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_api_config( + self, + ) -> Callable[[apigateway.GetApiConfigRequest], apigateway.ApiConfig]: + # 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._GetApiConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_gateway( + self, + ) -> Callable[[apigateway.GetGatewayRequest], apigateway.Gateway]: + # 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._GetGateway(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_api_configs( + self, + ) -> Callable[ + [apigateway.ListApiConfigsRequest], apigateway.ListApiConfigsResponse + ]: + # 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._ListApiConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_apis( + self, + ) -> Callable[[apigateway.ListApisRequest], apigateway.ListApisResponse]: + # 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._ListApis(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_gateways( + self, + ) -> Callable[[apigateway.ListGatewaysRequest], apigateway.ListGatewaysResponse]: + # 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._ListGateways(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_api( + self, + ) -> Callable[[apigateway.UpdateApiRequest], 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._UpdateApi(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_api_config( + self, + ) -> Callable[[apigateway.UpdateApiConfigRequest], 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._UpdateApiConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_gateway( + self, + ) -> Callable[[apigateway.UpdateGatewayRequest], 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._UpdateGateway(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ApiGatewayServiceRestTransport",) diff --git a/packages/google-cloud-api-gateway/tests/unit/gapic/apigateway_v1/test_api_gateway_service.py b/packages/google-cloud-api-gateway/tests/unit/gapic/apigateway_v1/test_api_gateway_service.py index a4673334f620..c4c46f3ecfb0 100644 --- a/packages/google-cloud-api-gateway/tests/unit/gapic/apigateway_v1/test_api_gateway_service.py +++ b/packages/google-cloud-api-gateway/tests/unit/gapic/apigateway_v1/test_api_gateway_service.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 ( @@ -43,12 +45,15 @@ from google.oauth2 import service_account from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_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.apigateway_v1.services.api_gateway_service import ( ApiGatewayServiceAsyncClient, @@ -109,6 +114,7 @@ def test__get_default_mtls_endpoint(): [ (ApiGatewayServiceClient, "grpc"), (ApiGatewayServiceAsyncClient, "grpc_asyncio"), + (ApiGatewayServiceClient, "rest"), ], ) def test_api_gateway_service_client_from_service_account_info( @@ -124,7 +130,11 @@ def test_api_gateway_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("apigateway.googleapis.com:443") + assert client.transport._host == ( + "apigateway.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://apigateway.googleapis.com" + ) @pytest.mark.parametrize( @@ -132,6 +142,7 @@ def test_api_gateway_service_client_from_service_account_info( [ (transports.ApiGatewayServiceGrpcTransport, "grpc"), (transports.ApiGatewayServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ApiGatewayServiceRestTransport, "rest"), ], ) def test_api_gateway_service_client_service_account_always_use_jwt( @@ -157,6 +168,7 @@ def test_api_gateway_service_client_service_account_always_use_jwt( [ (ApiGatewayServiceClient, "grpc"), (ApiGatewayServiceAsyncClient, "grpc_asyncio"), + (ApiGatewayServiceClient, "rest"), ], ) def test_api_gateway_service_client_from_service_account_file( @@ -179,13 +191,18 @@ def test_api_gateway_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("apigateway.googleapis.com:443") + assert client.transport._host == ( + "apigateway.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://apigateway.googleapis.com" + ) def test_api_gateway_service_client_get_transport_class(): transport = ApiGatewayServiceClient.get_transport_class() available_transports = [ transports.ApiGatewayServiceGrpcTransport, + transports.ApiGatewayServiceRestTransport, ] assert transport in available_transports @@ -202,6 +219,7 @@ def test_api_gateway_service_client_get_transport_class(): transports.ApiGatewayServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (ApiGatewayServiceClient, transports.ApiGatewayServiceRestTransport, "rest"), ], ) @mock.patch.object( @@ -357,6 +375,18 @@ def test_api_gateway_service_client_client_options( "grpc_asyncio", "false", ), + ( + ApiGatewayServiceClient, + transports.ApiGatewayServiceRestTransport, + "rest", + "true", + ), + ( + ApiGatewayServiceClient, + transports.ApiGatewayServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -556,6 +586,7 @@ def test_api_gateway_service_client_get_mtls_endpoint_and_cert_source(client_cla transports.ApiGatewayServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (ApiGatewayServiceClient, transports.ApiGatewayServiceRestTransport, "rest"), ], ) def test_api_gateway_service_client_client_options_scopes( @@ -596,6 +627,12 @@ def test_api_gateway_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + ApiGatewayServiceClient, + transports.ApiGatewayServiceRestTransport, + "rest", + None, + ), ], ) def test_api_gateway_service_client_client_options_credentials_file( @@ -4878,134 +4915,4575 @@ async def test_delete_api_config_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ApiGatewayServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + apigateway.ListGatewaysRequest, + dict, + ], +) +def test_list_gateways_rest(request_type): + client = ApiGatewayServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ApiGatewayServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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 = apigateway.ListGatewaysResponse( + next_page_token="next_page_token_value", + unreachable_locations=["unreachable_locations_value"], ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.ApiGatewayServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = apigateway.ListGatewaysResponse.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_gateways(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGatewaysPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable_locations == ["unreachable_locations_value"] + + +def test_list_gateways_rest_required_fields( + request_type=apigateway.ListGatewaysRequest, +): + transport_class = transports.ApiGatewayServiceRestTransport + + 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, + ) ) - with pytest.raises(ValueError): - client = ApiGatewayServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_gateways._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_gateways._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", ) + ) + jsonified_request.update(unset_fields) - # It is an error to provide an api_key and a transport instance. - transport = transports.ApiGatewayServiceGrpcTransport( + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = apigateway.ListGatewaysResponse() + # 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 = apigateway.ListGatewaysResponse.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_gateways(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_gateways_rest_unset_required_fields(): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_gateways._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_gateways_rest_interceptors(null_interceptor): + transport = transports.ApiGatewayServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ApiGatewayServiceRestInterceptor(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ApiGatewayServiceClient( - client_options=options, - transport=transport, + client = ApiGatewayServiceClient(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.ApiGatewayServiceRestInterceptor, "post_list_gateways" + ) as post, mock.patch.object( + transports.ApiGatewayServiceRestInterceptor, "pre_list_gateways" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = apigateway.ListGatewaysRequest.pb(apigateway.ListGatewaysRequest()) + 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 = apigateway.ListGatewaysResponse.to_json( + apigateway.ListGatewaysResponse() ) - # 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 = ApiGatewayServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + request = apigateway.ListGatewaysRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = apigateway.ListGatewaysResponse() + + client.list_gateways( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # It is an error to provide scopes and a transport instance. - transport = transports.ApiGatewayServiceGrpcTransport( + pre.assert_called_once() + post.assert_called_once() + + +def test_list_gateways_rest_bad_request( + transport: str = "rest", request_type=apigateway.ListGatewaysRequest +): + client = ApiGatewayServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - with pytest.raises(ValueError): - client = ApiGatewayServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ApiGatewayServiceGrpcTransport( + # 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_gateways(request) + + +def test_list_gateways_rest_flattened(): + client = ApiGatewayServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = ApiGatewayServiceClient(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 = apigateway.ListGatewaysResponse() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ApiGatewayServiceGrpcTransport( + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/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 = apigateway.ListGatewaysResponse.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_gateways(**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/{parent=projects/*/locations/*}/gateways" % client.transport._host, + args[1], + ) + + +def test_list_gateways_rest_flattened_error(transport: str = "rest"): + client = ApiGatewayServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel - transport = transports.ApiGatewayServiceGrpcAsyncIOTransport( + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_gateways( + apigateway.ListGatewaysRequest(), + parent="parent_value", + ) + + +def test_list_gateways_rest_pager(transport: str = "rest"): + client = ApiGatewayServiceClient( 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 = ( + apigateway.ListGatewaysResponse( + gateways=[ + apigateway.Gateway(), + apigateway.Gateway(), + apigateway.Gateway(), + ], + next_page_token="abc", + ), + apigateway.ListGatewaysResponse( + gateways=[], + next_page_token="def", + ), + apigateway.ListGatewaysResponse( + gateways=[ + apigateway.Gateway(), + ], + next_page_token="ghi", + ), + apigateway.ListGatewaysResponse( + gateways=[ + apigateway.Gateway(), + apigateway.Gateway(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(apigateway.ListGatewaysResponse.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.ApiGatewayServiceGrpcTransport, - transports.ApiGatewayServiceGrpcAsyncIOTransport, - ], -) -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": "projects/sample1/locations/sample2"} + + pager = client.list_gateways(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, apigateway.Gateway) for i in results) + + pages = list(client.list_gateways(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", + apigateway.GetGatewayRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = ApiGatewayServiceClient.get_transport_class(transport_name)( +def test_get_gateway_rest(request_type): + client = ApiGatewayServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/gateways/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 = apigateway.Gateway( + name="name_value", + display_name="display_name_value", + api_config="api_config_value", + state=apigateway.Gateway.State.CREATING, + default_hostname="default_hostname_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = apigateway.Gateway.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_gateway(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, apigateway.Gateway) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.api_config == "api_config_value" + assert response.state == apigateway.Gateway.State.CREATING + assert response.default_hostname == "default_hostname_value" + + +def test_get_gateway_rest_required_fields(request_type=apigateway.GetGatewayRequest): + transport_class = transports.ApiGatewayServiceRestTransport + + 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_gateway._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_gateway._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 = ApiGatewayServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.ApiGatewayServiceGrpcTransport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = apigateway.Gateway() + # 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 = apigateway.Gateway.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_gateway(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_gateway_rest_unset_required_fields(): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.get_gateway._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_api_gateway_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ApiGatewayServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_gateway_rest_interceptors(null_interceptor): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ApiGatewayServiceRestInterceptor(), + ) + client = ApiGatewayServiceClient(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.ApiGatewayServiceRestInterceptor, "post_get_gateway" + ) as post, mock.patch.object( + transports.ApiGatewayServiceRestInterceptor, "pre_get_gateway" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = apigateway.GetGatewayRequest.pb(apigateway.GetGatewayRequest()) + 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 = apigateway.Gateway.to_json(apigateway.Gateway()) + + request = apigateway.GetGatewayRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = apigateway.Gateway() + + client.get_gateway( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() -def test_api_gateway_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.apigateway_v1.services.api_gateway_service.transports.ApiGatewayServiceTransport.__init__" + +def test_get_gateway_rest_bad_request( + transport: str = "rest", request_type=apigateway.GetGatewayRequest +): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/gateways/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_gateway(request) + + +def test_get_gateway_rest_flattened(): + client = ApiGatewayServiceClient( + 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 = apigateway.Gateway() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/gateways/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 = apigateway.Gateway.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_gateway(**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/*/locations/*/gateways/*}" % client.transport._host, + args[1], + ) + + +def test_get_gateway_rest_flattened_error(transport: str = "rest"): + client = ApiGatewayServiceClient( + 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_gateway( + apigateway.GetGatewayRequest(), + name="name_value", + ) + + +def test_get_gateway_rest_error(): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + apigateway.CreateGatewayRequest, + dict, + ], +) +def test_create_gateway_rest(request_type): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["gateway"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "display_name": "display_name_value", + "api_config": "api_config_value", + "state": 1, + "default_hostname": "default_hostname_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_gateway(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_gateway_rest_required_fields( + request_type=apigateway.CreateGatewayRequest, +): + transport_class = transports.ApiGatewayServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["gateway_id"] = "" + 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 + assert "gatewayId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_gateway._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "gatewayId" in jsonified_request + assert jsonified_request["gatewayId"] == request_init["gateway_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["gatewayId"] = "gateway_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_gateway._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("gateway_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" + assert "gatewayId" in jsonified_request + assert jsonified_request["gatewayId"] == "gateway_id_value" + + client = ApiGatewayServiceClient( + 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_gateway(request) + + expected_params = [ + ( + "gatewayId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_gateway_rest_unset_required_fields(): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_gateway._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("gatewayId",)) + & set( + ( + "parent", + "gatewayId", + "gateway", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_gateway_rest_interceptors(null_interceptor): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ApiGatewayServiceRestInterceptor(), + ) + client = ApiGatewayServiceClient(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.ApiGatewayServiceRestInterceptor, "post_create_gateway" + ) as post, mock.patch.object( + transports.ApiGatewayServiceRestInterceptor, "pre_create_gateway" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = apigateway.CreateGatewayRequest.pb( + apigateway.CreateGatewayRequest() + ) + 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 = apigateway.CreateGatewayRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_gateway( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_gateway_rest_bad_request( + transport: str = "rest", request_type=apigateway.CreateGatewayRequest +): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["gateway"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "display_name": "display_name_value", + "api_config": "api_config_value", + "state": 1, + "default_hostname": "default_hostname_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_gateway(request) + + +def test_create_gateway_rest_flattened(): + client = ApiGatewayServiceClient( + 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": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + gateway=apigateway.Gateway(name="name_value"), + gateway_id="gateway_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_gateway(**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/{parent=projects/*/locations/*}/gateways" % client.transport._host, + args[1], + ) + + +def test_create_gateway_rest_flattened_error(transport: str = "rest"): + client = ApiGatewayServiceClient( + 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_gateway( + apigateway.CreateGatewayRequest(), + parent="parent_value", + gateway=apigateway.Gateway(name="name_value"), + gateway_id="gateway_id_value", + ) + + +def test_create_gateway_rest_error(): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + apigateway.UpdateGatewayRequest, + dict, + ], +) +def test_update_gateway_rest(request_type): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "gateway": {"name": "projects/sample1/locations/sample2/gateways/sample3"} + } + request_init["gateway"] = { + "name": "projects/sample1/locations/sample2/gateways/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "display_name": "display_name_value", + "api_config": "api_config_value", + "state": 1, + "default_hostname": "default_hostname_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_gateway(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_gateway_rest_required_fields( + request_type=apigateway.UpdateGatewayRequest, +): + transport_class = transports.ApiGatewayServiceRestTransport + + 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_gateway._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_gateway._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ApiGatewayServiceClient( + 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": "patch", + "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_gateway(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_gateway_rest_unset_required_fields(): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_gateway._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("gateway",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_gateway_rest_interceptors(null_interceptor): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ApiGatewayServiceRestInterceptor(), + ) + client = ApiGatewayServiceClient(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.ApiGatewayServiceRestInterceptor, "post_update_gateway" + ) as post, mock.patch.object( + transports.ApiGatewayServiceRestInterceptor, "pre_update_gateway" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = apigateway.UpdateGatewayRequest.pb( + apigateway.UpdateGatewayRequest() + ) + 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 = apigateway.UpdateGatewayRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_gateway( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_gateway_rest_bad_request( + transport: str = "rest", request_type=apigateway.UpdateGatewayRequest +): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "gateway": {"name": "projects/sample1/locations/sample2/gateways/sample3"} + } + request_init["gateway"] = { + "name": "projects/sample1/locations/sample2/gateways/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "display_name": "display_name_value", + "api_config": "api_config_value", + "state": 1, + "default_hostname": "default_hostname_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_gateway(request) + + +def test_update_gateway_rest_flattened(): + client = ApiGatewayServiceClient( + 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 = { + "gateway": {"name": "projects/sample1/locations/sample2/gateways/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + gateway=apigateway.Gateway(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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.update_gateway(**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/{gateway.name=projects/*/locations/*/gateways/*}" + % client.transport._host, + args[1], + ) + + +def test_update_gateway_rest_flattened_error(transport: str = "rest"): + client = ApiGatewayServiceClient( + 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.update_gateway( + apigateway.UpdateGatewayRequest(), + gateway=apigateway.Gateway(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_gateway_rest_error(): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + apigateway.DeleteGatewayRequest, + dict, + ], +) +def test_delete_gateway_rest(request_type): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/gateways/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_gateway(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_gateway_rest_required_fields( + request_type=apigateway.DeleteGatewayRequest, +): + transport_class = transports.ApiGatewayServiceRestTransport + + 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_gateway._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_gateway._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" + + client = ApiGatewayServiceClient( + 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_gateway(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_gateway_rest_unset_required_fields(): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_gateway._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_gateway_rest_interceptors(null_interceptor): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ApiGatewayServiceRestInterceptor(), + ) + client = ApiGatewayServiceClient(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.ApiGatewayServiceRestInterceptor, "post_delete_gateway" + ) as post, mock.patch.object( + transports.ApiGatewayServiceRestInterceptor, "pre_delete_gateway" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = apigateway.DeleteGatewayRequest.pb( + apigateway.DeleteGatewayRequest() + ) + 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 = apigateway.DeleteGatewayRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_gateway( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_gateway_rest_bad_request( + transport: str = "rest", request_type=apigateway.DeleteGatewayRequest +): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/gateways/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_gateway(request) + + +def test_delete_gateway_rest_flattened(): + client = ApiGatewayServiceClient( + 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": "projects/sample1/locations/sample2/gateways/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_gateway(**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/*/locations/*/gateways/*}" % client.transport._host, + args[1], + ) + + +def test_delete_gateway_rest_flattened_error(transport: str = "rest"): + client = ApiGatewayServiceClient( + 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_gateway( + apigateway.DeleteGatewayRequest(), + name="name_value", + ) + + +def test_delete_gateway_rest_error(): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + apigateway.ListApisRequest, + dict, + ], +) +def test_list_apis_rest(request_type): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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 = apigateway.ListApisResponse( + next_page_token="next_page_token_value", + unreachable_locations=["unreachable_locations_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = apigateway.ListApisResponse.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_apis(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApisPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable_locations == ["unreachable_locations_value"] + + +def test_list_apis_rest_required_fields(request_type=apigateway.ListApisRequest): + transport_class = transports.ApiGatewayServiceRestTransport + + 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_apis._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_apis._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "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 = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = apigateway.ListApisResponse() + # 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 = apigateway.ListApisResponse.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_apis(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_apis_rest_unset_required_fields(): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_apis._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_apis_rest_interceptors(null_interceptor): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ApiGatewayServiceRestInterceptor(), + ) + client = ApiGatewayServiceClient(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.ApiGatewayServiceRestInterceptor, "post_list_apis" + ) as post, mock.patch.object( + transports.ApiGatewayServiceRestInterceptor, "pre_list_apis" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = apigateway.ListApisRequest.pb(apigateway.ListApisRequest()) + 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 = apigateway.ListApisResponse.to_json( + apigateway.ListApisResponse() + ) + + request = apigateway.ListApisRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = apigateway.ListApisResponse() + + client.list_apis( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_apis_rest_bad_request( + transport: str = "rest", request_type=apigateway.ListApisRequest +): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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.list_apis(request) + + +def test_list_apis_rest_flattened(): + client = ApiGatewayServiceClient( + 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 = apigateway.ListApisResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/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 = apigateway.ListApisResponse.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_apis(**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/{parent=projects/*/locations/*}/apis" % client.transport._host, + args[1], + ) + + +def test_list_apis_rest_flattened_error(transport: str = "rest"): + client = ApiGatewayServiceClient( + 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.list_apis( + apigateway.ListApisRequest(), + parent="parent_value", + ) + + +def test_list_apis_rest_pager(transport: str = "rest"): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = ( + apigateway.ListApisResponse( + apis=[ + apigateway.Api(), + apigateway.Api(), + apigateway.Api(), + ], + next_page_token="abc", + ), + apigateway.ListApisResponse( + apis=[], + next_page_token="def", + ), + apigateway.ListApisResponse( + apis=[ + apigateway.Api(), + ], + next_page_token="ghi", + ), + apigateway.ListApisResponse( + apis=[ + apigateway.Api(), + apigateway.Api(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(apigateway.ListApisResponse.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 + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_apis(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, apigateway.Api) for i in results) + + pages = list(client.list_apis(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + apigateway.GetApiRequest, + dict, + ], +) +def test_get_api_rest(request_type): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/apis/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 = apigateway.Api( + name="name_value", + display_name="display_name_value", + managed_service="managed_service_value", + state=apigateway.Api.State.CREATING, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = apigateway.Api.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_api(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, apigateway.Api) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.managed_service == "managed_service_value" + assert response.state == apigateway.Api.State.CREATING + + +def test_get_api_rest_required_fields(request_type=apigateway.GetApiRequest): + transport_class = transports.ApiGatewayServiceRestTransport + + 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_api._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_api._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" + + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = apigateway.Api() + # 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 = apigateway.Api.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_api(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_api_rest_unset_required_fields(): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_api._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_api_rest_interceptors(null_interceptor): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ApiGatewayServiceRestInterceptor(), + ) + client = ApiGatewayServiceClient(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.ApiGatewayServiceRestInterceptor, "post_get_api" + ) as post, mock.patch.object( + transports.ApiGatewayServiceRestInterceptor, "pre_get_api" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = apigateway.GetApiRequest.pb(apigateway.GetApiRequest()) + 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 = apigateway.Api.to_json(apigateway.Api()) + + request = apigateway.GetApiRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = apigateway.Api() + + client.get_api( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_api_rest_bad_request( + transport: str = "rest", request_type=apigateway.GetApiRequest +): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/apis/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_api(request) + + +def test_get_api_rest_flattened(): + client = ApiGatewayServiceClient( + 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 = apigateway.Api() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/apis/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 = apigateway.Api.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_api(**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/*/locations/*/apis/*}" % client.transport._host, + args[1], + ) + + +def test_get_api_rest_flattened_error(transport: str = "rest"): + client = ApiGatewayServiceClient( + 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_api( + apigateway.GetApiRequest(), + name="name_value", + ) + + +def test_get_api_rest_error(): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + apigateway.CreateApiRequest, + dict, + ], +) +def test_create_api_rest(request_type): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["api"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "display_name": "display_name_value", + "managed_service": "managed_service_value", + "state": 1, + } + 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_api(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_api_rest_required_fields(request_type=apigateway.CreateApiRequest): + transport_class = transports.ApiGatewayServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["api_id"] = "" + 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 + assert "apiId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_api._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "apiId" in jsonified_request + assert jsonified_request["apiId"] == request_init["api_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["apiId"] = "api_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_api._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("api_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" + assert "apiId" in jsonified_request + assert jsonified_request["apiId"] == "api_id_value" + + client = ApiGatewayServiceClient( + 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_api(request) + + expected_params = [ + ( + "apiId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_api_rest_unset_required_fields(): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_api._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("apiId",)) + & set( + ( + "parent", + "apiId", + "api", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_api_rest_interceptors(null_interceptor): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ApiGatewayServiceRestInterceptor(), + ) + client = ApiGatewayServiceClient(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.ApiGatewayServiceRestInterceptor, "post_create_api" + ) as post, mock.patch.object( + transports.ApiGatewayServiceRestInterceptor, "pre_create_api" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = apigateway.CreateApiRequest.pb(apigateway.CreateApiRequest()) + 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 = apigateway.CreateApiRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_api( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_api_rest_bad_request( + transport: str = "rest", request_type=apigateway.CreateApiRequest +): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["api"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "display_name": "display_name_value", + "managed_service": "managed_service_value", + "state": 1, + } + 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_api(request) + + +def test_create_api_rest_flattened(): + client = ApiGatewayServiceClient( + 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": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + api=apigateway.Api(name="name_value"), + api_id="api_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_api(**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/{parent=projects/*/locations/*}/apis" % client.transport._host, + args[1], + ) + + +def test_create_api_rest_flattened_error(transport: str = "rest"): + client = ApiGatewayServiceClient( + 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_api( + apigateway.CreateApiRequest(), + parent="parent_value", + api=apigateway.Api(name="name_value"), + api_id="api_id_value", + ) + + +def test_create_api_rest_error(): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + apigateway.UpdateApiRequest, + dict, + ], +) +def test_update_api_rest(request_type): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"api": {"name": "projects/sample1/locations/sample2/apis/sample3"}} + request_init["api"] = { + "name": "projects/sample1/locations/sample2/apis/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "display_name": "display_name_value", + "managed_service": "managed_service_value", + "state": 1, + } + 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_api(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_api_rest_required_fields(request_type=apigateway.UpdateApiRequest): + transport_class = transports.ApiGatewayServiceRestTransport + + 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_api._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_api._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ApiGatewayServiceClient( + 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": "patch", + "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_api(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_api_rest_unset_required_fields(): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_api._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("api",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_api_rest_interceptors(null_interceptor): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ApiGatewayServiceRestInterceptor(), + ) + client = ApiGatewayServiceClient(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.ApiGatewayServiceRestInterceptor, "post_update_api" + ) as post, mock.patch.object( + transports.ApiGatewayServiceRestInterceptor, "pre_update_api" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = apigateway.UpdateApiRequest.pb(apigateway.UpdateApiRequest()) + 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 = apigateway.UpdateApiRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_api( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_api_rest_bad_request( + transport: str = "rest", request_type=apigateway.UpdateApiRequest +): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"api": {"name": "projects/sample1/locations/sample2/apis/sample3"}} + request_init["api"] = { + "name": "projects/sample1/locations/sample2/apis/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "display_name": "display_name_value", + "managed_service": "managed_service_value", + "state": 1, + } + 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_api(request) + + +def test_update_api_rest_flattened(): + client = ApiGatewayServiceClient( + 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 = { + "api": {"name": "projects/sample1/locations/sample2/apis/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + api=apigateway.Api(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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.update_api(**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/{api.name=projects/*/locations/*/apis/*}" % client.transport._host, + args[1], + ) + + +def test_update_api_rest_flattened_error(transport: str = "rest"): + client = ApiGatewayServiceClient( + 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.update_api( + apigateway.UpdateApiRequest(), + api=apigateway.Api(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_api_rest_error(): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + apigateway.DeleteApiRequest, + dict, + ], +) +def test_delete_api_rest(request_type): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/apis/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_api(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_api_rest_required_fields(request_type=apigateway.DeleteApiRequest): + transport_class = transports.ApiGatewayServiceRestTransport + + 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_api._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_api._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" + + client = ApiGatewayServiceClient( + 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_api(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_api_rest_unset_required_fields(): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_api._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_api_rest_interceptors(null_interceptor): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ApiGatewayServiceRestInterceptor(), + ) + client = ApiGatewayServiceClient(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.ApiGatewayServiceRestInterceptor, "post_delete_api" + ) as post, mock.patch.object( + transports.ApiGatewayServiceRestInterceptor, "pre_delete_api" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = apigateway.DeleteApiRequest.pb(apigateway.DeleteApiRequest()) + 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 = apigateway.DeleteApiRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_api( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_api_rest_bad_request( + transport: str = "rest", request_type=apigateway.DeleteApiRequest +): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/apis/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_api(request) + + +def test_delete_api_rest_flattened(): + client = ApiGatewayServiceClient( + 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": "projects/sample1/locations/sample2/apis/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_api(**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/*/locations/*/apis/*}" % client.transport._host, + args[1], + ) + + +def test_delete_api_rest_flattened_error(transport: str = "rest"): + client = ApiGatewayServiceClient( + 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_api( + apigateway.DeleteApiRequest(), + name="name_value", + ) + + +def test_delete_api_rest_error(): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + apigateway.ListApiConfigsRequest, + dict, + ], +) +def test_list_api_configs_rest(request_type): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apis/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 = apigateway.ListApiConfigsResponse( + next_page_token="next_page_token_value", + unreachable_locations=["unreachable_locations_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = apigateway.ListApiConfigsResponse.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_api_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApiConfigsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable_locations == ["unreachable_locations_value"] + + +def test_list_api_configs_rest_required_fields( + request_type=apigateway.ListApiConfigsRequest, +): + transport_class = transports.ApiGatewayServiceRestTransport + + 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_api_configs._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_api_configs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "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 = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = apigateway.ListApiConfigsResponse() + # 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 = apigateway.ListApiConfigsResponse.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_api_configs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_api_configs_rest_unset_required_fields(): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_api_configs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_api_configs_rest_interceptors(null_interceptor): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ApiGatewayServiceRestInterceptor(), + ) + client = ApiGatewayServiceClient(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.ApiGatewayServiceRestInterceptor, "post_list_api_configs" + ) as post, mock.patch.object( + transports.ApiGatewayServiceRestInterceptor, "pre_list_api_configs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = apigateway.ListApiConfigsRequest.pb( + apigateway.ListApiConfigsRequest() + ) + 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 = apigateway.ListApiConfigsResponse.to_json( + apigateway.ListApiConfigsResponse() + ) + + request = apigateway.ListApiConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = apigateway.ListApiConfigsResponse() + + client.list_api_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_api_configs_rest_bad_request( + transport: str = "rest", request_type=apigateway.ListApiConfigsRequest +): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apis/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.list_api_configs(request) + + +def test_list_api_configs_rest_flattened(): + client = ApiGatewayServiceClient( + 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 = apigateway.ListApiConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apis/sample3"} + + # 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 = apigateway.ListApiConfigsResponse.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_api_configs(**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/{parent=projects/*/locations/*/apis/*}/configs" + % client.transport._host, + args[1], + ) + + +def test_list_api_configs_rest_flattened_error(transport: str = "rest"): + client = ApiGatewayServiceClient( + 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.list_api_configs( + apigateway.ListApiConfigsRequest(), + parent="parent_value", + ) + + +def test_list_api_configs_rest_pager(transport: str = "rest"): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = ( + apigateway.ListApiConfigsResponse( + api_configs=[ + apigateway.ApiConfig(), + apigateway.ApiConfig(), + apigateway.ApiConfig(), + ], + next_page_token="abc", + ), + apigateway.ListApiConfigsResponse( + api_configs=[], + next_page_token="def", + ), + apigateway.ListApiConfigsResponse( + api_configs=[ + apigateway.ApiConfig(), + ], + next_page_token="ghi", + ), + apigateway.ListApiConfigsResponse( + api_configs=[ + apigateway.ApiConfig(), + apigateway.ApiConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(apigateway.ListApiConfigsResponse.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 + + sample_request = {"parent": "projects/sample1/locations/sample2/apis/sample3"} + + pager = client.list_api_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, apigateway.ApiConfig) for i in results) + + pages = list(client.list_api_configs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + apigateway.GetApiConfigRequest, + dict, + ], +) +def test_get_api_config_rest(request_type): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apis/sample3/configs/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 = apigateway.ApiConfig( + name="name_value", + display_name="display_name_value", + gateway_service_account="gateway_service_account_value", + service_config_id="service_config_id_value", + state=apigateway.ApiConfig.State.CREATING, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = apigateway.ApiConfig.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_api_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, apigateway.ApiConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.gateway_service_account == "gateway_service_account_value" + assert response.service_config_id == "service_config_id_value" + assert response.state == apigateway.ApiConfig.State.CREATING + + +def test_get_api_config_rest_required_fields( + request_type=apigateway.GetApiConfigRequest, +): + transport_class = transports.ApiGatewayServiceRestTransport + + 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_api_config._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_api_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view",)) + 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 = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = apigateway.ApiConfig() + # 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 = apigateway.ApiConfig.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_api_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_api_config_rest_unset_required_fields(): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_api_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("view",)) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_api_config_rest_interceptors(null_interceptor): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ApiGatewayServiceRestInterceptor(), + ) + client = ApiGatewayServiceClient(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.ApiGatewayServiceRestInterceptor, "post_get_api_config" + ) as post, mock.patch.object( + transports.ApiGatewayServiceRestInterceptor, "pre_get_api_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = apigateway.GetApiConfigRequest.pb(apigateway.GetApiConfigRequest()) + 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 = apigateway.ApiConfig.to_json(apigateway.ApiConfig()) + + request = apigateway.GetApiConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = apigateway.ApiConfig() + + client.get_api_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_api_config_rest_bad_request( + transport: str = "rest", request_type=apigateway.GetApiConfigRequest +): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apis/sample3/configs/sample4" + } + 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_api_config(request) + + +def test_get_api_config_rest_flattened(): + client = ApiGatewayServiceClient( + 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 = apigateway.ApiConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apis/sample3/configs/sample4" + } + + # 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 = apigateway.ApiConfig.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_api_config(**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/*/locations/*/apis/*/configs/*}" + % client.transport._host, + args[1], + ) + + +def test_get_api_config_rest_flattened_error(transport: str = "rest"): + client = ApiGatewayServiceClient( + 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_api_config( + apigateway.GetApiConfigRequest(), + name="name_value", + ) + + +def test_get_api_config_rest_error(): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + apigateway.CreateApiConfigRequest, + dict, + ], +) +def test_create_api_config_rest(request_type): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apis/sample3"} + request_init["api_config"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "display_name": "display_name_value", + "gateway_service_account": "gateway_service_account_value", + "service_config_id": "service_config_id_value", + "state": 1, + "openapi_documents": [ + {"document": {"path": "path_value", "contents": b"contents_blob"}} + ], + "grpc_services": [{"file_descriptor_set": {}, "source": {}}], + "managed_service_configs": {}, + } + 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_api_config(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_api_config_rest_required_fields( + request_type=apigateway.CreateApiConfigRequest, +): + transport_class = transports.ApiGatewayServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["api_config_id"] = "" + 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 + assert "apiConfigId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_api_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "apiConfigId" in jsonified_request + assert jsonified_request["apiConfigId"] == request_init["api_config_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["apiConfigId"] = "api_config_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_api_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("api_config_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" + assert "apiConfigId" in jsonified_request + assert jsonified_request["apiConfigId"] == "api_config_id_value" + + client = ApiGatewayServiceClient( + 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_api_config(request) + + expected_params = [ + ( + "apiConfigId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_api_config_rest_unset_required_fields(): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_api_config._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("apiConfigId",)) + & set( + ( + "parent", + "apiConfigId", + "apiConfig", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_api_config_rest_interceptors(null_interceptor): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ApiGatewayServiceRestInterceptor(), + ) + client = ApiGatewayServiceClient(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.ApiGatewayServiceRestInterceptor, "post_create_api_config" + ) as post, mock.patch.object( + transports.ApiGatewayServiceRestInterceptor, "pre_create_api_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = apigateway.CreateApiConfigRequest.pb( + apigateway.CreateApiConfigRequest() + ) + 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 = apigateway.CreateApiConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_api_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_api_config_rest_bad_request( + transport: str = "rest", request_type=apigateway.CreateApiConfigRequest +): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apis/sample3"} + request_init["api_config"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "display_name": "display_name_value", + "gateway_service_account": "gateway_service_account_value", + "service_config_id": "service_config_id_value", + "state": 1, + "openapi_documents": [ + {"document": {"path": "path_value", "contents": b"contents_blob"}} + ], + "grpc_services": [{"file_descriptor_set": {}, "source": {}}], + "managed_service_configs": {}, + } + 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_api_config(request) + + +def test_create_api_config_rest_flattened(): + client = ApiGatewayServiceClient( + 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": "projects/sample1/locations/sample2/apis/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + api_config=apigateway.ApiConfig(name="name_value"), + api_config_id="api_config_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_api_config(**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/{parent=projects/*/locations/*/apis/*}/configs" + % client.transport._host, + args[1], + ) + + +def test_create_api_config_rest_flattened_error(transport: str = "rest"): + client = ApiGatewayServiceClient( + 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_api_config( + apigateway.CreateApiConfigRequest(), + parent="parent_value", + api_config=apigateway.ApiConfig(name="name_value"), + api_config_id="api_config_id_value", + ) + + +def test_create_api_config_rest_error(): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + apigateway.UpdateApiConfigRequest, + dict, + ], +) +def test_update_api_config_rest(request_type): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "api_config": { + "name": "projects/sample1/locations/sample2/apis/sample3/configs/sample4" + } + } + request_init["api_config"] = { + "name": "projects/sample1/locations/sample2/apis/sample3/configs/sample4", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "display_name": "display_name_value", + "gateway_service_account": "gateway_service_account_value", + "service_config_id": "service_config_id_value", + "state": 1, + "openapi_documents": [ + {"document": {"path": "path_value", "contents": b"contents_blob"}} + ], + "grpc_services": [{"file_descriptor_set": {}, "source": {}}], + "managed_service_configs": {}, + } + 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_api_config(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_api_config_rest_required_fields( + request_type=apigateway.UpdateApiConfigRequest, +): + transport_class = transports.ApiGatewayServiceRestTransport + + 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_api_config._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_api_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ApiGatewayServiceClient( + 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": "patch", + "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_api_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_api_config_rest_unset_required_fields(): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_api_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("apiConfig",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_api_config_rest_interceptors(null_interceptor): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ApiGatewayServiceRestInterceptor(), + ) + client = ApiGatewayServiceClient(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.ApiGatewayServiceRestInterceptor, "post_update_api_config" + ) as post, mock.patch.object( + transports.ApiGatewayServiceRestInterceptor, "pre_update_api_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = apigateway.UpdateApiConfigRequest.pb( + apigateway.UpdateApiConfigRequest() + ) + 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 = apigateway.UpdateApiConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_api_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_api_config_rest_bad_request( + transport: str = "rest", request_type=apigateway.UpdateApiConfigRequest +): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "api_config": { + "name": "projects/sample1/locations/sample2/apis/sample3/configs/sample4" + } + } + request_init["api_config"] = { + "name": "projects/sample1/locations/sample2/apis/sample3/configs/sample4", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "display_name": "display_name_value", + "gateway_service_account": "gateway_service_account_value", + "service_config_id": "service_config_id_value", + "state": 1, + "openapi_documents": [ + {"document": {"path": "path_value", "contents": b"contents_blob"}} + ], + "grpc_services": [{"file_descriptor_set": {}, "source": {}}], + "managed_service_configs": {}, + } + 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_api_config(request) + + +def test_update_api_config_rest_flattened(): + client = ApiGatewayServiceClient( + 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 = { + "api_config": { + "name": "projects/sample1/locations/sample2/apis/sample3/configs/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + api_config=apigateway.ApiConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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.update_api_config(**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/{api_config.name=projects/*/locations/*/apis/*/configs/*}" + % client.transport._host, + args[1], + ) + + +def test_update_api_config_rest_flattened_error(transport: str = "rest"): + client = ApiGatewayServiceClient( + 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.update_api_config( + apigateway.UpdateApiConfigRequest(), + api_config=apigateway.ApiConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_api_config_rest_error(): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + apigateway.DeleteApiConfigRequest, + dict, + ], +) +def test_delete_api_config_rest(request_type): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apis/sample3/configs/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(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_api_config(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_api_config_rest_required_fields( + request_type=apigateway.DeleteApiConfigRequest, +): + transport_class = transports.ApiGatewayServiceRestTransport + + 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_api_config._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_api_config._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" + + client = ApiGatewayServiceClient( + 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_api_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_api_config_rest_unset_required_fields(): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_api_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_api_config_rest_interceptors(null_interceptor): + transport = transports.ApiGatewayServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ApiGatewayServiceRestInterceptor(), + ) + client = ApiGatewayServiceClient(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.ApiGatewayServiceRestInterceptor, "post_delete_api_config" + ) as post, mock.patch.object( + transports.ApiGatewayServiceRestInterceptor, "pre_delete_api_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = apigateway.DeleteApiConfigRequest.pb( + apigateway.DeleteApiConfigRequest() + ) + 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 = apigateway.DeleteApiConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_api_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_api_config_rest_bad_request( + transport: str = "rest", request_type=apigateway.DeleteApiConfigRequest +): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apis/sample3/configs/sample4" + } + 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_api_config(request) + + +def test_delete_api_config_rest_flattened(): + client = ApiGatewayServiceClient( + 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": "projects/sample1/locations/sample2/apis/sample3/configs/sample4" + } + + # 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_api_config(**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/*/locations/*/apis/*/configs/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_api_config_rest_flattened_error(transport: str = "rest"): + client = ApiGatewayServiceClient( + 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_api_config( + apigateway.DeleteApiConfigRequest(), + name="name_value", + ) + + +def test_delete_api_config_rest_error(): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ApiGatewayServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ApiGatewayServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ApiGatewayServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ApiGatewayServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ApiGatewayServiceClient( + 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 = ApiGatewayServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ApiGatewayServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ApiGatewayServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ApiGatewayServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ApiGatewayServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ApiGatewayServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ApiGatewayServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ApiGatewayServiceGrpcTransport, + transports.ApiGatewayServiceGrpcAsyncIOTransport, + transports.ApiGatewayServiceRestTransport, + ], +) +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 = ApiGatewayServiceClient.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 = ApiGatewayServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ApiGatewayServiceGrpcTransport, + ) + + +def test_api_gateway_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ApiGatewayServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_api_gateway_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.apigateway_v1.services.api_gateway_service.transports.ApiGatewayServiceTransport.__init__" ) as Transport: Transport.return_value = None transport = transports.ApiGatewayServiceTransport( @@ -5121,6 +9599,7 @@ def test_api_gateway_service_transport_auth_adc(transport_class): [ transports.ApiGatewayServiceGrpcTransport, transports.ApiGatewayServiceGrpcAsyncIOTransport, + transports.ApiGatewayServiceRestTransport, ], ) def test_api_gateway_service_transport_auth_gdch_credentials(transport_class): @@ -5220,11 +9699,40 @@ def test_api_gateway_service_grpc_transport_client_cert_source_for_mtls( ) +def test_api_gateway_service_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.ApiGatewayServiceRestTransport( + 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_api_gateway_service_rest_lro_client(): + client = ApiGatewayServiceClient( + 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_api_gateway_service_host_no_port(transport_name): @@ -5235,7 +9743,11 @@ def test_api_gateway_service_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("apigateway.googleapis.com:443") + assert client.transport._host == ( + "apigateway.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://apigateway.googleapis.com" + ) @pytest.mark.parametrize( @@ -5243,6 +9755,7 @@ def test_api_gateway_service_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_api_gateway_service_host_with_port(transport_name): @@ -5253,7 +9766,75 @@ def test_api_gateway_service_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("apigateway.googleapis.com:8000") + assert client.transport._host == ( + "apigateway.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://apigateway.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_api_gateway_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ApiGatewayServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ApiGatewayServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_gateways._session + session2 = client2.transport.list_gateways._session + assert session1 != session2 + session1 = client1.transport.get_gateway._session + session2 = client2.transport.get_gateway._session + assert session1 != session2 + session1 = client1.transport.create_gateway._session + session2 = client2.transport.create_gateway._session + assert session1 != session2 + session1 = client1.transport.update_gateway._session + session2 = client2.transport.update_gateway._session + assert session1 != session2 + session1 = client1.transport.delete_gateway._session + session2 = client2.transport.delete_gateway._session + assert session1 != session2 + session1 = client1.transport.list_apis._session + session2 = client2.transport.list_apis._session + assert session1 != session2 + session1 = client1.transport.get_api._session + session2 = client2.transport.get_api._session + assert session1 != session2 + session1 = client1.transport.create_api._session + session2 = client2.transport.create_api._session + assert session1 != session2 + session1 = client1.transport.update_api._session + session2 = client2.transport.update_api._session + assert session1 != session2 + session1 = client1.transport.delete_api._session + session2 = client2.transport.delete_api._session + assert session1 != session2 + session1 = client1.transport.list_api_configs._session + session2 = client2.transport.list_api_configs._session + assert session1 != session2 + session1 = client1.transport.get_api_config._session + session2 = client2.transport.get_api_config._session + assert session1 != session2 + session1 = client1.transport.create_api_config._session + session2 = client2.transport.create_api_config._session + assert session1 != session2 + session1 = client1.transport.update_api_config._session + session2 = client2.transport.update_api_config._session + assert session1 != session2 + session1 = client1.transport.delete_api_config._session + session2 = client2.transport.delete_api_config._session + assert session1 != session2 def test_api_gateway_service_grpc_transport_channel(): @@ -5701,6 +10282,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -5718,6 +10300,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: