From 00dcc297378b1b61480b68d90a763c174f727e6a 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 14:27:32 -0500 Subject: [PATCH] feat: enable "rest" transport in Python for services supporting numeric enums (#70) 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 --- .../network_services_v1/gapic_metadata.json | 200 + .../services/network_services/client.py | 2 + .../network_services/transports/__init__.py | 4 + .../network_services/transports/rest.py | 6371 ++++++++ .../test_network_services.py | 13627 +++++++++++++++- 5 files changed, 19873 insertions(+), 331 deletions(-) create mode 100644 packages/google-cloud-network-services/google/cloud/network_services_v1/services/network_services/transports/rest.py diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1/gapic_metadata.json b/packages/google-cloud-network-services/google/cloud/network_services_v1/gapic_metadata.json index a203db46be4e..2dafd79c9882 100644 --- a/packages/google-cloud-network-services/google/cloud/network_services_v1/gapic_metadata.json +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1/gapic_metadata.json @@ -406,6 +406,206 @@ ] } } + }, + "rest": { + "libraryClient": "NetworkServicesClient", + "rpcs": { + "CreateEndpointPolicy": { + "methods": [ + "create_endpoint_policy" + ] + }, + "CreateGateway": { + "methods": [ + "create_gateway" + ] + }, + "CreateGrpcRoute": { + "methods": [ + "create_grpc_route" + ] + }, + "CreateHttpRoute": { + "methods": [ + "create_http_route" + ] + }, + "CreateMesh": { + "methods": [ + "create_mesh" + ] + }, + "CreateServiceBinding": { + "methods": [ + "create_service_binding" + ] + }, + "CreateTcpRoute": { + "methods": [ + "create_tcp_route" + ] + }, + "CreateTlsRoute": { + "methods": [ + "create_tls_route" + ] + }, + "DeleteEndpointPolicy": { + "methods": [ + "delete_endpoint_policy" + ] + }, + "DeleteGateway": { + "methods": [ + "delete_gateway" + ] + }, + "DeleteGrpcRoute": { + "methods": [ + "delete_grpc_route" + ] + }, + "DeleteHttpRoute": { + "methods": [ + "delete_http_route" + ] + }, + "DeleteMesh": { + "methods": [ + "delete_mesh" + ] + }, + "DeleteServiceBinding": { + "methods": [ + "delete_service_binding" + ] + }, + "DeleteTcpRoute": { + "methods": [ + "delete_tcp_route" + ] + }, + "DeleteTlsRoute": { + "methods": [ + "delete_tls_route" + ] + }, + "GetEndpointPolicy": { + "methods": [ + "get_endpoint_policy" + ] + }, + "GetGateway": { + "methods": [ + "get_gateway" + ] + }, + "GetGrpcRoute": { + "methods": [ + "get_grpc_route" + ] + }, + "GetHttpRoute": { + "methods": [ + "get_http_route" + ] + }, + "GetMesh": { + "methods": [ + "get_mesh" + ] + }, + "GetServiceBinding": { + "methods": [ + "get_service_binding" + ] + }, + "GetTcpRoute": { + "methods": [ + "get_tcp_route" + ] + }, + "GetTlsRoute": { + "methods": [ + "get_tls_route" + ] + }, + "ListEndpointPolicies": { + "methods": [ + "list_endpoint_policies" + ] + }, + "ListGateways": { + "methods": [ + "list_gateways" + ] + }, + "ListGrpcRoutes": { + "methods": [ + "list_grpc_routes" + ] + }, + "ListHttpRoutes": { + "methods": [ + "list_http_routes" + ] + }, + "ListMeshes": { + "methods": [ + "list_meshes" + ] + }, + "ListServiceBindings": { + "methods": [ + "list_service_bindings" + ] + }, + "ListTcpRoutes": { + "methods": [ + "list_tcp_routes" + ] + }, + "ListTlsRoutes": { + "methods": [ + "list_tls_routes" + ] + }, + "UpdateEndpointPolicy": { + "methods": [ + "update_endpoint_policy" + ] + }, + "UpdateGateway": { + "methods": [ + "update_gateway" + ] + }, + "UpdateGrpcRoute": { + "methods": [ + "update_grpc_route" + ] + }, + "UpdateHttpRoute": { + "methods": [ + "update_http_route" + ] + }, + "UpdateMesh": { + "methods": [ + "update_mesh" + ] + }, + "UpdateTcpRoute": { + "methods": [ + "update_tcp_route" + ] + }, + "UpdateTlsRoute": { + "methods": [ + "update_tls_route" + ] + } + } } } } diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1/services/network_services/client.py b/packages/google-cloud-network-services/google/cloud/network_services_v1/services/network_services/client.py index d282ff97a8d0..a93aadbd4652 100644 --- a/packages/google-cloud-network-services/google/cloud/network_services_v1/services/network_services/client.py +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1/services/network_services/client.py @@ -82,6 +82,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, NetworkServicesTransport from .transports.grpc import NetworkServicesGrpcTransport from .transports.grpc_asyncio import NetworkServicesGrpcAsyncIOTransport +from .transports.rest import NetworkServicesRestTransport class NetworkServicesClientMeta(type): @@ -97,6 +98,7 @@ class NetworkServicesClientMeta(type): ) # type: Dict[str, Type[NetworkServicesTransport]] _transport_registry["grpc"] = NetworkServicesGrpcTransport _transport_registry["grpc_asyncio"] = NetworkServicesGrpcAsyncIOTransport + _transport_registry["rest"] = NetworkServicesRestTransport def get_transport_class( cls, diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1/services/network_services/transports/__init__.py b/packages/google-cloud-network-services/google/cloud/network_services_v1/services/network_services/transports/__init__.py index c6a0a8e04edb..3f3fff2ceb5b 100644 --- a/packages/google-cloud-network-services/google/cloud/network_services_v1/services/network_services/transports/__init__.py +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1/services/network_services/transports/__init__.py @@ -19,14 +19,18 @@ from .base import NetworkServicesTransport from .grpc import NetworkServicesGrpcTransport from .grpc_asyncio import NetworkServicesGrpcAsyncIOTransport +from .rest import NetworkServicesRestInterceptor, NetworkServicesRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[NetworkServicesTransport]] _transport_registry["grpc"] = NetworkServicesGrpcTransport _transport_registry["grpc_asyncio"] = NetworkServicesGrpcAsyncIOTransport +_transport_registry["rest"] = NetworkServicesRestTransport __all__ = ( "NetworkServicesTransport", "NetworkServicesGrpcTransport", "NetworkServicesGrpcAsyncIOTransport", + "NetworkServicesRestTransport", + "NetworkServicesRestInterceptor", ) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1/services/network_services/transports/rest.py b/packages/google-cloud-network-services/google/cloud/network_services_v1/services/network_services/transports/rest.py new file mode 100644 index 000000000000..dfa64d341c6e --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1/services/network_services/transports/rest.py @@ -0,0 +1,6371 @@ +# -*- 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.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.network_services_v1.types import ( + endpoint_policy as gcn_endpoint_policy, +) +from google.cloud.network_services_v1.types import ( + service_binding as gcn_service_binding, +) +from google.cloud.network_services_v1.types import endpoint_policy +from google.cloud.network_services_v1.types import gateway +from google.cloud.network_services_v1.types import gateway as gcn_gateway +from google.cloud.network_services_v1.types import grpc_route +from google.cloud.network_services_v1.types import grpc_route as gcn_grpc_route +from google.cloud.network_services_v1.types import http_route +from google.cloud.network_services_v1.types import http_route as gcn_http_route +from google.cloud.network_services_v1.types import mesh +from google.cloud.network_services_v1.types import mesh as gcn_mesh +from google.cloud.network_services_v1.types import service_binding +from google.cloud.network_services_v1.types import tcp_route +from google.cloud.network_services_v1.types import tcp_route as gcn_tcp_route +from google.cloud.network_services_v1.types import tls_route +from google.cloud.network_services_v1.types import tls_route as gcn_tls_route + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import NetworkServicesTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class NetworkServicesRestInterceptor: + """Interceptor for NetworkServices. + + 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 NetworkServicesRestTransport. + + .. code-block:: python + class MyCustomNetworkServicesInterceptor(NetworkServicesRestInterceptor): + def pre_create_endpoint_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_endpoint_policy(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_create_grpc_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_grpc_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_http_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_http_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_mesh(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_mesh(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_service_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_service_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_tcp_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_tcp_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_tls_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_tls_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_endpoint_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_endpoint_policy(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_delete_grpc_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_grpc_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_http_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_http_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_mesh(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_mesh(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_service_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_service_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_tcp_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_tcp_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_tls_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_tls_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_endpoint_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_endpoint_policy(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_get_grpc_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_grpc_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_http_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_http_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_mesh(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_mesh(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_service_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_service_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_tcp_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_tcp_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_tls_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_tls_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_endpoint_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_endpoint_policies(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_list_grpc_routes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_grpc_routes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_http_routes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_http_routes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_meshes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_meshes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_service_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_service_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_tcp_routes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_tcp_routes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_tls_routes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_tls_routes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_endpoint_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_endpoint_policy(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 + + def pre_update_grpc_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_grpc_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_http_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_http_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_mesh(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_mesh(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_tcp_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_tcp_route(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_tls_route(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_tls_route(self, response): + logging.log(f"Received response: {response}") + return response + + transport = NetworkServicesRestTransport(interceptor=MyCustomNetworkServicesInterceptor()) + client = NetworkServicesClient(transport=transport) + + + """ + + def pre_create_endpoint_policy( + self, + request: gcn_endpoint_policy.CreateEndpointPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + gcn_endpoint_policy.CreateEndpointPolicyRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for create_endpoint_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_create_endpoint_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_endpoint_policy + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_create_gateway( + self, + request: gcn_gateway.CreateGatewayRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcn_gateway.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 NetworkServices 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 NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_create_grpc_route( + self, + request: gcn_grpc_route.CreateGrpcRouteRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcn_grpc_route.CreateGrpcRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_grpc_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_create_grpc_route( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_grpc_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_create_http_route( + self, + request: gcn_http_route.CreateHttpRouteRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcn_http_route.CreateHttpRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_http_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_create_http_route( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_http_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_create_mesh( + self, request: gcn_mesh.CreateMeshRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[gcn_mesh.CreateMeshRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_mesh + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_create_mesh( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_mesh + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_create_service_binding( + self, + request: gcn_service_binding.CreateServiceBindingRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + gcn_service_binding.CreateServiceBindingRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for create_service_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_create_service_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_service_binding + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_create_tcp_route( + self, + request: gcn_tcp_route.CreateTcpRouteRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcn_tcp_route.CreateTcpRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_tcp_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_create_tcp_route( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_tcp_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_create_tls_route( + self, + request: gcn_tls_route.CreateTlsRouteRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcn_tls_route.CreateTlsRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_tls_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_create_tls_route( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_tls_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_delete_endpoint_policy( + self, + request: endpoint_policy.DeleteEndpointPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[endpoint_policy.DeleteEndpointPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_endpoint_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_endpoint_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_endpoint_policy + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_delete_gateway( + self, request: gateway.DeleteGatewayRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[gateway.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 NetworkServices 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 NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_delete_grpc_route( + self, + request: grpc_route.DeleteGrpcRouteRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[grpc_route.DeleteGrpcRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_grpc_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_grpc_route( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_grpc_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_delete_http_route( + self, + request: http_route.DeleteHttpRouteRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[http_route.DeleteHttpRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_http_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_http_route( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_http_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_delete_mesh( + self, request: mesh.DeleteMeshRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[mesh.DeleteMeshRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_mesh + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_mesh( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_mesh + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_delete_service_binding( + self, + request: service_binding.DeleteServiceBindingRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service_binding.DeleteServiceBindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_service_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_service_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_service_binding + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_delete_tcp_route( + self, + request: tcp_route.DeleteTcpRouteRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[tcp_route.DeleteTcpRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_tcp_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_tcp_route( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_tcp_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_delete_tls_route( + self, + request: tls_route.DeleteTlsRouteRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[tls_route.DeleteTlsRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_tls_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_tls_route( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_tls_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_get_endpoint_policy( + self, + request: endpoint_policy.GetEndpointPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[endpoint_policy.GetEndpointPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_endpoint_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_endpoint_policy( + self, response: endpoint_policy.EndpointPolicy + ) -> endpoint_policy.EndpointPolicy: + """Post-rpc interceptor for get_endpoint_policy + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_get_gateway( + self, request: gateway.GetGatewayRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[gateway.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 NetworkServices server. + """ + return request, metadata + + def post_get_gateway(self, response: gateway.Gateway) -> gateway.Gateway: + """Post-rpc interceptor for get_gateway + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_get_grpc_route( + self, + request: grpc_route.GetGrpcRouteRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[grpc_route.GetGrpcRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_grpc_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_grpc_route( + self, response: grpc_route.GrpcRoute + ) -> grpc_route.GrpcRoute: + """Post-rpc interceptor for get_grpc_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_get_http_route( + self, + request: http_route.GetHttpRouteRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[http_route.GetHttpRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_http_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_http_route( + self, response: http_route.HttpRoute + ) -> http_route.HttpRoute: + """Post-rpc interceptor for get_http_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_get_mesh( + self, request: mesh.GetMeshRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[mesh.GetMeshRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_mesh + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_mesh(self, response: mesh.Mesh) -> mesh.Mesh: + """Post-rpc interceptor for get_mesh + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_get_service_binding( + self, + request: service_binding.GetServiceBindingRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service_binding.GetServiceBindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_service_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_service_binding( + self, response: service_binding.ServiceBinding + ) -> service_binding.ServiceBinding: + """Post-rpc interceptor for get_service_binding + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_get_tcp_route( + self, request: tcp_route.GetTcpRouteRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[tcp_route.GetTcpRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_tcp_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_tcp_route(self, response: tcp_route.TcpRoute) -> tcp_route.TcpRoute: + """Post-rpc interceptor for get_tcp_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_get_tls_route( + self, request: tls_route.GetTlsRouteRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[tls_route.GetTlsRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_tls_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_tls_route(self, response: tls_route.TlsRoute) -> tls_route.TlsRoute: + """Post-rpc interceptor for get_tls_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_list_endpoint_policies( + self, + request: endpoint_policy.ListEndpointPoliciesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[endpoint_policy.ListEndpointPoliciesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_endpoint_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_endpoint_policies( + self, response: endpoint_policy.ListEndpointPoliciesResponse + ) -> endpoint_policy.ListEndpointPoliciesResponse: + """Post-rpc interceptor for list_endpoint_policies + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_list_gateways( + self, request: gateway.ListGatewaysRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[gateway.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 NetworkServices server. + """ + return request, metadata + + def post_list_gateways( + self, response: gateway.ListGatewaysResponse + ) -> gateway.ListGatewaysResponse: + """Post-rpc interceptor for list_gateways + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_list_grpc_routes( + self, + request: grpc_route.ListGrpcRoutesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[grpc_route.ListGrpcRoutesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_grpc_routes + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_grpc_routes( + self, response: grpc_route.ListGrpcRoutesResponse + ) -> grpc_route.ListGrpcRoutesResponse: + """Post-rpc interceptor for list_grpc_routes + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_list_http_routes( + self, + request: http_route.ListHttpRoutesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[http_route.ListHttpRoutesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_http_routes + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_http_routes( + self, response: http_route.ListHttpRoutesResponse + ) -> http_route.ListHttpRoutesResponse: + """Post-rpc interceptor for list_http_routes + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_list_meshes( + self, request: mesh.ListMeshesRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[mesh.ListMeshesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_meshes + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_meshes( + self, response: mesh.ListMeshesResponse + ) -> mesh.ListMeshesResponse: + """Post-rpc interceptor for list_meshes + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_list_service_bindings( + self, + request: service_binding.ListServiceBindingsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service_binding.ListServiceBindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_service_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_service_bindings( + self, response: service_binding.ListServiceBindingsResponse + ) -> service_binding.ListServiceBindingsResponse: + """Post-rpc interceptor for list_service_bindings + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_list_tcp_routes( + self, + request: tcp_route.ListTcpRoutesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[tcp_route.ListTcpRoutesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_tcp_routes + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_tcp_routes( + self, response: tcp_route.ListTcpRoutesResponse + ) -> tcp_route.ListTcpRoutesResponse: + """Post-rpc interceptor for list_tcp_routes + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_list_tls_routes( + self, + request: tls_route.ListTlsRoutesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[tls_route.ListTlsRoutesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_tls_routes + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_tls_routes( + self, response: tls_route.ListTlsRoutesResponse + ) -> tls_route.ListTlsRoutesResponse: + """Post-rpc interceptor for list_tls_routes + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_update_endpoint_policy( + self, + request: gcn_endpoint_policy.UpdateEndpointPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + gcn_endpoint_policy.UpdateEndpointPolicyRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_endpoint_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_update_endpoint_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_endpoint_policy + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_update_gateway( + self, + request: gcn_gateway.UpdateGatewayRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcn_gateway.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 NetworkServices 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 NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_update_grpc_route( + self, + request: gcn_grpc_route.UpdateGrpcRouteRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcn_grpc_route.UpdateGrpcRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_grpc_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_update_grpc_route( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_grpc_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_update_http_route( + self, + request: gcn_http_route.UpdateHttpRouteRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcn_http_route.UpdateHttpRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_http_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_update_http_route( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_http_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_update_mesh( + self, request: gcn_mesh.UpdateMeshRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[gcn_mesh.UpdateMeshRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_mesh + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_update_mesh( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_mesh + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_update_tcp_route( + self, + request: gcn_tcp_route.UpdateTcpRouteRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcn_tcp_route.UpdateTcpRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_tcp_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_update_tcp_route( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_tcp_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_update_tls_route( + self, + request: gcn_tls_route.UpdateTlsRouteRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcn_tls_route.UpdateTlsRouteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_tls_route + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_update_tls_route( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_tls_route + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> locations_pb2.Location: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.GetLocationRequest + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> locations_pb2.ListLocationsResponse: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsRequest + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> policy_pb2.Policy: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: iam_policy_pb2.GetIamPolicyRequest + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> policy_pb2.Policy: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: iam_policy_pb2.SetIamPolicyRequest + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsRequest + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> None: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_cancel_operation( + self, response: operations_pb2.CancelOperationRequest + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> None: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_operation( + self, response: operations_pb2.DeleteOperationRequest + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> operations_pb2.Operation: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.GetOperationRequest + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> operations_pb2.ListOperationsResponse: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsRequest + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class NetworkServicesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: NetworkServicesRestInterceptor + + +class NetworkServicesRestTransport(NetworkServicesTransport): + """REST backend transport for NetworkServices. + + 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 = "networkservices.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[NetworkServicesRestInterceptor] = 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 NetworkServicesRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateEndpointPolicy(NetworkServicesRestStub): + def __hash__(self): + return hash("CreateEndpointPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "endpointPolicyId": "", + } + + @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: gcn_endpoint_policy.CreateEndpointPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create endpoint policy method over HTTP. + + Args: + request (~.gcn_endpoint_policy.CreateEndpointPolicyRequest): + The request object. Request used with the + CreateEndpointPolicy method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/*}/endpointPolicies", + "body": "endpoint_policy", + }, + ] + request, metadata = self._interceptor.pre_create_endpoint_policy( + request, metadata + ) + pb_request = gcn_endpoint_policy.CreateEndpointPolicyRequest.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_endpoint_policy(resp) + return resp + + class _CreateGateway(NetworkServicesRestStub): + 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: gcn_gateway.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 (~.gcn_gateway.CreateGatewayRequest): + The request object. Request used by the CreateGateway + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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 = gcn_gateway.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 _CreateGrpcRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("CreateGrpcRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "grpcRouteId": "", + } + + @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: gcn_grpc_route.CreateGrpcRouteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create grpc route method over HTTP. + + Args: + request (~.gcn_grpc_route.CreateGrpcRouteRequest): + The request object. Request used by the CreateGrpcRoute + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/*}/grpcRoutes", + "body": "grpc_route", + }, + ] + request, metadata = self._interceptor.pre_create_grpc_route( + request, metadata + ) + pb_request = gcn_grpc_route.CreateGrpcRouteRequest.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_grpc_route(resp) + return resp + + class _CreateHttpRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("CreateHttpRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "httpRouteId": "", + } + + @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: gcn_http_route.CreateHttpRouteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create http route method over HTTP. + + Args: + request (~.gcn_http_route.CreateHttpRouteRequest): + The request object. Request used by the HttpRoute method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/*}/httpRoutes", + "body": "http_route", + }, + ] + request, metadata = self._interceptor.pre_create_http_route( + request, metadata + ) + pb_request = gcn_http_route.CreateHttpRouteRequest.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_http_route(resp) + return resp + + class _CreateMesh(NetworkServicesRestStub): + def __hash__(self): + return hash("CreateMesh") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "meshId": "", + } + + @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: gcn_mesh.CreateMeshRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create mesh method over HTTP. + + Args: + request (~.gcn_mesh.CreateMeshRequest): + The request object. Request used by the CreateMesh + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/*}/meshes", + "body": "mesh", + }, + ] + request, metadata = self._interceptor.pre_create_mesh(request, metadata) + pb_request = gcn_mesh.CreateMeshRequest.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_mesh(resp) + return resp + + class _CreateServiceBinding(NetworkServicesRestStub): + def __hash__(self): + return hash("CreateServiceBinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "serviceBindingId": "", + } + + @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: gcn_service_binding.CreateServiceBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create service binding method over HTTP. + + Args: + request (~.gcn_service_binding.CreateServiceBindingRequest): + The request object. Request used by the ServiceBinding + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/*}/serviceBindings", + "body": "service_binding", + }, + ] + request, metadata = self._interceptor.pre_create_service_binding( + request, metadata + ) + pb_request = gcn_service_binding.CreateServiceBindingRequest.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_service_binding(resp) + return resp + + class _CreateTcpRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("CreateTcpRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "tcpRouteId": "", + } + + @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: gcn_tcp_route.CreateTcpRouteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create tcp route method over HTTP. + + Args: + request (~.gcn_tcp_route.CreateTcpRouteRequest): + The request object. Request used by the TcpRoute method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/*}/tcpRoutes", + "body": "tcp_route", + }, + ] + request, metadata = self._interceptor.pre_create_tcp_route( + request, metadata + ) + pb_request = gcn_tcp_route.CreateTcpRouteRequest.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_tcp_route(resp) + return resp + + class _CreateTlsRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("CreateTlsRoute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "tlsRouteId": "", + } + + @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: gcn_tls_route.CreateTlsRouteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create tls route method over HTTP. + + Args: + request (~.gcn_tls_route.CreateTlsRouteRequest): + The request object. Request used by the TlsRoute method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/*}/tlsRoutes", + "body": "tls_route", + }, + ] + request, metadata = self._interceptor.pre_create_tls_route( + request, metadata + ) + pb_request = gcn_tls_route.CreateTlsRouteRequest.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_tls_route(resp) + return resp + + class _DeleteEndpointPolicy(NetworkServicesRestStub): + def __hash__(self): + return hash("DeleteEndpointPolicy") + + __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: endpoint_policy.DeleteEndpointPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete endpoint policy method over HTTP. + + Args: + request (~.endpoint_policy.DeleteEndpointPolicyRequest): + The request object. Request used with the + DeleteEndpointPolicy method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/*/endpointPolicies/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_endpoint_policy( + request, metadata + ) + pb_request = endpoint_policy.DeleteEndpointPolicyRequest.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_endpoint_policy(resp) + return resp + + class _DeleteGateway(NetworkServicesRestStub): + 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: gateway.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 (~.gateway.DeleteGatewayRequest): + The request object. Request used by the DeleteGateway + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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 = gateway.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 _DeleteGrpcRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("DeleteGrpcRoute") + + __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: grpc_route.DeleteGrpcRouteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete grpc route method over HTTP. + + Args: + request (~.grpc_route.DeleteGrpcRouteRequest): + The request object. Request used by the DeleteGrpcRoute + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/*/grpcRoutes/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_grpc_route( + request, metadata + ) + pb_request = grpc_route.DeleteGrpcRouteRequest.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_grpc_route(resp) + return resp + + class _DeleteHttpRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("DeleteHttpRoute") + + __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: http_route.DeleteHttpRouteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete http route method over HTTP. + + Args: + request (~.http_route.DeleteHttpRouteRequest): + The request object. Request used by the DeleteHttpRoute + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/*/httpRoutes/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_http_route( + request, metadata + ) + pb_request = http_route.DeleteHttpRouteRequest.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_http_route(resp) + return resp + + class _DeleteMesh(NetworkServicesRestStub): + def __hash__(self): + return hash("DeleteMesh") + + __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: mesh.DeleteMeshRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete mesh method over HTTP. + + Args: + request (~.mesh.DeleteMeshRequest): + The request object. Request used by the DeleteMesh + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/*/meshes/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_mesh(request, metadata) + pb_request = mesh.DeleteMeshRequest.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_mesh(resp) + return resp + + class _DeleteServiceBinding(NetworkServicesRestStub): + def __hash__(self): + return hash("DeleteServiceBinding") + + __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: service_binding.DeleteServiceBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete service binding method over HTTP. + + Args: + request (~.service_binding.DeleteServiceBindingRequest): + The request object. Request used by the + DeleteServiceBinding method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/*/serviceBindings/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_service_binding( + request, metadata + ) + pb_request = service_binding.DeleteServiceBindingRequest.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_service_binding(resp) + return resp + + class _DeleteTcpRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("DeleteTcpRoute") + + __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: tcp_route.DeleteTcpRouteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete tcp route method over HTTP. + + Args: + request (~.tcp_route.DeleteTcpRouteRequest): + The request object. Request used by the DeleteTcpRoute + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/*/tcpRoutes/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_tcp_route( + request, metadata + ) + pb_request = tcp_route.DeleteTcpRouteRequest.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_tcp_route(resp) + return resp + + class _DeleteTlsRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("DeleteTlsRoute") + + __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: tls_route.DeleteTlsRouteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete tls route method over HTTP. + + Args: + request (~.tls_route.DeleteTlsRouteRequest): + The request object. Request used by the DeleteTlsRoute + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/*/tlsRoutes/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_tls_route( + request, metadata + ) + pb_request = tls_route.DeleteTlsRouteRequest.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_tls_route(resp) + return resp + + class _GetEndpointPolicy(NetworkServicesRestStub): + def __hash__(self): + return hash("GetEndpointPolicy") + + __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: endpoint_policy.GetEndpointPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> endpoint_policy.EndpointPolicy: + r"""Call the get endpoint policy method over HTTP. + + Args: + request (~.endpoint_policy.GetEndpointPolicyRequest): + The request object. Request used with the + GetEndpointPolicy method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.endpoint_policy.EndpointPolicy: + EndpointPolicy is a resource that + helps apply desired configuration on the + endpoints that match specific criteria. + For example, this resource can be used + to apply "authentication config" an all + endpoints that serve on port 8080. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/endpointPolicies/*}", + }, + ] + request, metadata = self._interceptor.pre_get_endpoint_policy( + request, metadata + ) + pb_request = endpoint_policy.GetEndpointPolicyRequest.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 = endpoint_policy.EndpointPolicy() + pb_resp = endpoint_policy.EndpointPolicy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_endpoint_policy(resp) + return resp + + class _GetGateway(NetworkServicesRestStub): + 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: gateway.GetGatewayRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gateway.Gateway: + r"""Call the get gateway method over HTTP. + + Args: + request (~.gateway.GetGatewayRequest): + The request object. Request used by the GetGateway + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gateway.Gateway: + Gateway represents the configuration + for a proxy, typically a load balancer. + It captures the ip:port over which the + services are exposed by the proxy, along + with any policy configurations. Routes + have reference to to Gateways to dictate + how requests should be routed by this + Gateway. + + """ + + 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 = gateway.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 = gateway.Gateway() + pb_resp = gateway.Gateway.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_gateway(resp) + return resp + + class _GetGrpcRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("GetGrpcRoute") + + __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: grpc_route.GetGrpcRouteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grpc_route.GrpcRoute: + r"""Call the get grpc route method over HTTP. + + Args: + request (~.grpc_route.GetGrpcRouteRequest): + The request object. Request used by the GetGrpcRoute + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.grpc_route.GrpcRoute: + GrpcRoute is the resource defining + how gRPC traffic routed by a Mesh or + Gateway resource is routed. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/grpcRoutes/*}", + }, + ] + request, metadata = self._interceptor.pre_get_grpc_route(request, metadata) + pb_request = grpc_route.GetGrpcRouteRequest.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 = grpc_route.GrpcRoute() + pb_resp = grpc_route.GrpcRoute.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_grpc_route(resp) + return resp + + class _GetHttpRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("GetHttpRoute") + + __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: http_route.GetHttpRouteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> http_route.HttpRoute: + r"""Call the get http route method over HTTP. + + Args: + request (~.http_route.GetHttpRouteRequest): + The request object. Request used by the GetHttpRoute + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.http_route.HttpRoute: + HttpRoute is the resource defining + how HTTP traffic should be routed by a + Mesh or Gateway resource. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/httpRoutes/*}", + }, + ] + request, metadata = self._interceptor.pre_get_http_route(request, metadata) + pb_request = http_route.GetHttpRouteRequest.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 = http_route.HttpRoute() + pb_resp = http_route.HttpRoute.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_http_route(resp) + return resp + + class _GetMesh(NetworkServicesRestStub): + def __hash__(self): + return hash("GetMesh") + + __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: mesh.GetMeshRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> mesh.Mesh: + r"""Call the get mesh method over HTTP. + + Args: + request (~.mesh.GetMeshRequest): + The request object. Request used by the GetMesh method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.mesh.Mesh: + Mesh represents a logical + configuration grouping for workload to + workload communication within a service + mesh. Routes that point to mesh dictate + how requests are routed within this + logical mesh boundary. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/meshes/*}", + }, + ] + request, metadata = self._interceptor.pre_get_mesh(request, metadata) + pb_request = mesh.GetMeshRequest.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 = mesh.Mesh() + pb_resp = mesh.Mesh.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_mesh(resp) + return resp + + class _GetServiceBinding(NetworkServicesRestStub): + def __hash__(self): + return hash("GetServiceBinding") + + __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: service_binding.GetServiceBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service_binding.ServiceBinding: + r"""Call the get service binding method over HTTP. + + Args: + request (~.service_binding.GetServiceBindingRequest): + The request object. Request used by the GetServiceBinding + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service_binding.ServiceBinding: + ServiceBinding is the resource that + defines a Service Directory Service to + be used in a BackendService resource. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/serviceBindings/*}", + }, + ] + request, metadata = self._interceptor.pre_get_service_binding( + request, metadata + ) + pb_request = service_binding.GetServiceBindingRequest.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 = service_binding.ServiceBinding() + pb_resp = service_binding.ServiceBinding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_service_binding(resp) + return resp + + class _GetTcpRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("GetTcpRoute") + + __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: tcp_route.GetTcpRouteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tcp_route.TcpRoute: + r"""Call the get tcp route method over HTTP. + + Args: + request (~.tcp_route.GetTcpRouteRequest): + The request object. Request used by the GetTcpRoute + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.tcp_route.TcpRoute: + TcpRoute is the resource defining how + TCP traffic should be routed by a + Mesh/Gateway resource. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/tcpRoutes/*}", + }, + ] + request, metadata = self._interceptor.pre_get_tcp_route(request, metadata) + pb_request = tcp_route.GetTcpRouteRequest.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 = tcp_route.TcpRoute() + pb_resp = tcp_route.TcpRoute.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_tcp_route(resp) + return resp + + class _GetTlsRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("GetTlsRoute") + + __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: tls_route.GetTlsRouteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tls_route.TlsRoute: + r"""Call the get tls route method over HTTP. + + Args: + request (~.tls_route.GetTlsRouteRequest): + The request object. Request used by the GetTlsRoute + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.tls_route.TlsRoute: + TlsRoute defines how traffic should + be routed based on SNI and other + matching L3 attributes. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/tlsRoutes/*}", + }, + ] + request, metadata = self._interceptor.pre_get_tls_route(request, metadata) + pb_request = tls_route.GetTlsRouteRequest.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 = tls_route.TlsRoute() + pb_resp = tls_route.TlsRoute.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_tls_route(resp) + return resp + + class _ListEndpointPolicies(NetworkServicesRestStub): + def __hash__(self): + return hash("ListEndpointPolicies") + + __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: endpoint_policy.ListEndpointPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> endpoint_policy.ListEndpointPoliciesResponse: + r"""Call the list endpoint policies method over HTTP. + + Args: + request (~.endpoint_policy.ListEndpointPoliciesRequest): + The request object. Request used with the + ListEndpointPolicies method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.endpoint_policy.ListEndpointPoliciesResponse: + Response returned by the + ListEndpointPolicies method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/endpointPolicies", + }, + ] + request, metadata = self._interceptor.pre_list_endpoint_policies( + request, metadata + ) + pb_request = endpoint_policy.ListEndpointPoliciesRequest.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 = endpoint_policy.ListEndpointPoliciesResponse() + pb_resp = endpoint_policy.ListEndpointPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_endpoint_policies(resp) + return resp + + class _ListGateways(NetworkServicesRestStub): + 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: gateway.ListGatewaysRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gateway.ListGatewaysResponse: + r"""Call the list gateways method over HTTP. + + Args: + request (~.gateway.ListGatewaysRequest): + The request object. Request used with the ListGateways + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gateway.ListGatewaysResponse: + Response returned by the ListGateways + method. + + """ + + 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 = gateway.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 = gateway.ListGatewaysResponse() + pb_resp = gateway.ListGatewaysResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_gateways(resp) + return resp + + class _ListGrpcRoutes(NetworkServicesRestStub): + def __hash__(self): + return hash("ListGrpcRoutes") + + __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: grpc_route.ListGrpcRoutesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grpc_route.ListGrpcRoutesResponse: + r"""Call the list grpc routes method over HTTP. + + Args: + request (~.grpc_route.ListGrpcRoutesRequest): + The request object. Request used with the ListGrpcRoutes + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.grpc_route.ListGrpcRoutesResponse: + Response returned by the + ListGrpcRoutes method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/grpcRoutes", + }, + ] + request, metadata = self._interceptor.pre_list_grpc_routes( + request, metadata + ) + pb_request = grpc_route.ListGrpcRoutesRequest.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 = grpc_route.ListGrpcRoutesResponse() + pb_resp = grpc_route.ListGrpcRoutesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_grpc_routes(resp) + return resp + + class _ListHttpRoutes(NetworkServicesRestStub): + def __hash__(self): + return hash("ListHttpRoutes") + + __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: http_route.ListHttpRoutesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> http_route.ListHttpRoutesResponse: + r"""Call the list http routes method over HTTP. + + Args: + request (~.http_route.ListHttpRoutesRequest): + The request object. Request used with the ListHttpRoutes + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.http_route.ListHttpRoutesResponse: + Response returned by the + ListHttpRoutes method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/httpRoutes", + }, + ] + request, metadata = self._interceptor.pre_list_http_routes( + request, metadata + ) + pb_request = http_route.ListHttpRoutesRequest.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 = http_route.ListHttpRoutesResponse() + pb_resp = http_route.ListHttpRoutesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_http_routes(resp) + return resp + + class _ListMeshes(NetworkServicesRestStub): + def __hash__(self): + return hash("ListMeshes") + + __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: mesh.ListMeshesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> mesh.ListMeshesResponse: + r"""Call the list meshes method over HTTP. + + Args: + request (~.mesh.ListMeshesRequest): + The request object. Request used with the ListMeshes + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.mesh.ListMeshesResponse: + Response returned by the ListMeshes + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/meshes", + }, + ] + request, metadata = self._interceptor.pre_list_meshes(request, metadata) + pb_request = mesh.ListMeshesRequest.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 = mesh.ListMeshesResponse() + pb_resp = mesh.ListMeshesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_meshes(resp) + return resp + + class _ListServiceBindings(NetworkServicesRestStub): + def __hash__(self): + return hash("ListServiceBindings") + + __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: service_binding.ListServiceBindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service_binding.ListServiceBindingsResponse: + r"""Call the list service bindings method over HTTP. + + Args: + request (~.service_binding.ListServiceBindingsRequest): + The request object. Request used with the + ListServiceBindings method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service_binding.ListServiceBindingsResponse: + Response returned by the + ListServiceBindings method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/serviceBindings", + }, + ] + request, metadata = self._interceptor.pre_list_service_bindings( + request, metadata + ) + pb_request = service_binding.ListServiceBindingsRequest.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 = service_binding.ListServiceBindingsResponse() + pb_resp = service_binding.ListServiceBindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_service_bindings(resp) + return resp + + class _ListTcpRoutes(NetworkServicesRestStub): + def __hash__(self): + return hash("ListTcpRoutes") + + __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: tcp_route.ListTcpRoutesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tcp_route.ListTcpRoutesResponse: + r"""Call the list tcp routes method over HTTP. + + Args: + request (~.tcp_route.ListTcpRoutesRequest): + The request object. Request used with the ListTcpRoutes + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.tcp_route.ListTcpRoutesResponse: + Response returned by the + ListTcpRoutes method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/tcpRoutes", + }, + ] + request, metadata = self._interceptor.pre_list_tcp_routes(request, metadata) + pb_request = tcp_route.ListTcpRoutesRequest.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 = tcp_route.ListTcpRoutesResponse() + pb_resp = tcp_route.ListTcpRoutesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_tcp_routes(resp) + return resp + + class _ListTlsRoutes(NetworkServicesRestStub): + def __hash__(self): + return hash("ListTlsRoutes") + + __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: tls_route.ListTlsRoutesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> tls_route.ListTlsRoutesResponse: + r"""Call the list tls routes method over HTTP. + + Args: + request (~.tls_route.ListTlsRoutesRequest): + The request object. Request used with the ListTlsRoutes + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.tls_route.ListTlsRoutesResponse: + Response returned by the + ListTlsRoutes method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/tlsRoutes", + }, + ] + request, metadata = self._interceptor.pre_list_tls_routes(request, metadata) + pb_request = tls_route.ListTlsRoutesRequest.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 = tls_route.ListTlsRoutesResponse() + pb_resp = tls_route.ListTlsRoutesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_tls_routes(resp) + return resp + + class _UpdateEndpointPolicy(NetworkServicesRestStub): + def __hash__(self): + return hash("UpdateEndpointPolicy") + + __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: gcn_endpoint_policy.UpdateEndpointPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update endpoint policy method over HTTP. + + Args: + request (~.gcn_endpoint_policy.UpdateEndpointPolicyRequest): + The request object. Request used with the + UpdateEndpointPolicy method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/{endpoint_policy.name=projects/*/locations/*/endpointPolicies/*}", + "body": "endpoint_policy", + }, + ] + request, metadata = self._interceptor.pre_update_endpoint_policy( + request, metadata + ) + pb_request = gcn_endpoint_policy.UpdateEndpointPolicyRequest.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_endpoint_policy(resp) + return resp + + class _UpdateGateway(NetworkServicesRestStub): + 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: gcn_gateway.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 (~.gcn_gateway.UpdateGatewayRequest): + The request object. Request used by the UpdateGateway + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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 = gcn_gateway.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 + + class _UpdateGrpcRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("UpdateGrpcRoute") + + __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: gcn_grpc_route.UpdateGrpcRouteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update grpc route method over HTTP. + + Args: + request (~.gcn_grpc_route.UpdateGrpcRouteRequest): + The request object. Request used by the UpdateGrpcRoute + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/{grpc_route.name=projects/*/locations/*/grpcRoutes/*}", + "body": "grpc_route", + }, + ] + request, metadata = self._interceptor.pre_update_grpc_route( + request, metadata + ) + pb_request = gcn_grpc_route.UpdateGrpcRouteRequest.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_grpc_route(resp) + return resp + + class _UpdateHttpRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("UpdateHttpRoute") + + __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: gcn_http_route.UpdateHttpRouteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update http route method over HTTP. + + Args: + request (~.gcn_http_route.UpdateHttpRouteRequest): + The request object. Request used by the UpdateHttpRoute + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/{http_route.name=projects/*/locations/*/httpRoutes/*}", + "body": "http_route", + }, + ] + request, metadata = self._interceptor.pre_update_http_route( + request, metadata + ) + pb_request = gcn_http_route.UpdateHttpRouteRequest.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_http_route(resp) + return resp + + class _UpdateMesh(NetworkServicesRestStub): + def __hash__(self): + return hash("UpdateMesh") + + __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: gcn_mesh.UpdateMeshRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update mesh method over HTTP. + + Args: + request (~.gcn_mesh.UpdateMeshRequest): + The request object. Request used by the UpdateMesh + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/{mesh.name=projects/*/locations/*/meshes/*}", + "body": "mesh", + }, + ] + request, metadata = self._interceptor.pre_update_mesh(request, metadata) + pb_request = gcn_mesh.UpdateMeshRequest.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_mesh(resp) + return resp + + class _UpdateTcpRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("UpdateTcpRoute") + + __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: gcn_tcp_route.UpdateTcpRouteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update tcp route method over HTTP. + + Args: + request (~.gcn_tcp_route.UpdateTcpRouteRequest): + The request object. Request used by the UpdateTcpRoute + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/{tcp_route.name=projects/*/locations/*/tcpRoutes/*}", + "body": "tcp_route", + }, + ] + request, metadata = self._interceptor.pre_update_tcp_route( + request, metadata + ) + pb_request = gcn_tcp_route.UpdateTcpRouteRequest.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_tcp_route(resp) + return resp + + class _UpdateTlsRoute(NetworkServicesRestStub): + def __hash__(self): + return hash("UpdateTlsRoute") + + __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: gcn_tls_route.UpdateTlsRouteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update tls route method over HTTP. + + Args: + request (~.gcn_tls_route.UpdateTlsRouteRequest): + The request object. Request used by the UpdateTlsRoute + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + 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/{tls_route.name=projects/*/locations/*/tlsRoutes/*}", + "body": "tls_route", + }, + ] + request, metadata = self._interceptor.pre_update_tls_route( + request, metadata + ) + pb_request = gcn_tls_route.UpdateTlsRouteRequest.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_tls_route(resp) + return resp + + @property + def create_endpoint_policy( + self, + ) -> Callable[ + [gcn_endpoint_policy.CreateEndpointPolicyRequest], 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._CreateEndpointPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_gateway( + self, + ) -> Callable[[gcn_gateway.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 create_grpc_route( + self, + ) -> Callable[[gcn_grpc_route.CreateGrpcRouteRequest], 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._CreateGrpcRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_http_route( + self, + ) -> Callable[[gcn_http_route.CreateHttpRouteRequest], 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._CreateHttpRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_mesh( + self, + ) -> Callable[[gcn_mesh.CreateMeshRequest], 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._CreateMesh(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_service_binding( + self, + ) -> Callable[ + [gcn_service_binding.CreateServiceBindingRequest], 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._CreateServiceBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_tcp_route( + self, + ) -> Callable[[gcn_tcp_route.CreateTcpRouteRequest], 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._CreateTcpRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_tls_route( + self, + ) -> Callable[[gcn_tls_route.CreateTlsRouteRequest], 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._CreateTlsRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_endpoint_policy( + self, + ) -> Callable[ + [endpoint_policy.DeleteEndpointPolicyRequest], 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._DeleteEndpointPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_gateway( + self, + ) -> Callable[[gateway.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 delete_grpc_route( + self, + ) -> Callable[[grpc_route.DeleteGrpcRouteRequest], 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._DeleteGrpcRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_http_route( + self, + ) -> Callable[[http_route.DeleteHttpRouteRequest], 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._DeleteHttpRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_mesh( + self, + ) -> Callable[[mesh.DeleteMeshRequest], 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._DeleteMesh(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_service_binding( + self, + ) -> Callable[ + [service_binding.DeleteServiceBindingRequest], 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._DeleteServiceBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_tcp_route( + self, + ) -> Callable[[tcp_route.DeleteTcpRouteRequest], 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._DeleteTcpRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_tls_route( + self, + ) -> Callable[[tls_route.DeleteTlsRouteRequest], 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._DeleteTlsRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_endpoint_policy( + self, + ) -> Callable[ + [endpoint_policy.GetEndpointPolicyRequest], endpoint_policy.EndpointPolicy + ]: + # 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._GetEndpointPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_gateway(self) -> Callable[[gateway.GetGatewayRequest], gateway.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 get_grpc_route( + self, + ) -> Callable[[grpc_route.GetGrpcRouteRequest], grpc_route.GrpcRoute]: + # 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._GetGrpcRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_http_route( + self, + ) -> Callable[[http_route.GetHttpRouteRequest], http_route.HttpRoute]: + # 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._GetHttpRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_mesh(self) -> Callable[[mesh.GetMeshRequest], mesh.Mesh]: + # 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._GetMesh(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_service_binding( + self, + ) -> Callable[ + [service_binding.GetServiceBindingRequest], service_binding.ServiceBinding + ]: + # 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._GetServiceBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_tcp_route( + self, + ) -> Callable[[tcp_route.GetTcpRouteRequest], tcp_route.TcpRoute]: + # 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._GetTcpRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_tls_route( + self, + ) -> Callable[[tls_route.GetTlsRouteRequest], tls_route.TlsRoute]: + # 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._GetTlsRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_endpoint_policies( + self, + ) -> Callable[ + [endpoint_policy.ListEndpointPoliciesRequest], + endpoint_policy.ListEndpointPoliciesResponse, + ]: + # 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._ListEndpointPolicies(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_gateways( + self, + ) -> Callable[[gateway.ListGatewaysRequest], gateway.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 list_grpc_routes( + self, + ) -> Callable[ + [grpc_route.ListGrpcRoutesRequest], grpc_route.ListGrpcRoutesResponse + ]: + # 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._ListGrpcRoutes(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_http_routes( + self, + ) -> Callable[ + [http_route.ListHttpRoutesRequest], http_route.ListHttpRoutesResponse + ]: + # 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._ListHttpRoutes(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_meshes( + self, + ) -> Callable[[mesh.ListMeshesRequest], mesh.ListMeshesResponse]: + # 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._ListMeshes(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_service_bindings( + self, + ) -> Callable[ + [service_binding.ListServiceBindingsRequest], + service_binding.ListServiceBindingsResponse, + ]: + # 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._ListServiceBindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_tcp_routes( + self, + ) -> Callable[[tcp_route.ListTcpRoutesRequest], tcp_route.ListTcpRoutesResponse]: + # 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._ListTcpRoutes(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_tls_routes( + self, + ) -> Callable[[tls_route.ListTlsRoutesRequest], tls_route.ListTlsRoutesResponse]: + # 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._ListTlsRoutes(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_endpoint_policy( + self, + ) -> Callable[ + [gcn_endpoint_policy.UpdateEndpointPolicyRequest], 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._UpdateEndpointPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_gateway( + self, + ) -> Callable[[gcn_gateway.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 update_grpc_route( + self, + ) -> Callable[[gcn_grpc_route.UpdateGrpcRouteRequest], 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._UpdateGrpcRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_http_route( + self, + ) -> Callable[[gcn_http_route.UpdateHttpRouteRequest], 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._UpdateHttpRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_mesh( + self, + ) -> Callable[[gcn_mesh.UpdateMeshRequest], 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._UpdateMesh(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_tcp_route( + self, + ) -> Callable[[gcn_tcp_route.UpdateTcpRouteRequest], 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._UpdateTcpRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_tls_route( + self, + ) -> Callable[[gcn_tls_route.UpdateTlsRouteRequest], 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._UpdateTlsRoute(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(NetworkServicesRestStub): + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(NetworkServicesRestStub): + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/locations", + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(NetworkServicesRestStub): + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/edgeCacheKeysets/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/edgeCacheOrigins/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/edgeCacheServices/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/endpointPolicies/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/serviceBindings/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/meshes/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/gateways/*}:getIamPolicy", + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(NetworkServicesRestStub): + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/edgeCacheKeysets/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/edgeCacheOrigins/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/edgeCacheServices/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/endpointPolicies/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/serviceBindings/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/meshes/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/gateways/*}:setIamPolicy", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + 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) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(NetworkServicesRestStub): + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/edgeCacheKeysets/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/edgeCacheOrigins/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/edgeCacheServices/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/endpointPolicies/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/serviceBindings/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/meshes/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/gateways/*}:testIamPermissions", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + 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) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(NetworkServicesRestStub): + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + 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 self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(NetworkServicesRestStub): + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(NetworkServicesRestStub): + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(NetworkServicesRestStub): + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("NetworkServicesRestTransport",) diff --git a/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1/test_network_services.py b/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1/test_network_services.py index 74e49dd23c77..8f28373f1aa4 100644 --- a/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1/test_network_services.py +++ b/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1/test_network_services.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 ( @@ -48,12 +50,15 @@ from google.protobuf import duration_pb2 # type: ignore 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.network_services_v1.services.network_services import ( NetworkServicesAsyncClient, @@ -133,6 +138,7 @@ def test__get_default_mtls_endpoint(): [ (NetworkServicesClient, "grpc"), (NetworkServicesAsyncClient, "grpc_asyncio"), + (NetworkServicesClient, "rest"), ], ) def test_network_services_client_from_service_account_info( @@ -148,7 +154,11 @@ def test_network_services_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("networkservices.googleapis.com:443") + assert client.transport._host == ( + "networkservices.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networkservices.googleapis.com" + ) @pytest.mark.parametrize( @@ -156,6 +166,7 @@ def test_network_services_client_from_service_account_info( [ (transports.NetworkServicesGrpcTransport, "grpc"), (transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.NetworkServicesRestTransport, "rest"), ], ) def test_network_services_client_service_account_always_use_jwt( @@ -181,6 +192,7 @@ def test_network_services_client_service_account_always_use_jwt( [ (NetworkServicesClient, "grpc"), (NetworkServicesAsyncClient, "grpc_asyncio"), + (NetworkServicesClient, "rest"), ], ) def test_network_services_client_from_service_account_file( @@ -203,13 +215,18 @@ def test_network_services_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("networkservices.googleapis.com:443") + assert client.transport._host == ( + "networkservices.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networkservices.googleapis.com" + ) def test_network_services_client_get_transport_class(): transport = NetworkServicesClient.get_transport_class() available_transports = [ transports.NetworkServicesGrpcTransport, + transports.NetworkServicesRestTransport, ] assert transport in available_transports @@ -226,6 +243,7 @@ def test_network_services_client_get_transport_class(): transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio", ), + (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest"), ], ) @mock.patch.object( @@ -381,6 +399,18 @@ def test_network_services_client_client_options( "grpc_asyncio", "false", ), + ( + NetworkServicesClient, + transports.NetworkServicesRestTransport, + "rest", + "true", + ), + ( + NetworkServicesClient, + transports.NetworkServicesRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -580,6 +610,7 @@ def test_network_services_client_get_mtls_endpoint_and_cert_source(client_class) transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio", ), + (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest"), ], ) def test_network_services_client_client_options_scopes( @@ -620,6 +651,7 @@ def test_network_services_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest", None), ], ) def test_network_services_client_client_options_credentials_file( @@ -11737,142 +11769,12369 @@ async def test_delete_mesh_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.NetworkServicesGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + endpoint_policy.ListEndpointPoliciesRequest, + dict, + ], +) +def test_list_endpoint_policies_rest(request_type): + client = NetworkServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = NetworkServicesClient( - 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 = endpoint_policy.ListEndpointPoliciesResponse( + next_page_token="next_page_token_value", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.NetworkServicesGrpcTransport( + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = endpoint_policy.ListEndpointPoliciesResponse.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_endpoint_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEndpointPoliciesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_endpoint_policies_rest_required_fields( + request_type=endpoint_policy.ListEndpointPoliciesRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_endpoint_policies._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_endpoint_policies._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = NetworkServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = endpoint_policy.ListEndpointPoliciesResponse() + # 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 = endpoint_policy.ListEndpointPoliciesResponse.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_endpoint_policies(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_endpoint_policies_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - with pytest.raises(ValueError): - client = NetworkServicesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + + unset_fields = transport.list_endpoint_policies._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) ) + & set(("parent",)) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.NetworkServicesGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_endpoint_policies_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = NetworkServicesClient( - client_options=options, - transport=transport, + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_endpoint_policies" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_list_endpoint_policies" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = endpoint_policy.ListEndpointPoliciesRequest.pb( + endpoint_policy.ListEndpointPoliciesRequest() + ) + 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 = ( + endpoint_policy.ListEndpointPoliciesResponse.to_json( + endpoint_policy.ListEndpointPoliciesResponse() + ) ) - # 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 = NetworkServicesClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + request = endpoint_policy.ListEndpointPoliciesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = endpoint_policy.ListEndpointPoliciesResponse() + + client.list_endpoint_policies( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # It is an error to provide scopes and a transport instance. - transport = transports.NetworkServicesGrpcTransport( + pre.assert_called_once() + post.assert_called_once() + + +def test_list_endpoint_policies_rest_bad_request( + transport: str = "rest", request_type=endpoint_policy.ListEndpointPoliciesRequest +): + client = NetworkServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - with pytest.raises(ValueError): - client = NetworkServicesClient( - 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.NetworkServicesGrpcTransport( + # 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_endpoint_policies(request) + + +def test_list_endpoint_policies_rest_flattened(): + client = NetworkServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = NetworkServicesClient(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 = endpoint_policy.ListEndpointPoliciesResponse() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.NetworkServicesGrpcTransport( + # 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 = endpoint_policy.ListEndpointPoliciesResponse.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_endpoint_policies(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/endpointPolicies" + % client.transport._host, + args[1], + ) + + +def test_list_endpoint_policies_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel - transport = transports.NetworkServicesGrpcAsyncIOTransport( + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_endpoint_policies( + endpoint_policy.ListEndpointPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_endpoint_policies_rest_pager(transport: str = "rest"): + client = NetworkServicesClient( 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 = ( + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + next_page_token="abc", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[], + next_page_token="def", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + ], + next_page_token="ghi", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + endpoint_policy.ListEndpointPoliciesResponse.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.NetworkServicesGrpcTransport, - transports.NetworkServicesGrpcAsyncIOTransport, - ], -) -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_endpoint_policies(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, endpoint_policy.EndpointPolicy) for i in results) + + pages = list(client.list_endpoint_policies(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + endpoint_policy.GetEndpointPolicyRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = NetworkServicesClient.get_transport_class(transport_name)( +def test_get_endpoint_policy_rest(request_type): + client = NetworkServicesClient( 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/endpointPolicies/sample3" + } + request = request_type(**request_init) -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.NetworkServicesGrpcTransport, + # 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 = endpoint_policy.EndpointPolicy( + name="name_value", + type_=endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY, + authorization_policy="authorization_policy_value", + description="description_value", + server_tls_policy="server_tls_policy_value", + client_tls_policy="client_tls_policy_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = endpoint_policy.EndpointPolicy.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_endpoint_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, endpoint_policy.EndpointPolicy) + assert response.name == "name_value" + assert ( + response.type_ + == endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY ) + assert response.authorization_policy == "authorization_policy_value" + assert response.description == "description_value" + assert response.server_tls_policy == "server_tls_policy_value" + assert response.client_tls_policy == "client_tls_policy_value" -def test_network_services_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.NetworkServicesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", +def test_get_endpoint_policy_rest_required_fields( + request_type=endpoint_policy.GetEndpointPolicyRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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 -def test_network_services_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.network_services_v1.services.network_services.transports.NetworkServicesTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.NetworkServicesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_endpoint_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Every method on the transport should just blindly - # raise NotImplementedError. + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_endpoint_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = endpoint_policy.EndpointPolicy() + # 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 = endpoint_policy.EndpointPolicy.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_endpoint_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_endpoint_policy_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_endpoint_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_endpoint_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_endpoint_policy" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_get_endpoint_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = endpoint_policy.GetEndpointPolicyRequest.pb( + endpoint_policy.GetEndpointPolicyRequest() + ) + 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 = endpoint_policy.EndpointPolicy.to_json( + endpoint_policy.EndpointPolicy() + ) + + request = endpoint_policy.GetEndpointPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = endpoint_policy.EndpointPolicy() + + client.get_endpoint_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_endpoint_policy_rest_bad_request( + transport: str = "rest", request_type=endpoint_policy.GetEndpointPolicyRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/endpointPolicies/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_endpoint_policy(request) + + +def test_get_endpoint_policy_rest_flattened(): + client = NetworkServicesClient( + 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 = endpoint_policy.EndpointPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/endpointPolicies/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 = endpoint_policy.EndpointPolicy.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_endpoint_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/endpointPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_get_endpoint_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_endpoint_policy( + endpoint_policy.GetEndpointPolicyRequest(), + name="name_value", + ) + + +def test_get_endpoint_policy_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_endpoint_policy.CreateEndpointPolicyRequest, + dict, + ], +) +def test_create_endpoint_policy_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["endpoint_policy"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "type_": 1, + "authorization_policy": "authorization_policy_value", + "endpoint_matcher": { + "metadata_label_matcher": { + "metadata_label_match_criteria": 1, + "metadata_labels": [ + { + "label_name": "label_name_value", + "label_value": "label_value_value", + } + ], + } + }, + "traffic_port_selector": {"ports": ["ports_value1", "ports_value2"]}, + "description": "description_value", + "server_tls_policy": "server_tls_policy_value", + "client_tls_policy": "client_tls_policy_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_endpoint_policy(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_endpoint_policy_rest_required_fields( + request_type=gcn_endpoint_policy.CreateEndpointPolicyRequest, +): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["endpoint_policy_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 "endpointPolicyId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_endpoint_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "endpointPolicyId" in jsonified_request + assert jsonified_request["endpointPolicyId"] == request_init["endpoint_policy_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["endpointPolicyId"] = "endpoint_policy_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_endpoint_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("endpoint_policy_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "endpointPolicyId" in jsonified_request + assert jsonified_request["endpointPolicyId"] == "endpoint_policy_id_value" + + client = NetworkServicesClient( + 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_endpoint_policy(request) + + expected_params = [ + ( + "endpointPolicyId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_endpoint_policy_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_endpoint_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("endpointPolicyId",)) + & set( + ( + "parent", + "endpointPolicyId", + "endpointPolicy", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_endpoint_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_endpoint_policy" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_create_endpoint_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_endpoint_policy.CreateEndpointPolicyRequest.pb( + gcn_endpoint_policy.CreateEndpointPolicyRequest() + ) + 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 = gcn_endpoint_policy.CreateEndpointPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_endpoint_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_endpoint_policy_rest_bad_request( + transport: str = "rest", + request_type=gcn_endpoint_policy.CreateEndpointPolicyRequest, +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["endpoint_policy"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "type_": 1, + "authorization_policy": "authorization_policy_value", + "endpoint_matcher": { + "metadata_label_matcher": { + "metadata_label_match_criteria": 1, + "metadata_labels": [ + { + "label_name": "label_name_value", + "label_value": "label_value_value", + } + ], + } + }, + "traffic_port_selector": {"ports": ["ports_value1", "ports_value2"]}, + "description": "description_value", + "server_tls_policy": "server_tls_policy_value", + "client_tls_policy": "client_tls_policy_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_endpoint_policy(request) + + +def test_create_endpoint_policy_rest_flattened(): + client = NetworkServicesClient( + 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", + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name="name_value"), + endpoint_policy_id="endpoint_policy_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_endpoint_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/endpointPolicies" + % client.transport._host, + args[1], + ) + + +def test_create_endpoint_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_endpoint_policy( + gcn_endpoint_policy.CreateEndpointPolicyRequest(), + parent="parent_value", + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name="name_value"), + endpoint_policy_id="endpoint_policy_id_value", + ) + + +def test_create_endpoint_policy_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_endpoint_policy.UpdateEndpointPolicyRequest, + dict, + ], +) +def test_update_endpoint_policy_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "endpoint_policy": { + "name": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + } + request_init["endpoint_policy"] = { + "name": "projects/sample1/locations/sample2/endpointPolicies/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "type_": 1, + "authorization_policy": "authorization_policy_value", + "endpoint_matcher": { + "metadata_label_matcher": { + "metadata_label_match_criteria": 1, + "metadata_labels": [ + { + "label_name": "label_name_value", + "label_value": "label_value_value", + } + ], + } + }, + "traffic_port_selector": {"ports": ["ports_value1", "ports_value2"]}, + "description": "description_value", + "server_tls_policy": "server_tls_policy_value", + "client_tls_policy": "client_tls_policy_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_endpoint_policy(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_endpoint_policy_rest_required_fields( + request_type=gcn_endpoint_policy.UpdateEndpointPolicyRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_endpoint_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_endpoint_policy._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 = NetworkServicesClient( + 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_endpoint_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_endpoint_policy_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_endpoint_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("endpointPolicy",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_endpoint_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_endpoint_policy" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_update_endpoint_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_endpoint_policy.UpdateEndpointPolicyRequest.pb( + gcn_endpoint_policy.UpdateEndpointPolicyRequest() + ) + 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 = gcn_endpoint_policy.UpdateEndpointPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_endpoint_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_endpoint_policy_rest_bad_request( + transport: str = "rest", + request_type=gcn_endpoint_policy.UpdateEndpointPolicyRequest, +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "endpoint_policy": { + "name": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + } + request_init["endpoint_policy"] = { + "name": "projects/sample1/locations/sample2/endpointPolicies/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "type_": 1, + "authorization_policy": "authorization_policy_value", + "endpoint_matcher": { + "metadata_label_matcher": { + "metadata_label_match_criteria": 1, + "metadata_labels": [ + { + "label_name": "label_name_value", + "label_value": "label_value_value", + } + ], + } + }, + "traffic_port_selector": {"ports": ["ports_value1", "ports_value2"]}, + "description": "description_value", + "server_tls_policy": "server_tls_policy_value", + "client_tls_policy": "client_tls_policy_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_endpoint_policy(request) + + +def test_update_endpoint_policy_rest_flattened(): + client = NetworkServicesClient( + 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 = { + "endpoint_policy": { + "name": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(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_endpoint_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{endpoint_policy.name=projects/*/locations/*/endpointPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_update_endpoint_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_endpoint_policy( + gcn_endpoint_policy.UpdateEndpointPolicyRequest(), + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_endpoint_policy_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + endpoint_policy.DeleteEndpointPolicyRequest, + dict, + ], +) +def test_delete_endpoint_policy_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/endpointPolicies/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_endpoint_policy(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_endpoint_policy_rest_required_fields( + request_type=endpoint_policy.DeleteEndpointPolicyRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_endpoint_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_endpoint_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = NetworkServicesClient( + 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_endpoint_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_endpoint_policy_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_endpoint_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_endpoint_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_endpoint_policy" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_delete_endpoint_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = endpoint_policy.DeleteEndpointPolicyRequest.pb( + endpoint_policy.DeleteEndpointPolicyRequest() + ) + 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 = endpoint_policy.DeleteEndpointPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_endpoint_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_endpoint_policy_rest_bad_request( + transport: str = "rest", request_type=endpoint_policy.DeleteEndpointPolicyRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/endpointPolicies/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_endpoint_policy(request) + + +def test_delete_endpoint_policy_rest_flattened(): + client = NetworkServicesClient( + 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/endpointPolicies/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_endpoint_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/endpointPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_endpoint_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_endpoint_policy( + endpoint_policy.DeleteEndpointPolicyRequest(), + name="name_value", + ) + + +def test_delete_endpoint_policy_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gateway.ListGatewaysRequest, + dict, + ], +) +def test_list_gateways_rest(request_type): + client = NetworkServicesClient( + 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 = gateway.ListGatewaysResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gateway.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" + + +def test_list_gateways_rest_required_fields(request_type=gateway.ListGatewaysRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_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( + ( + "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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gateway.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 = gateway.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.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_gateways._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_gateways_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_gateways" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_list_gateways" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gateway.ListGatewaysRequest.pb(gateway.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 = gateway.ListGatewaysResponse.to_json( + gateway.ListGatewaysResponse() + ) + + request = gateway.ListGatewaysRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gateway.ListGatewaysResponse() + + client.list_gateways( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_gateways_rest_bad_request( + transport: str = "rest", request_type=gateway.ListGatewaysRequest +): + client = NetworkServicesClient( + 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_gateways(request) + + +def test_list_gateways_rest_flattened(): + client = NetworkServicesClient( + 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 = gateway.ListGatewaysResponse() + + # 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 = gateway.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 = NetworkServicesClient( + 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_gateways( + gateway.ListGatewaysRequest(), + parent="parent_value", + ) + + +def test_list_gateways_rest_pager(transport: str = "rest"): + client = NetworkServicesClient( + 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 = ( + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + gateway.Gateway(), + gateway.Gateway(), + ], + next_page_token="abc", + ), + gateway.ListGatewaysResponse( + gateways=[], + next_page_token="def", + ), + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + ], + next_page_token="ghi", + ), + gateway.ListGatewaysResponse( + gateways=[ + gateway.Gateway(), + gateway.Gateway(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(gateway.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 + + 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, gateway.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( + "request_type", + [ + gateway.GetGatewayRequest, + dict, + ], +) +def test_get_gateway_rest(request_type): + client = NetworkServicesClient( + 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 = gateway.Gateway( + name="name_value", + self_link="self_link_value", + description="description_value", + type_=gateway.Gateway.Type.OPEN_MESH, + ports=[568], + scope="scope_value", + server_tls_policy="server_tls_policy_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gateway.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, gateway.Gateway) + assert response.name == "name_value" + assert response.self_link == "self_link_value" + assert response.description == "description_value" + assert response.type_ == gateway.Gateway.Type.OPEN_MESH + assert response.ports == [568] + assert response.scope == "scope_value" + assert response.server_tls_policy == "server_tls_policy_value" + + +def test_get_gateway_rest_required_fields(request_type=gateway.GetGatewayRequest): + transport_class = transports.NetworkServicesRestTransport + + 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" + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gateway.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 = gateway.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.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_gateway._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_gateway_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_gateway" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_get_gateway" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gateway.GetGatewayRequest.pb(gateway.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 = gateway.Gateway.to_json(gateway.Gateway()) + + request = gateway.GetGatewayRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gateway.Gateway() + + client.get_gateway( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_gateway_rest_bad_request( + transport: str = "rest", request_type=gateway.GetGatewayRequest +): + client = NetworkServicesClient( + 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 = NetworkServicesClient( + 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 = gateway.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 = gateway.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 = NetworkServicesClient( + 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( + gateway.GetGatewayRequest(), + name="name_value", + ) + + +def test_get_gateway_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_gateway.CreateGatewayRequest, + dict, + ], +) +def test_create_gateway_rest(request_type): + client = NetworkServicesClient( + 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", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "type_": 1, + "ports": [569, 570], + "scope": "scope_value", + "server_tls_policy": "server_tls_policy_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=gcn_gateway.CreateGatewayRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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 = NetworkServicesClient( + 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.NetworkServicesRestTransport( + 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.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_gateway" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_create_gateway" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_gateway.CreateGatewayRequest.pb( + gcn_gateway.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 = gcn_gateway.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=gcn_gateway.CreateGatewayRequest +): + client = NetworkServicesClient( + 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", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "type_": 1, + "ports": [569, 570], + "scope": "scope_value", + "server_tls_policy": "server_tls_policy_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 = NetworkServicesClient( + 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=gcn_gateway.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 = NetworkServicesClient( + 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( + gcn_gateway.CreateGatewayRequest(), + parent="parent_value", + gateway=gcn_gateway.Gateway(name="name_value"), + gateway_id="gateway_id_value", + ) + + +def test_create_gateway_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_gateway.UpdateGatewayRequest, + dict, + ], +) +def test_update_gateway_rest(request_type): + client = NetworkServicesClient( + 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", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "type_": 1, + "ports": [569, 570], + "scope": "scope_value", + "server_tls_policy": "server_tls_policy_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=gcn_gateway.UpdateGatewayRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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 = NetworkServicesClient( + 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.NetworkServicesRestTransport( + 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.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_gateway" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_update_gateway" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_gateway.UpdateGatewayRequest.pb( + gcn_gateway.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 = gcn_gateway.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=gcn_gateway.UpdateGatewayRequest +): + client = NetworkServicesClient( + 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", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "type_": 1, + "ports": [569, 570], + "scope": "scope_value", + "server_tls_policy": "server_tls_policy_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 = NetworkServicesClient( + 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=gcn_gateway.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 = NetworkServicesClient( + 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( + gcn_gateway.UpdateGatewayRequest(), + gateway=gcn_gateway.Gateway(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_gateway_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gateway.DeleteGatewayRequest, + dict, + ], +) +def test_delete_gateway_rest(request_type): + client = NetworkServicesClient( + 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=gateway.DeleteGatewayRequest): + transport_class = transports.NetworkServicesRestTransport + + 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 = NetworkServicesClient( + 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.NetworkServicesRestTransport( + 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.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_gateway" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_delete_gateway" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gateway.DeleteGatewayRequest.pb(gateway.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 = gateway.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=gateway.DeleteGatewayRequest +): + client = NetworkServicesClient( + 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 = NetworkServicesClient( + 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 = NetworkServicesClient( + 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( + gateway.DeleteGatewayRequest(), + name="name_value", + ) + + +def test_delete_gateway_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + grpc_route.ListGrpcRoutesRequest, + dict, + ], +) +def test_list_grpc_routes_rest(request_type): + client = NetworkServicesClient( + 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 = grpc_route.ListGrpcRoutesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = grpc_route.ListGrpcRoutesResponse.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_grpc_routes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGrpcRoutesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_grpc_routes_rest_required_fields( + request_type=grpc_route.ListGrpcRoutesRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_grpc_routes._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_grpc_routes._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grpc_route.ListGrpcRoutesResponse() + # 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 = grpc_route.ListGrpcRoutesResponse.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_grpc_routes(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_grpc_routes_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_grpc_routes._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_grpc_routes_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_grpc_routes" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_list_grpc_routes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grpc_route.ListGrpcRoutesRequest.pb( + grpc_route.ListGrpcRoutesRequest() + ) + 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 = grpc_route.ListGrpcRoutesResponse.to_json( + grpc_route.ListGrpcRoutesResponse() + ) + + request = grpc_route.ListGrpcRoutesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grpc_route.ListGrpcRoutesResponse() + + client.list_grpc_routes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_grpc_routes_rest_bad_request( + transport: str = "rest", request_type=grpc_route.ListGrpcRoutesRequest +): + client = NetworkServicesClient( + 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_grpc_routes(request) + + +def test_list_grpc_routes_rest_flattened(): + client = NetworkServicesClient( + 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 = grpc_route.ListGrpcRoutesResponse() + + # 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 = grpc_route.ListGrpcRoutesResponse.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_grpc_routes(**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/*}/grpcRoutes" % client.transport._host, + args[1], + ) + + +def test_list_grpc_routes_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_grpc_routes( + grpc_route.ListGrpcRoutesRequest(), + parent="parent_value", + ) + + +def test_list_grpc_routes_rest_pager(transport: str = "rest"): + client = NetworkServicesClient( + 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 = ( + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + ], + next_page_token="abc", + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[], + next_page_token="def", + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + ], + next_page_token="ghi", + ), + grpc_route.ListGrpcRoutesResponse( + grpc_routes=[ + grpc_route.GrpcRoute(), + grpc_route.GrpcRoute(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(grpc_route.ListGrpcRoutesResponse.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_grpc_routes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, grpc_route.GrpcRoute) for i in results) + + pages = list(client.list_grpc_routes(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", + [ + grpc_route.GetGrpcRouteRequest, + dict, + ], +) +def test_get_grpc_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/grpcRoutes/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 = grpc_route.GrpcRoute( + name="name_value", + self_link="self_link_value", + description="description_value", + hostnames=["hostnames_value"], + meshes=["meshes_value"], + gateways=["gateways_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = grpc_route.GrpcRoute.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_grpc_route(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grpc_route.GrpcRoute) + assert response.name == "name_value" + assert response.self_link == "self_link_value" + assert response.description == "description_value" + assert response.hostnames == ["hostnames_value"] + assert response.meshes == ["meshes_value"] + assert response.gateways == ["gateways_value"] + + +def test_get_grpc_route_rest_required_fields( + request_type=grpc_route.GetGrpcRouteRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_grpc_route._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_grpc_route._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grpc_route.GrpcRoute() + # 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 = grpc_route.GrpcRoute.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_grpc_route(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_grpc_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_grpc_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_grpc_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_grpc_route" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_get_grpc_route" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grpc_route.GetGrpcRouteRequest.pb(grpc_route.GetGrpcRouteRequest()) + 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 = grpc_route.GrpcRoute.to_json(grpc_route.GrpcRoute()) + + request = grpc_route.GetGrpcRouteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grpc_route.GrpcRoute() + + client.get_grpc_route( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_grpc_route_rest_bad_request( + transport: str = "rest", request_type=grpc_route.GetGrpcRouteRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/grpcRoutes/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_grpc_route(request) + + +def test_get_grpc_route_rest_flattened(): + client = NetworkServicesClient( + 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 = grpc_route.GrpcRoute() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/grpcRoutes/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 = grpc_route.GrpcRoute.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_grpc_route(**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/*/grpcRoutes/*}" % client.transport._host, + args[1], + ) + + +def test_get_grpc_route_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_grpc_route( + grpc_route.GetGrpcRouteRequest(), + name="name_value", + ) + + +def test_get_grpc_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_grpc_route.CreateGrpcRouteRequest, + dict, + ], +) +def test_create_grpc_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["grpc_route"] = { + "name": "name_value", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "hostnames": ["hostnames_value1", "hostnames_value2"], + "meshes": ["meshes_value1", "meshes_value2"], + "gateways": ["gateways_value1", "gateways_value2"], + "rules": [ + { + "matches": [ + { + "method": { + "type_": 1, + "grpc_service": "grpc_service_value", + "grpc_method": "grpc_method_value", + "case_sensitive": True, + }, + "headers": [ + {"type_": 1, "key": "key_value", "value": "value_value"} + ], + } + ], + "action": { + "destinations": [ + {"service_name": "service_name_value", "weight": 648} + ], + "fault_injection_policy": { + "delay": { + "fixed_delay": {"seconds": 751, "nanos": 543}, + "percentage": 1054, + }, + "abort": {"http_status": 1219, "percentage": 1054}, + }, + "timeout": {}, + "retry_policy": { + "retry_conditions": [ + "retry_conditions_value1", + "retry_conditions_value2", + ], + "num_retries": 1197, + }, + }, + } + ], + } + 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_grpc_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_grpc_route_rest_required_fields( + request_type=gcn_grpc_route.CreateGrpcRouteRequest, +): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["grpc_route_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 "grpcRouteId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_grpc_route._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "grpcRouteId" in jsonified_request + assert jsonified_request["grpcRouteId"] == request_init["grpc_route_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["grpcRouteId"] = "grpc_route_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_grpc_route._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("grpc_route_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 "grpcRouteId" in jsonified_request + assert jsonified_request["grpcRouteId"] == "grpc_route_id_value" + + client = NetworkServicesClient( + 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_grpc_route(request) + + expected_params = [ + ( + "grpcRouteId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_grpc_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_grpc_route._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("grpcRouteId",)) + & set( + ( + "parent", + "grpcRouteId", + "grpcRoute", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_grpc_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_grpc_route" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_create_grpc_route" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_grpc_route.CreateGrpcRouteRequest.pb( + gcn_grpc_route.CreateGrpcRouteRequest() + ) + 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 = gcn_grpc_route.CreateGrpcRouteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_grpc_route( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_grpc_route_rest_bad_request( + transport: str = "rest", request_type=gcn_grpc_route.CreateGrpcRouteRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["grpc_route"] = { + "name": "name_value", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "hostnames": ["hostnames_value1", "hostnames_value2"], + "meshes": ["meshes_value1", "meshes_value2"], + "gateways": ["gateways_value1", "gateways_value2"], + "rules": [ + { + "matches": [ + { + "method": { + "type_": 1, + "grpc_service": "grpc_service_value", + "grpc_method": "grpc_method_value", + "case_sensitive": True, + }, + "headers": [ + {"type_": 1, "key": "key_value", "value": "value_value"} + ], + } + ], + "action": { + "destinations": [ + {"service_name": "service_name_value", "weight": 648} + ], + "fault_injection_policy": { + "delay": { + "fixed_delay": {"seconds": 751, "nanos": 543}, + "percentage": 1054, + }, + "abort": {"http_status": 1219, "percentage": 1054}, + }, + "timeout": {}, + "retry_policy": { + "retry_conditions": [ + "retry_conditions_value1", + "retry_conditions_value2", + ], + "num_retries": 1197, + }, + }, + } + ], + } + 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_grpc_route(request) + + +def test_create_grpc_route_rest_flattened(): + client = NetworkServicesClient( + 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", + grpc_route=gcn_grpc_route.GrpcRoute(name="name_value"), + grpc_route_id="grpc_route_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_grpc_route(**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/*}/grpcRoutes" % client.transport._host, + args[1], + ) + + +def test_create_grpc_route_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_grpc_route( + gcn_grpc_route.CreateGrpcRouteRequest(), + parent="parent_value", + grpc_route=gcn_grpc_route.GrpcRoute(name="name_value"), + grpc_route_id="grpc_route_id_value", + ) + + +def test_create_grpc_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_grpc_route.UpdateGrpcRouteRequest, + dict, + ], +) +def test_update_grpc_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "grpc_route": {"name": "projects/sample1/locations/sample2/grpcRoutes/sample3"} + } + request_init["grpc_route"] = { + "name": "projects/sample1/locations/sample2/grpcRoutes/sample3", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "hostnames": ["hostnames_value1", "hostnames_value2"], + "meshes": ["meshes_value1", "meshes_value2"], + "gateways": ["gateways_value1", "gateways_value2"], + "rules": [ + { + "matches": [ + { + "method": { + "type_": 1, + "grpc_service": "grpc_service_value", + "grpc_method": "grpc_method_value", + "case_sensitive": True, + }, + "headers": [ + {"type_": 1, "key": "key_value", "value": "value_value"} + ], + } + ], + "action": { + "destinations": [ + {"service_name": "service_name_value", "weight": 648} + ], + "fault_injection_policy": { + "delay": { + "fixed_delay": {"seconds": 751, "nanos": 543}, + "percentage": 1054, + }, + "abort": {"http_status": 1219, "percentage": 1054}, + }, + "timeout": {}, + "retry_policy": { + "retry_conditions": [ + "retry_conditions_value1", + "retry_conditions_value2", + ], + "num_retries": 1197, + }, + }, + } + ], + } + 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_grpc_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_grpc_route_rest_required_fields( + request_type=gcn_grpc_route.UpdateGrpcRouteRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_grpc_route._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_grpc_route._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 = NetworkServicesClient( + 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_grpc_route(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_grpc_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_grpc_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("grpcRoute",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_grpc_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_grpc_route" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_update_grpc_route" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_grpc_route.UpdateGrpcRouteRequest.pb( + gcn_grpc_route.UpdateGrpcRouteRequest() + ) + 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 = gcn_grpc_route.UpdateGrpcRouteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_grpc_route( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_grpc_route_rest_bad_request( + transport: str = "rest", request_type=gcn_grpc_route.UpdateGrpcRouteRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "grpc_route": {"name": "projects/sample1/locations/sample2/grpcRoutes/sample3"} + } + request_init["grpc_route"] = { + "name": "projects/sample1/locations/sample2/grpcRoutes/sample3", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "hostnames": ["hostnames_value1", "hostnames_value2"], + "meshes": ["meshes_value1", "meshes_value2"], + "gateways": ["gateways_value1", "gateways_value2"], + "rules": [ + { + "matches": [ + { + "method": { + "type_": 1, + "grpc_service": "grpc_service_value", + "grpc_method": "grpc_method_value", + "case_sensitive": True, + }, + "headers": [ + {"type_": 1, "key": "key_value", "value": "value_value"} + ], + } + ], + "action": { + "destinations": [ + {"service_name": "service_name_value", "weight": 648} + ], + "fault_injection_policy": { + "delay": { + "fixed_delay": {"seconds": 751, "nanos": 543}, + "percentage": 1054, + }, + "abort": {"http_status": 1219, "percentage": 1054}, + }, + "timeout": {}, + "retry_policy": { + "retry_conditions": [ + "retry_conditions_value1", + "retry_conditions_value2", + ], + "num_retries": 1197, + }, + }, + } + ], + } + 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_grpc_route(request) + + +def test_update_grpc_route_rest_flattened(): + client = NetworkServicesClient( + 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 = { + "grpc_route": { + "name": "projects/sample1/locations/sample2/grpcRoutes/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + grpc_route=gcn_grpc_route.GrpcRoute(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_grpc_route(**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/{grpc_route.name=projects/*/locations/*/grpcRoutes/*}" + % client.transport._host, + args[1], + ) + + +def test_update_grpc_route_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_grpc_route( + gcn_grpc_route.UpdateGrpcRouteRequest(), + grpc_route=gcn_grpc_route.GrpcRoute(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_grpc_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + grpc_route.DeleteGrpcRouteRequest, + dict, + ], +) +def test_delete_grpc_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/grpcRoutes/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_grpc_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_grpc_route_rest_required_fields( + request_type=grpc_route.DeleteGrpcRouteRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_grpc_route._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_grpc_route._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 = NetworkServicesClient( + 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_grpc_route(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_grpc_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_grpc_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_grpc_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_grpc_route" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_delete_grpc_route" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grpc_route.DeleteGrpcRouteRequest.pb( + grpc_route.DeleteGrpcRouteRequest() + ) + 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 = grpc_route.DeleteGrpcRouteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_grpc_route( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_grpc_route_rest_bad_request( + transport: str = "rest", request_type=grpc_route.DeleteGrpcRouteRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/grpcRoutes/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_grpc_route(request) + + +def test_delete_grpc_route_rest_flattened(): + client = NetworkServicesClient( + 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/grpcRoutes/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_grpc_route(**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/*/grpcRoutes/*}" % client.transport._host, + args[1], + ) + + +def test_delete_grpc_route_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_grpc_route( + grpc_route.DeleteGrpcRouteRequest(), + name="name_value", + ) + + +def test_delete_grpc_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + http_route.ListHttpRoutesRequest, + dict, + ], +) +def test_list_http_routes_rest(request_type): + client = NetworkServicesClient( + 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 = http_route.ListHttpRoutesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = http_route.ListHttpRoutesResponse.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_http_routes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListHttpRoutesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_http_routes_rest_required_fields( + request_type=http_route.ListHttpRoutesRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_http_routes._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_http_routes._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = http_route.ListHttpRoutesResponse() + # 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 = http_route.ListHttpRoutesResponse.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_http_routes(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_http_routes_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_http_routes._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_http_routes_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_http_routes" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_list_http_routes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = http_route.ListHttpRoutesRequest.pb( + http_route.ListHttpRoutesRequest() + ) + 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 = http_route.ListHttpRoutesResponse.to_json( + http_route.ListHttpRoutesResponse() + ) + + request = http_route.ListHttpRoutesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = http_route.ListHttpRoutesResponse() + + client.list_http_routes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_http_routes_rest_bad_request( + transport: str = "rest", request_type=http_route.ListHttpRoutesRequest +): + client = NetworkServicesClient( + 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_http_routes(request) + + +def test_list_http_routes_rest_flattened(): + client = NetworkServicesClient( + 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 = http_route.ListHttpRoutesResponse() + + # 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 = http_route.ListHttpRoutesResponse.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_http_routes(**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/*}/httpRoutes" % client.transport._host, + args[1], + ) + + +def test_list_http_routes_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_http_routes( + http_route.ListHttpRoutesRequest(), + parent="parent_value", + ) + + +def test_list_http_routes_rest_pager(transport: str = "rest"): + client = NetworkServicesClient( + 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 = ( + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + http_route.HttpRoute(), + http_route.HttpRoute(), + ], + next_page_token="abc", + ), + http_route.ListHttpRoutesResponse( + http_routes=[], + next_page_token="def", + ), + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + ], + next_page_token="ghi", + ), + http_route.ListHttpRoutesResponse( + http_routes=[ + http_route.HttpRoute(), + http_route.HttpRoute(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(http_route.ListHttpRoutesResponse.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_http_routes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, http_route.HttpRoute) for i in results) + + pages = list(client.list_http_routes(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", + [ + http_route.GetHttpRouteRequest, + dict, + ], +) +def test_get_http_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/httpRoutes/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 = http_route.HttpRoute( + name="name_value", + self_link="self_link_value", + description="description_value", + hostnames=["hostnames_value"], + meshes=["meshes_value"], + gateways=["gateways_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = http_route.HttpRoute.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_http_route(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, http_route.HttpRoute) + assert response.name == "name_value" + assert response.self_link == "self_link_value" + assert response.description == "description_value" + assert response.hostnames == ["hostnames_value"] + assert response.meshes == ["meshes_value"] + assert response.gateways == ["gateways_value"] + + +def test_get_http_route_rest_required_fields( + request_type=http_route.GetHttpRouteRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_http_route._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_http_route._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = http_route.HttpRoute() + # 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 = http_route.HttpRoute.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_http_route(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_http_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_http_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_http_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_http_route" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_get_http_route" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = http_route.GetHttpRouteRequest.pb(http_route.GetHttpRouteRequest()) + 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 = http_route.HttpRoute.to_json(http_route.HttpRoute()) + + request = http_route.GetHttpRouteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = http_route.HttpRoute() + + client.get_http_route( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_http_route_rest_bad_request( + transport: str = "rest", request_type=http_route.GetHttpRouteRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/httpRoutes/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_http_route(request) + + +def test_get_http_route_rest_flattened(): + client = NetworkServicesClient( + 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 = http_route.HttpRoute() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/httpRoutes/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 = http_route.HttpRoute.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_http_route(**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/*/httpRoutes/*}" % client.transport._host, + args[1], + ) + + +def test_get_http_route_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_http_route( + http_route.GetHttpRouteRequest(), + name="name_value", + ) + + +def test_get_http_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_http_route.CreateHttpRouteRequest, + dict, + ], +) +def test_create_http_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["http_route"] = { + "name": "name_value", + "self_link": "self_link_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "hostnames": ["hostnames_value1", "hostnames_value2"], + "meshes": ["meshes_value1", "meshes_value2"], + "gateways": ["gateways_value1", "gateways_value2"], + "labels": {}, + "rules": [ + { + "matches": [ + { + "full_path_match": "full_path_match_value", + "prefix_match": "prefix_match_value", + "regex_match": "regex_match_value", + "ignore_case": True, + "headers": [ + { + "exact_match": "exact_match_value", + "regex_match": "regex_match_value", + "prefix_match": "prefix_match_value", + "present_match": True, + "suffix_match": "suffix_match_value", + "range_match": {"start": 558, "end": 311}, + "header": "header_value", + "invert_match": True, + } + ], + "query_parameters": [ + { + "exact_match": "exact_match_value", + "regex_match": "regex_match_value", + "present_match": True, + "query_parameter": "query_parameter_value", + } + ], + } + ], + "action": { + "destinations": [ + {"service_name": "service_name_value", "weight": 648} + ], + "redirect": { + "host_redirect": "host_redirect_value", + "path_redirect": "path_redirect_value", + "prefix_rewrite": "prefix_rewrite_value", + "response_code": 1, + "https_redirect": True, + "strip_query": True, + "port_redirect": 1398, + }, + "fault_injection_policy": { + "delay": { + "fixed_delay": {"seconds": 751, "nanos": 543}, + "percentage": 1054, + }, + "abort": {"http_status": 1219, "percentage": 1054}, + }, + "request_header_modifier": { + "set": {}, + "add": {}, + "remove": ["remove_value1", "remove_value2"], + }, + "response_header_modifier": {}, + "url_rewrite": { + "path_prefix_rewrite": "path_prefix_rewrite_value", + "host_rewrite": "host_rewrite_value", + }, + "timeout": {}, + "retry_policy": { + "retry_conditions": [ + "retry_conditions_value1", + "retry_conditions_value2", + ], + "num_retries": 1197, + "per_try_timeout": {}, + }, + "request_mirror_policy": {"destination": {}}, + "cors_policy": { + "allow_origins": [ + "allow_origins_value1", + "allow_origins_value2", + ], + "allow_origin_regexes": [ + "allow_origin_regexes_value1", + "allow_origin_regexes_value2", + ], + "allow_methods": [ + "allow_methods_value1", + "allow_methods_value2", + ], + "allow_headers": [ + "allow_headers_value1", + "allow_headers_value2", + ], + "expose_headers": [ + "expose_headers_value1", + "expose_headers_value2", + ], + "max_age": "max_age_value", + "allow_credentials": True, + "disabled": True, + }, + }, + } + ], + } + 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_http_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_http_route_rest_required_fields( + request_type=gcn_http_route.CreateHttpRouteRequest, +): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["http_route_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 "httpRouteId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_http_route._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "httpRouteId" in jsonified_request + assert jsonified_request["httpRouteId"] == request_init["http_route_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["httpRouteId"] = "http_route_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_http_route._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("http_route_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 "httpRouteId" in jsonified_request + assert jsonified_request["httpRouteId"] == "http_route_id_value" + + client = NetworkServicesClient( + 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_http_route(request) + + expected_params = [ + ( + "httpRouteId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_http_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_http_route._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("httpRouteId",)) + & set( + ( + "parent", + "httpRouteId", + "httpRoute", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_http_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_http_route" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_create_http_route" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_http_route.CreateHttpRouteRequest.pb( + gcn_http_route.CreateHttpRouteRequest() + ) + 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 = gcn_http_route.CreateHttpRouteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_http_route( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_http_route_rest_bad_request( + transport: str = "rest", request_type=gcn_http_route.CreateHttpRouteRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["http_route"] = { + "name": "name_value", + "self_link": "self_link_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "hostnames": ["hostnames_value1", "hostnames_value2"], + "meshes": ["meshes_value1", "meshes_value2"], + "gateways": ["gateways_value1", "gateways_value2"], + "labels": {}, + "rules": [ + { + "matches": [ + { + "full_path_match": "full_path_match_value", + "prefix_match": "prefix_match_value", + "regex_match": "regex_match_value", + "ignore_case": True, + "headers": [ + { + "exact_match": "exact_match_value", + "regex_match": "regex_match_value", + "prefix_match": "prefix_match_value", + "present_match": True, + "suffix_match": "suffix_match_value", + "range_match": {"start": 558, "end": 311}, + "header": "header_value", + "invert_match": True, + } + ], + "query_parameters": [ + { + "exact_match": "exact_match_value", + "regex_match": "regex_match_value", + "present_match": True, + "query_parameter": "query_parameter_value", + } + ], + } + ], + "action": { + "destinations": [ + {"service_name": "service_name_value", "weight": 648} + ], + "redirect": { + "host_redirect": "host_redirect_value", + "path_redirect": "path_redirect_value", + "prefix_rewrite": "prefix_rewrite_value", + "response_code": 1, + "https_redirect": True, + "strip_query": True, + "port_redirect": 1398, + }, + "fault_injection_policy": { + "delay": { + "fixed_delay": {"seconds": 751, "nanos": 543}, + "percentage": 1054, + }, + "abort": {"http_status": 1219, "percentage": 1054}, + }, + "request_header_modifier": { + "set": {}, + "add": {}, + "remove": ["remove_value1", "remove_value2"], + }, + "response_header_modifier": {}, + "url_rewrite": { + "path_prefix_rewrite": "path_prefix_rewrite_value", + "host_rewrite": "host_rewrite_value", + }, + "timeout": {}, + "retry_policy": { + "retry_conditions": [ + "retry_conditions_value1", + "retry_conditions_value2", + ], + "num_retries": 1197, + "per_try_timeout": {}, + }, + "request_mirror_policy": {"destination": {}}, + "cors_policy": { + "allow_origins": [ + "allow_origins_value1", + "allow_origins_value2", + ], + "allow_origin_regexes": [ + "allow_origin_regexes_value1", + "allow_origin_regexes_value2", + ], + "allow_methods": [ + "allow_methods_value1", + "allow_methods_value2", + ], + "allow_headers": [ + "allow_headers_value1", + "allow_headers_value2", + ], + "expose_headers": [ + "expose_headers_value1", + "expose_headers_value2", + ], + "max_age": "max_age_value", + "allow_credentials": True, + "disabled": True, + }, + }, + } + ], + } + 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_http_route(request) + + +def test_create_http_route_rest_flattened(): + client = NetworkServicesClient( + 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", + http_route=gcn_http_route.HttpRoute(name="name_value"), + http_route_id="http_route_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_http_route(**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/*}/httpRoutes" % client.transport._host, + args[1], + ) + + +def test_create_http_route_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_http_route( + gcn_http_route.CreateHttpRouteRequest(), + parent="parent_value", + http_route=gcn_http_route.HttpRoute(name="name_value"), + http_route_id="http_route_id_value", + ) + + +def test_create_http_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_http_route.UpdateHttpRouteRequest, + dict, + ], +) +def test_update_http_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "http_route": {"name": "projects/sample1/locations/sample2/httpRoutes/sample3"} + } + request_init["http_route"] = { + "name": "projects/sample1/locations/sample2/httpRoutes/sample3", + "self_link": "self_link_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "hostnames": ["hostnames_value1", "hostnames_value2"], + "meshes": ["meshes_value1", "meshes_value2"], + "gateways": ["gateways_value1", "gateways_value2"], + "labels": {}, + "rules": [ + { + "matches": [ + { + "full_path_match": "full_path_match_value", + "prefix_match": "prefix_match_value", + "regex_match": "regex_match_value", + "ignore_case": True, + "headers": [ + { + "exact_match": "exact_match_value", + "regex_match": "regex_match_value", + "prefix_match": "prefix_match_value", + "present_match": True, + "suffix_match": "suffix_match_value", + "range_match": {"start": 558, "end": 311}, + "header": "header_value", + "invert_match": True, + } + ], + "query_parameters": [ + { + "exact_match": "exact_match_value", + "regex_match": "regex_match_value", + "present_match": True, + "query_parameter": "query_parameter_value", + } + ], + } + ], + "action": { + "destinations": [ + {"service_name": "service_name_value", "weight": 648} + ], + "redirect": { + "host_redirect": "host_redirect_value", + "path_redirect": "path_redirect_value", + "prefix_rewrite": "prefix_rewrite_value", + "response_code": 1, + "https_redirect": True, + "strip_query": True, + "port_redirect": 1398, + }, + "fault_injection_policy": { + "delay": { + "fixed_delay": {"seconds": 751, "nanos": 543}, + "percentage": 1054, + }, + "abort": {"http_status": 1219, "percentage": 1054}, + }, + "request_header_modifier": { + "set": {}, + "add": {}, + "remove": ["remove_value1", "remove_value2"], + }, + "response_header_modifier": {}, + "url_rewrite": { + "path_prefix_rewrite": "path_prefix_rewrite_value", + "host_rewrite": "host_rewrite_value", + }, + "timeout": {}, + "retry_policy": { + "retry_conditions": [ + "retry_conditions_value1", + "retry_conditions_value2", + ], + "num_retries": 1197, + "per_try_timeout": {}, + }, + "request_mirror_policy": {"destination": {}}, + "cors_policy": { + "allow_origins": [ + "allow_origins_value1", + "allow_origins_value2", + ], + "allow_origin_regexes": [ + "allow_origin_regexes_value1", + "allow_origin_regexes_value2", + ], + "allow_methods": [ + "allow_methods_value1", + "allow_methods_value2", + ], + "allow_headers": [ + "allow_headers_value1", + "allow_headers_value2", + ], + "expose_headers": [ + "expose_headers_value1", + "expose_headers_value2", + ], + "max_age": "max_age_value", + "allow_credentials": True, + "disabled": True, + }, + }, + } + ], + } + 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_http_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_http_route_rest_required_fields( + request_type=gcn_http_route.UpdateHttpRouteRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_http_route._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_http_route._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 = NetworkServicesClient( + 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_http_route(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_http_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_http_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("httpRoute",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_http_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_http_route" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_update_http_route" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_http_route.UpdateHttpRouteRequest.pb( + gcn_http_route.UpdateHttpRouteRequest() + ) + 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 = gcn_http_route.UpdateHttpRouteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_http_route( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_http_route_rest_bad_request( + transport: str = "rest", request_type=gcn_http_route.UpdateHttpRouteRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "http_route": {"name": "projects/sample1/locations/sample2/httpRoutes/sample3"} + } + request_init["http_route"] = { + "name": "projects/sample1/locations/sample2/httpRoutes/sample3", + "self_link": "self_link_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "hostnames": ["hostnames_value1", "hostnames_value2"], + "meshes": ["meshes_value1", "meshes_value2"], + "gateways": ["gateways_value1", "gateways_value2"], + "labels": {}, + "rules": [ + { + "matches": [ + { + "full_path_match": "full_path_match_value", + "prefix_match": "prefix_match_value", + "regex_match": "regex_match_value", + "ignore_case": True, + "headers": [ + { + "exact_match": "exact_match_value", + "regex_match": "regex_match_value", + "prefix_match": "prefix_match_value", + "present_match": True, + "suffix_match": "suffix_match_value", + "range_match": {"start": 558, "end": 311}, + "header": "header_value", + "invert_match": True, + } + ], + "query_parameters": [ + { + "exact_match": "exact_match_value", + "regex_match": "regex_match_value", + "present_match": True, + "query_parameter": "query_parameter_value", + } + ], + } + ], + "action": { + "destinations": [ + {"service_name": "service_name_value", "weight": 648} + ], + "redirect": { + "host_redirect": "host_redirect_value", + "path_redirect": "path_redirect_value", + "prefix_rewrite": "prefix_rewrite_value", + "response_code": 1, + "https_redirect": True, + "strip_query": True, + "port_redirect": 1398, + }, + "fault_injection_policy": { + "delay": { + "fixed_delay": {"seconds": 751, "nanos": 543}, + "percentage": 1054, + }, + "abort": {"http_status": 1219, "percentage": 1054}, + }, + "request_header_modifier": { + "set": {}, + "add": {}, + "remove": ["remove_value1", "remove_value2"], + }, + "response_header_modifier": {}, + "url_rewrite": { + "path_prefix_rewrite": "path_prefix_rewrite_value", + "host_rewrite": "host_rewrite_value", + }, + "timeout": {}, + "retry_policy": { + "retry_conditions": [ + "retry_conditions_value1", + "retry_conditions_value2", + ], + "num_retries": 1197, + "per_try_timeout": {}, + }, + "request_mirror_policy": {"destination": {}}, + "cors_policy": { + "allow_origins": [ + "allow_origins_value1", + "allow_origins_value2", + ], + "allow_origin_regexes": [ + "allow_origin_regexes_value1", + "allow_origin_regexes_value2", + ], + "allow_methods": [ + "allow_methods_value1", + "allow_methods_value2", + ], + "allow_headers": [ + "allow_headers_value1", + "allow_headers_value2", + ], + "expose_headers": [ + "expose_headers_value1", + "expose_headers_value2", + ], + "max_age": "max_age_value", + "allow_credentials": True, + "disabled": True, + }, + }, + } + ], + } + 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_http_route(request) + + +def test_update_http_route_rest_flattened(): + client = NetworkServicesClient( + 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 = { + "http_route": { + "name": "projects/sample1/locations/sample2/httpRoutes/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + http_route=gcn_http_route.HttpRoute(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_http_route(**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/{http_route.name=projects/*/locations/*/httpRoutes/*}" + % client.transport._host, + args[1], + ) + + +def test_update_http_route_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_http_route( + gcn_http_route.UpdateHttpRouteRequest(), + http_route=gcn_http_route.HttpRoute(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_http_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + http_route.DeleteHttpRouteRequest, + dict, + ], +) +def test_delete_http_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/httpRoutes/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_http_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_http_route_rest_required_fields( + request_type=http_route.DeleteHttpRouteRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_http_route._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_http_route._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 = NetworkServicesClient( + 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_http_route(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_http_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_http_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_http_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_http_route" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_delete_http_route" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = http_route.DeleteHttpRouteRequest.pb( + http_route.DeleteHttpRouteRequest() + ) + 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 = http_route.DeleteHttpRouteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_http_route( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_http_route_rest_bad_request( + transport: str = "rest", request_type=http_route.DeleteHttpRouteRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/httpRoutes/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_http_route(request) + + +def test_delete_http_route_rest_flattened(): + client = NetworkServicesClient( + 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/httpRoutes/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_http_route(**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/*/httpRoutes/*}" % client.transport._host, + args[1], + ) + + +def test_delete_http_route_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_http_route( + http_route.DeleteHttpRouteRequest(), + name="name_value", + ) + + +def test_delete_http_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + tcp_route.ListTcpRoutesRequest, + dict, + ], +) +def test_list_tcp_routes_rest(request_type): + client = NetworkServicesClient( + 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 = tcp_route.ListTcpRoutesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = tcp_route.ListTcpRoutesResponse.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_tcp_routes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTcpRoutesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_tcp_routes_rest_required_fields( + request_type=tcp_route.ListTcpRoutesRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_tcp_routes._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_tcp_routes._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tcp_route.ListTcpRoutesResponse() + # 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 = tcp_route.ListTcpRoutesResponse.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_tcp_routes(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_tcp_routes_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_tcp_routes._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tcp_routes_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_tcp_routes" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_list_tcp_routes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tcp_route.ListTcpRoutesRequest.pb(tcp_route.ListTcpRoutesRequest()) + 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 = tcp_route.ListTcpRoutesResponse.to_json( + tcp_route.ListTcpRoutesResponse() + ) + + request = tcp_route.ListTcpRoutesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tcp_route.ListTcpRoutesResponse() + + client.list_tcp_routes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_tcp_routes_rest_bad_request( + transport: str = "rest", request_type=tcp_route.ListTcpRoutesRequest +): + client = NetworkServicesClient( + 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_tcp_routes(request) + + +def test_list_tcp_routes_rest_flattened(): + client = NetworkServicesClient( + 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 = tcp_route.ListTcpRoutesResponse() + + # 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 = tcp_route.ListTcpRoutesResponse.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_tcp_routes(**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/*}/tcpRoutes" % client.transport._host, + args[1], + ) + + +def test_list_tcp_routes_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_tcp_routes( + tcp_route.ListTcpRoutesRequest(), + parent="parent_value", + ) + + +def test_list_tcp_routes_rest_pager(transport: str = "rest"): + client = NetworkServicesClient( + 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 = ( + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + ], + next_page_token="abc", + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[], + next_page_token="def", + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + ], + next_page_token="ghi", + ), + tcp_route.ListTcpRoutesResponse( + tcp_routes=[ + tcp_route.TcpRoute(), + tcp_route.TcpRoute(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(tcp_route.ListTcpRoutesResponse.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_tcp_routes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tcp_route.TcpRoute) for i in results) + + pages = list(client.list_tcp_routes(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", + [ + tcp_route.GetTcpRouteRequest, + dict, + ], +) +def test_get_tcp_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/tcpRoutes/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 = tcp_route.TcpRoute( + name="name_value", + self_link="self_link_value", + description="description_value", + meshes=["meshes_value"], + gateways=["gateways_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = tcp_route.TcpRoute.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_tcp_route(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tcp_route.TcpRoute) + assert response.name == "name_value" + assert response.self_link == "self_link_value" + assert response.description == "description_value" + assert response.meshes == ["meshes_value"] + assert response.gateways == ["gateways_value"] + + +def test_get_tcp_route_rest_required_fields(request_type=tcp_route.GetTcpRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_tcp_route._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_tcp_route._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tcp_route.TcpRoute() + # 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 = tcp_route.TcpRoute.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_tcp_route(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_tcp_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_tcp_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_tcp_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_tcp_route" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_get_tcp_route" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tcp_route.GetTcpRouteRequest.pb(tcp_route.GetTcpRouteRequest()) + 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 = tcp_route.TcpRoute.to_json(tcp_route.TcpRoute()) + + request = tcp_route.GetTcpRouteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tcp_route.TcpRoute() + + client.get_tcp_route( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_tcp_route_rest_bad_request( + transport: str = "rest", request_type=tcp_route.GetTcpRouteRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/tcpRoutes/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_tcp_route(request) + + +def test_get_tcp_route_rest_flattened(): + client = NetworkServicesClient( + 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 = tcp_route.TcpRoute() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/tcpRoutes/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 = tcp_route.TcpRoute.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_tcp_route(**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/*/tcpRoutes/*}" % client.transport._host, + args[1], + ) + + +def test_get_tcp_route_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_tcp_route( + tcp_route.GetTcpRouteRequest(), + name="name_value", + ) + + +def test_get_tcp_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_tcp_route.CreateTcpRouteRequest, + dict, + ], +) +def test_create_tcp_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["tcp_route"] = { + "name": "name_value", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "description": "description_value", + "rules": [ + { + "matches": [{"address": "address_value", "port": "port_value"}], + "action": { + "destinations": [ + {"service_name": "service_name_value", "weight": 648} + ], + "original_destination": True, + }, + } + ], + "meshes": ["meshes_value1", "meshes_value2"], + "gateways": ["gateways_value1", "gateways_value2"], + "labels": {}, + } + 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_tcp_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_tcp_route_rest_required_fields( + request_type=gcn_tcp_route.CreateTcpRouteRequest, +): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["tcp_route_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 "tcpRouteId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_tcp_route._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "tcpRouteId" in jsonified_request + assert jsonified_request["tcpRouteId"] == request_init["tcp_route_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["tcpRouteId"] = "tcp_route_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_tcp_route._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("tcp_route_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 "tcpRouteId" in jsonified_request + assert jsonified_request["tcpRouteId"] == "tcp_route_id_value" + + client = NetworkServicesClient( + 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_tcp_route(request) + + expected_params = [ + ( + "tcpRouteId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_tcp_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_tcp_route._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("tcpRouteId",)) + & set( + ( + "parent", + "tcpRouteId", + "tcpRoute", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_tcp_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_tcp_route" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_create_tcp_route" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_tcp_route.CreateTcpRouteRequest.pb( + gcn_tcp_route.CreateTcpRouteRequest() + ) + 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 = gcn_tcp_route.CreateTcpRouteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_tcp_route( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_tcp_route_rest_bad_request( + transport: str = "rest", request_type=gcn_tcp_route.CreateTcpRouteRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["tcp_route"] = { + "name": "name_value", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "description": "description_value", + "rules": [ + { + "matches": [{"address": "address_value", "port": "port_value"}], + "action": { + "destinations": [ + {"service_name": "service_name_value", "weight": 648} + ], + "original_destination": True, + }, + } + ], + "meshes": ["meshes_value1", "meshes_value2"], + "gateways": ["gateways_value1", "gateways_value2"], + "labels": {}, + } + 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_tcp_route(request) + + +def test_create_tcp_route_rest_flattened(): + client = NetworkServicesClient( + 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", + tcp_route=gcn_tcp_route.TcpRoute(name="name_value"), + tcp_route_id="tcp_route_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_tcp_route(**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/*}/tcpRoutes" % client.transport._host, + args[1], + ) + + +def test_create_tcp_route_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_tcp_route( + gcn_tcp_route.CreateTcpRouteRequest(), + parent="parent_value", + tcp_route=gcn_tcp_route.TcpRoute(name="name_value"), + tcp_route_id="tcp_route_id_value", + ) + + +def test_create_tcp_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_tcp_route.UpdateTcpRouteRequest, + dict, + ], +) +def test_update_tcp_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "tcp_route": {"name": "projects/sample1/locations/sample2/tcpRoutes/sample3"} + } + request_init["tcp_route"] = { + "name": "projects/sample1/locations/sample2/tcpRoutes/sample3", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "description": "description_value", + "rules": [ + { + "matches": [{"address": "address_value", "port": "port_value"}], + "action": { + "destinations": [ + {"service_name": "service_name_value", "weight": 648} + ], + "original_destination": True, + }, + } + ], + "meshes": ["meshes_value1", "meshes_value2"], + "gateways": ["gateways_value1", "gateways_value2"], + "labels": {}, + } + 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_tcp_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_tcp_route_rest_required_fields( + request_type=gcn_tcp_route.UpdateTcpRouteRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_tcp_route._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_tcp_route._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 = NetworkServicesClient( + 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_tcp_route(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_tcp_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_tcp_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("tcpRoute",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_tcp_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_tcp_route" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_update_tcp_route" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_tcp_route.UpdateTcpRouteRequest.pb( + gcn_tcp_route.UpdateTcpRouteRequest() + ) + 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 = gcn_tcp_route.UpdateTcpRouteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_tcp_route( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_tcp_route_rest_bad_request( + transport: str = "rest", request_type=gcn_tcp_route.UpdateTcpRouteRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "tcp_route": {"name": "projects/sample1/locations/sample2/tcpRoutes/sample3"} + } + request_init["tcp_route"] = { + "name": "projects/sample1/locations/sample2/tcpRoutes/sample3", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "description": "description_value", + "rules": [ + { + "matches": [{"address": "address_value", "port": "port_value"}], + "action": { + "destinations": [ + {"service_name": "service_name_value", "weight": 648} + ], + "original_destination": True, + }, + } + ], + "meshes": ["meshes_value1", "meshes_value2"], + "gateways": ["gateways_value1", "gateways_value2"], + "labels": {}, + } + 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_tcp_route(request) + + +def test_update_tcp_route_rest_flattened(): + client = NetworkServicesClient( + 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 = { + "tcp_route": { + "name": "projects/sample1/locations/sample2/tcpRoutes/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + tcp_route=gcn_tcp_route.TcpRoute(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_tcp_route(**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/{tcp_route.name=projects/*/locations/*/tcpRoutes/*}" + % client.transport._host, + args[1], + ) + + +def test_update_tcp_route_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_tcp_route( + gcn_tcp_route.UpdateTcpRouteRequest(), + tcp_route=gcn_tcp_route.TcpRoute(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_tcp_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + tcp_route.DeleteTcpRouteRequest, + dict, + ], +) +def test_delete_tcp_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/tcpRoutes/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_tcp_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_tcp_route_rest_required_fields( + request_type=tcp_route.DeleteTcpRouteRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_tcp_route._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_tcp_route._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 = NetworkServicesClient( + 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_tcp_route(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_tcp_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_tcp_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_tcp_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_tcp_route" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_delete_tcp_route" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tcp_route.DeleteTcpRouteRequest.pb( + tcp_route.DeleteTcpRouteRequest() + ) + 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 = tcp_route.DeleteTcpRouteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_tcp_route( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_tcp_route_rest_bad_request( + transport: str = "rest", request_type=tcp_route.DeleteTcpRouteRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/tcpRoutes/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_tcp_route(request) + + +def test_delete_tcp_route_rest_flattened(): + client = NetworkServicesClient( + 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/tcpRoutes/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_tcp_route(**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/*/tcpRoutes/*}" % client.transport._host, + args[1], + ) + + +def test_delete_tcp_route_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_tcp_route( + tcp_route.DeleteTcpRouteRequest(), + name="name_value", + ) + + +def test_delete_tcp_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + tls_route.ListTlsRoutesRequest, + dict, + ], +) +def test_list_tls_routes_rest(request_type): + client = NetworkServicesClient( + 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 = tls_route.ListTlsRoutesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = tls_route.ListTlsRoutesResponse.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_tls_routes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTlsRoutesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_tls_routes_rest_required_fields( + request_type=tls_route.ListTlsRoutesRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_tls_routes._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_tls_routes._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tls_route.ListTlsRoutesResponse() + # 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 = tls_route.ListTlsRoutesResponse.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_tls_routes(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_tls_routes_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_tls_routes._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tls_routes_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_tls_routes" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_list_tls_routes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tls_route.ListTlsRoutesRequest.pb(tls_route.ListTlsRoutesRequest()) + 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 = tls_route.ListTlsRoutesResponse.to_json( + tls_route.ListTlsRoutesResponse() + ) + + request = tls_route.ListTlsRoutesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tls_route.ListTlsRoutesResponse() + + client.list_tls_routes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_tls_routes_rest_bad_request( + transport: str = "rest", request_type=tls_route.ListTlsRoutesRequest +): + client = NetworkServicesClient( + 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_tls_routes(request) + + +def test_list_tls_routes_rest_flattened(): + client = NetworkServicesClient( + 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 = tls_route.ListTlsRoutesResponse() + + # 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 = tls_route.ListTlsRoutesResponse.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_tls_routes(**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/*}/tlsRoutes" % client.transport._host, + args[1], + ) + + +def test_list_tls_routes_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_tls_routes( + tls_route.ListTlsRoutesRequest(), + parent="parent_value", + ) + + +def test_list_tls_routes_rest_pager(transport: str = "rest"): + client = NetworkServicesClient( + 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 = ( + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + tls_route.TlsRoute(), + tls_route.TlsRoute(), + ], + next_page_token="abc", + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[], + next_page_token="def", + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + ], + next_page_token="ghi", + ), + tls_route.ListTlsRoutesResponse( + tls_routes=[ + tls_route.TlsRoute(), + tls_route.TlsRoute(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(tls_route.ListTlsRoutesResponse.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_tls_routes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tls_route.TlsRoute) for i in results) + + pages = list(client.list_tls_routes(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", + [ + tls_route.GetTlsRouteRequest, + dict, + ], +) +def test_get_tls_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/tlsRoutes/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 = tls_route.TlsRoute( + name="name_value", + self_link="self_link_value", + description="description_value", + meshes=["meshes_value"], + gateways=["gateways_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = tls_route.TlsRoute.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_tls_route(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tls_route.TlsRoute) + assert response.name == "name_value" + assert response.self_link == "self_link_value" + assert response.description == "description_value" + assert response.meshes == ["meshes_value"] + assert response.gateways == ["gateways_value"] + + +def test_get_tls_route_rest_required_fields(request_type=tls_route.GetTlsRouteRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_tls_route._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_tls_route._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tls_route.TlsRoute() + # 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 = tls_route.TlsRoute.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_tls_route(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_tls_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_tls_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_tls_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_tls_route" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_get_tls_route" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tls_route.GetTlsRouteRequest.pb(tls_route.GetTlsRouteRequest()) + 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 = tls_route.TlsRoute.to_json(tls_route.TlsRoute()) + + request = tls_route.GetTlsRouteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tls_route.TlsRoute() + + client.get_tls_route( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_tls_route_rest_bad_request( + transport: str = "rest", request_type=tls_route.GetTlsRouteRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/tlsRoutes/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_tls_route(request) + + +def test_get_tls_route_rest_flattened(): + client = NetworkServicesClient( + 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 = tls_route.TlsRoute() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/tlsRoutes/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 = tls_route.TlsRoute.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_tls_route(**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/*/tlsRoutes/*}" % client.transport._host, + args[1], + ) + + +def test_get_tls_route_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_tls_route( + tls_route.GetTlsRouteRequest(), + name="name_value", + ) + + +def test_get_tls_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_tls_route.CreateTlsRouteRequest, + dict, + ], +) +def test_create_tls_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["tls_route"] = { + "name": "name_value", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "description": "description_value", + "rules": [ + { + "matches": [ + { + "sni_host": ["sni_host_value1", "sni_host_value2"], + "alpn": ["alpn_value1", "alpn_value2"], + } + ], + "action": { + "destinations": [ + {"service_name": "service_name_value", "weight": 648} + ] + }, + } + ], + "meshes": ["meshes_value1", "meshes_value2"], + "gateways": ["gateways_value1", "gateways_value2"], + } + 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_tls_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_tls_route_rest_required_fields( + request_type=gcn_tls_route.CreateTlsRouteRequest, +): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["tls_route_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 "tlsRouteId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_tls_route._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "tlsRouteId" in jsonified_request + assert jsonified_request["tlsRouteId"] == request_init["tls_route_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["tlsRouteId"] = "tls_route_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_tls_route._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("tls_route_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 "tlsRouteId" in jsonified_request + assert jsonified_request["tlsRouteId"] == "tls_route_id_value" + + client = NetworkServicesClient( + 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_tls_route(request) + + expected_params = [ + ( + "tlsRouteId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_tls_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_tls_route._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("tlsRouteId",)) + & set( + ( + "parent", + "tlsRouteId", + "tlsRoute", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_tls_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_tls_route" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_create_tls_route" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_tls_route.CreateTlsRouteRequest.pb( + gcn_tls_route.CreateTlsRouteRequest() + ) + 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 = gcn_tls_route.CreateTlsRouteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_tls_route( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_tls_route_rest_bad_request( + transport: str = "rest", request_type=gcn_tls_route.CreateTlsRouteRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["tls_route"] = { + "name": "name_value", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "description": "description_value", + "rules": [ + { + "matches": [ + { + "sni_host": ["sni_host_value1", "sni_host_value2"], + "alpn": ["alpn_value1", "alpn_value2"], + } + ], + "action": { + "destinations": [ + {"service_name": "service_name_value", "weight": 648} + ] + }, + } + ], + "meshes": ["meshes_value1", "meshes_value2"], + "gateways": ["gateways_value1", "gateways_value2"], + } + 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_tls_route(request) + + +def test_create_tls_route_rest_flattened(): + client = NetworkServicesClient( + 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", + tls_route=gcn_tls_route.TlsRoute(name="name_value"), + tls_route_id="tls_route_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_tls_route(**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/*}/tlsRoutes" % client.transport._host, + args[1], + ) + + +def test_create_tls_route_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_tls_route( + gcn_tls_route.CreateTlsRouteRequest(), + parent="parent_value", + tls_route=gcn_tls_route.TlsRoute(name="name_value"), + tls_route_id="tls_route_id_value", + ) + + +def test_create_tls_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_tls_route.UpdateTlsRouteRequest, + dict, + ], +) +def test_update_tls_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "tls_route": {"name": "projects/sample1/locations/sample2/tlsRoutes/sample3"} + } + request_init["tls_route"] = { + "name": "projects/sample1/locations/sample2/tlsRoutes/sample3", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "description": "description_value", + "rules": [ + { + "matches": [ + { + "sni_host": ["sni_host_value1", "sni_host_value2"], + "alpn": ["alpn_value1", "alpn_value2"], + } + ], + "action": { + "destinations": [ + {"service_name": "service_name_value", "weight": 648} + ] + }, + } + ], + "meshes": ["meshes_value1", "meshes_value2"], + "gateways": ["gateways_value1", "gateways_value2"], + } + 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_tls_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_tls_route_rest_required_fields( + request_type=gcn_tls_route.UpdateTlsRouteRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_tls_route._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_tls_route._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 = NetworkServicesClient( + 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_tls_route(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_tls_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_tls_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("tlsRoute",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_tls_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_tls_route" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_update_tls_route" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_tls_route.UpdateTlsRouteRequest.pb( + gcn_tls_route.UpdateTlsRouteRequest() + ) + 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 = gcn_tls_route.UpdateTlsRouteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_tls_route( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_tls_route_rest_bad_request( + transport: str = "rest", request_type=gcn_tls_route.UpdateTlsRouteRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "tls_route": {"name": "projects/sample1/locations/sample2/tlsRoutes/sample3"} + } + request_init["tls_route"] = { + "name": "projects/sample1/locations/sample2/tlsRoutes/sample3", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "description": "description_value", + "rules": [ + { + "matches": [ + { + "sni_host": ["sni_host_value1", "sni_host_value2"], + "alpn": ["alpn_value1", "alpn_value2"], + } + ], + "action": { + "destinations": [ + {"service_name": "service_name_value", "weight": 648} + ] + }, + } + ], + "meshes": ["meshes_value1", "meshes_value2"], + "gateways": ["gateways_value1", "gateways_value2"], + } + 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_tls_route(request) + + +def test_update_tls_route_rest_flattened(): + client = NetworkServicesClient( + 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 = { + "tls_route": { + "name": "projects/sample1/locations/sample2/tlsRoutes/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + tls_route=gcn_tls_route.TlsRoute(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_tls_route(**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/{tls_route.name=projects/*/locations/*/tlsRoutes/*}" + % client.transport._host, + args[1], + ) + + +def test_update_tls_route_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_tls_route( + gcn_tls_route.UpdateTlsRouteRequest(), + tls_route=gcn_tls_route.TlsRoute(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_tls_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + tls_route.DeleteTlsRouteRequest, + dict, + ], +) +def test_delete_tls_route_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/tlsRoutes/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_tls_route(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_tls_route_rest_required_fields( + request_type=tls_route.DeleteTlsRouteRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_tls_route._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_tls_route._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 = NetworkServicesClient( + 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_tls_route(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_tls_route_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_tls_route._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_tls_route_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_tls_route" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_delete_tls_route" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tls_route.DeleteTlsRouteRequest.pb( + tls_route.DeleteTlsRouteRequest() + ) + 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 = tls_route.DeleteTlsRouteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_tls_route( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_tls_route_rest_bad_request( + transport: str = "rest", request_type=tls_route.DeleteTlsRouteRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/tlsRoutes/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_tls_route(request) + + +def test_delete_tls_route_rest_flattened(): + client = NetworkServicesClient( + 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/tlsRoutes/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_tls_route(**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/*/tlsRoutes/*}" % client.transport._host, + args[1], + ) + + +def test_delete_tls_route_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_tls_route( + tls_route.DeleteTlsRouteRequest(), + name="name_value", + ) + + +def test_delete_tls_route_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service_binding.ListServiceBindingsRequest, + dict, + ], +) +def test_list_service_bindings_rest(request_type): + client = NetworkServicesClient( + 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 = service_binding.ListServiceBindingsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service_binding.ListServiceBindingsResponse.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_service_bindings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServiceBindingsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_service_bindings_rest_required_fields( + request_type=service_binding.ListServiceBindingsRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_service_bindings._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_service_bindings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service_binding.ListServiceBindingsResponse() + # 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 = service_binding.ListServiceBindingsResponse.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_service_bindings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_service_bindings_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_service_bindings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_service_bindings_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_service_bindings" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_list_service_bindings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service_binding.ListServiceBindingsRequest.pb( + service_binding.ListServiceBindingsRequest() + ) + 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 = service_binding.ListServiceBindingsResponse.to_json( + service_binding.ListServiceBindingsResponse() + ) + + request = service_binding.ListServiceBindingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service_binding.ListServiceBindingsResponse() + + client.list_service_bindings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_service_bindings_rest_bad_request( + transport: str = "rest", request_type=service_binding.ListServiceBindingsRequest +): + client = NetworkServicesClient( + 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_service_bindings(request) + + +def test_list_service_bindings_rest_flattened(): + client = NetworkServicesClient( + 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 = service_binding.ListServiceBindingsResponse() + + # 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 = service_binding.ListServiceBindingsResponse.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_service_bindings(**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/*}/serviceBindings" + % client.transport._host, + args[1], + ) + + +def test_list_service_bindings_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_service_bindings( + service_binding.ListServiceBindingsRequest(), + parent="parent_value", + ) + + +def test_list_service_bindings_rest_pager(transport: str = "rest"): + client = NetworkServicesClient( + 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 = ( + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + ], + next_page_token="abc", + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[], + next_page_token="def", + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + ], + next_page_token="ghi", + ), + service_binding.ListServiceBindingsResponse( + service_bindings=[ + service_binding.ServiceBinding(), + service_binding.ServiceBinding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service_binding.ListServiceBindingsResponse.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_service_bindings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, service_binding.ServiceBinding) for i in results) + + pages = list(client.list_service_bindings(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", + [ + service_binding.GetServiceBindingRequest, + dict, + ], +) +def test_get_service_binding_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/serviceBindings/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 = service_binding.ServiceBinding( + name="name_value", + description="description_value", + service="service_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service_binding.ServiceBinding.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_service_binding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service_binding.ServiceBinding) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.service == "service_value" + + +def test_get_service_binding_rest_required_fields( + request_type=service_binding.GetServiceBindingRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_service_binding._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_service_binding._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service_binding.ServiceBinding() + # 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 = service_binding.ServiceBinding.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_service_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_service_binding_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_service_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_service_binding_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_service_binding" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_get_service_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service_binding.GetServiceBindingRequest.pb( + service_binding.GetServiceBindingRequest() + ) + 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 = service_binding.ServiceBinding.to_json( + service_binding.ServiceBinding() + ) + + request = service_binding.GetServiceBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service_binding.ServiceBinding() + + client.get_service_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_service_binding_rest_bad_request( + transport: str = "rest", request_type=service_binding.GetServiceBindingRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/serviceBindings/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_service_binding(request) + + +def test_get_service_binding_rest_flattened(): + client = NetworkServicesClient( + 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 = service_binding.ServiceBinding() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/serviceBindings/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 = service_binding.ServiceBinding.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_service_binding(**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/*/serviceBindings/*}" + % client.transport._host, + args[1], + ) + + +def test_get_service_binding_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_service_binding( + service_binding.GetServiceBindingRequest(), + name="name_value", + ) + + +def test_get_service_binding_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_service_binding.CreateServiceBindingRequest, + dict, + ], +) +def test_create_service_binding_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["service_binding"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "service": "service_value", + "labels": {}, + } + 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_service_binding(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_service_binding_rest_required_fields( + request_type=gcn_service_binding.CreateServiceBindingRequest, +): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["service_binding_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 "serviceBindingId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_service_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "serviceBindingId" in jsonified_request + assert jsonified_request["serviceBindingId"] == request_init["service_binding_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["serviceBindingId"] = "service_binding_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_service_binding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("service_binding_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 "serviceBindingId" in jsonified_request + assert jsonified_request["serviceBindingId"] == "service_binding_id_value" + + client = NetworkServicesClient( + 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_service_binding(request) + + expected_params = [ + ( + "serviceBindingId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_service_binding_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_service_binding._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("serviceBindingId",)) + & set( + ( + "parent", + "serviceBindingId", + "serviceBinding", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_service_binding_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_service_binding" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_create_service_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_service_binding.CreateServiceBindingRequest.pb( + gcn_service_binding.CreateServiceBindingRequest() + ) + 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 = gcn_service_binding.CreateServiceBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_service_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_service_binding_rest_bad_request( + transport: str = "rest", + request_type=gcn_service_binding.CreateServiceBindingRequest, +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["service_binding"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "service": "service_value", + "labels": {}, + } + 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_service_binding(request) + + +def test_create_service_binding_rest_flattened(): + client = NetworkServicesClient( + 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", + service_binding=gcn_service_binding.ServiceBinding(name="name_value"), + service_binding_id="service_binding_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_service_binding(**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/*}/serviceBindings" + % client.transport._host, + args[1], + ) + + +def test_create_service_binding_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_service_binding( + gcn_service_binding.CreateServiceBindingRequest(), + parent="parent_value", + service_binding=gcn_service_binding.ServiceBinding(name="name_value"), + service_binding_id="service_binding_id_value", + ) + + +def test_create_service_binding_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service_binding.DeleteServiceBindingRequest, + dict, + ], +) +def test_delete_service_binding_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/serviceBindings/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_service_binding(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_service_binding_rest_required_fields( + request_type=service_binding.DeleteServiceBindingRequest, +): + transport_class = transports.NetworkServicesRestTransport + + 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_service_binding._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_service_binding._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 = NetworkServicesClient( + 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_service_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_service_binding_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_service_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_service_binding_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_service_binding" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_delete_service_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service_binding.DeleteServiceBindingRequest.pb( + service_binding.DeleteServiceBindingRequest() + ) + 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 = service_binding.DeleteServiceBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_service_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_service_binding_rest_bad_request( + transport: str = "rest", request_type=service_binding.DeleteServiceBindingRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/serviceBindings/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_service_binding(request) + + +def test_delete_service_binding_rest_flattened(): + client = NetworkServicesClient( + 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/serviceBindings/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_service_binding(**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/*/serviceBindings/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_service_binding_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_service_binding( + service_binding.DeleteServiceBindingRequest(), + name="name_value", + ) + + +def test_delete_service_binding_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + mesh.ListMeshesRequest, + dict, + ], +) +def test_list_meshes_rest(request_type): + client = NetworkServicesClient( + 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 = mesh.ListMeshesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = mesh.ListMeshesResponse.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_meshes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMeshesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_meshes_rest_required_fields(request_type=mesh.ListMeshesRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_meshes._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_meshes._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = mesh.ListMeshesResponse() + # 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 = mesh.ListMeshesResponse.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_meshes(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_meshes_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_meshes._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_meshes_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_list_meshes" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_list_meshes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = mesh.ListMeshesRequest.pb(mesh.ListMeshesRequest()) + 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 = mesh.ListMeshesResponse.to_json( + mesh.ListMeshesResponse() + ) + + request = mesh.ListMeshesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = mesh.ListMeshesResponse() + + client.list_meshes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_meshes_rest_bad_request( + transport: str = "rest", request_type=mesh.ListMeshesRequest +): + client = NetworkServicesClient( + 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_meshes(request) + + +def test_list_meshes_rest_flattened(): + client = NetworkServicesClient( + 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 = mesh.ListMeshesResponse() + + # 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 = mesh.ListMeshesResponse.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_meshes(**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/*}/meshes" % client.transport._host, + args[1], + ) + + +def test_list_meshes_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_meshes( + mesh.ListMeshesRequest(), + parent="parent_value", + ) + + +def test_list_meshes_rest_pager(transport: str = "rest"): + client = NetworkServicesClient( + 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 = ( + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + mesh.Mesh(), + mesh.Mesh(), + ], + next_page_token="abc", + ), + mesh.ListMeshesResponse( + meshes=[], + next_page_token="def", + ), + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + ], + next_page_token="ghi", + ), + mesh.ListMeshesResponse( + meshes=[ + mesh.Mesh(), + mesh.Mesh(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(mesh.ListMeshesResponse.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_meshes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, mesh.Mesh) for i in results) + + pages = list(client.list_meshes(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", + [ + mesh.GetMeshRequest, + dict, + ], +) +def test_get_mesh_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/meshes/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 = mesh.Mesh( + name="name_value", + self_link="self_link_value", + description="description_value", + interception_port=1848, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = mesh.Mesh.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_mesh(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, mesh.Mesh) + assert response.name == "name_value" + assert response.self_link == "self_link_value" + assert response.description == "description_value" + assert response.interception_port == 1848 + + +def test_get_mesh_rest_required_fields(request_type=mesh.GetMeshRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_mesh._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_mesh._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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = mesh.Mesh() + # 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 = mesh.Mesh.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_mesh(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_mesh_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_mesh._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_mesh_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_get_mesh" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_get_mesh" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = mesh.GetMeshRequest.pb(mesh.GetMeshRequest()) + 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 = mesh.Mesh.to_json(mesh.Mesh()) + + request = mesh.GetMeshRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = mesh.Mesh() + + client.get_mesh( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_mesh_rest_bad_request( + transport: str = "rest", request_type=mesh.GetMeshRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/meshes/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_mesh(request) + + +def test_get_mesh_rest_flattened(): + client = NetworkServicesClient( + 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 = mesh.Mesh() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/meshes/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 = mesh.Mesh.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_mesh(**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/*/meshes/*}" % client.transport._host, + args[1], + ) + + +def test_get_mesh_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_mesh( + mesh.GetMeshRequest(), + name="name_value", + ) + + +def test_get_mesh_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_mesh.CreateMeshRequest, + dict, + ], +) +def test_create_mesh_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["mesh"] = { + "name": "name_value", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "interception_port": 1848, + } + 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_mesh(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_mesh_rest_required_fields(request_type=gcn_mesh.CreateMeshRequest): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["mesh_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 "meshId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_mesh._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "meshId" in jsonified_request + assert jsonified_request["meshId"] == request_init["mesh_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["meshId"] = "mesh_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_mesh._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("mesh_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 "meshId" in jsonified_request + assert jsonified_request["meshId"] == "mesh_id_value" + + client = NetworkServicesClient( + 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_mesh(request) + + expected_params = [ + ( + "meshId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_mesh_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_mesh._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("meshId",)) + & set( + ( + "parent", + "meshId", + "mesh", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_mesh_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_create_mesh" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_create_mesh" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_mesh.CreateMeshRequest.pb(gcn_mesh.CreateMeshRequest()) + 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 = gcn_mesh.CreateMeshRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_mesh( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_mesh_rest_bad_request( + transport: str = "rest", request_type=gcn_mesh.CreateMeshRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["mesh"] = { + "name": "name_value", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "interception_port": 1848, + } + 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_mesh(request) + + +def test_create_mesh_rest_flattened(): + client = NetworkServicesClient( + 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", + mesh=gcn_mesh.Mesh(name="name_value"), + mesh_id="mesh_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_mesh(**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/*}/meshes" % client.transport._host, + args[1], + ) + + +def test_create_mesh_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_mesh( + gcn_mesh.CreateMeshRequest(), + parent="parent_value", + mesh=gcn_mesh.Mesh(name="name_value"), + mesh_id="mesh_id_value", + ) + + +def test_create_mesh_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_mesh.UpdateMeshRequest, + dict, + ], +) +def test_update_mesh_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "mesh": {"name": "projects/sample1/locations/sample2/meshes/sample3"} + } + request_init["mesh"] = { + "name": "projects/sample1/locations/sample2/meshes/sample3", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "interception_port": 1848, + } + 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_mesh(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_mesh_rest_required_fields(request_type=gcn_mesh.UpdateMeshRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_mesh._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_mesh._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 = NetworkServicesClient( + 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_mesh(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_mesh_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_mesh._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("mesh",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_mesh_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_update_mesh" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_update_mesh" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcn_mesh.UpdateMeshRequest.pb(gcn_mesh.UpdateMeshRequest()) + 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 = gcn_mesh.UpdateMeshRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_mesh( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_mesh_rest_bad_request( + transport: str = "rest", request_type=gcn_mesh.UpdateMeshRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "mesh": {"name": "projects/sample1/locations/sample2/meshes/sample3"} + } + request_init["mesh"] = { + "name": "projects/sample1/locations/sample2/meshes/sample3", + "self_link": "self_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "interception_port": 1848, + } + 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_mesh(request) + + +def test_update_mesh_rest_flattened(): + client = NetworkServicesClient( + 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 = { + "mesh": {"name": "projects/sample1/locations/sample2/meshes/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + mesh=gcn_mesh.Mesh(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_mesh(**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/{mesh.name=projects/*/locations/*/meshes/*}" + % client.transport._host, + args[1], + ) + + +def test_update_mesh_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_mesh( + gcn_mesh.UpdateMeshRequest(), + mesh=gcn_mesh.Mesh(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_mesh_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + mesh.DeleteMeshRequest, + dict, + ], +) +def test_delete_mesh_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/meshes/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_mesh(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_mesh_rest_required_fields(request_type=mesh.DeleteMeshRequest): + transport_class = transports.NetworkServicesRestTransport + + 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_mesh._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_mesh._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 = NetworkServicesClient( + 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_mesh(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_mesh_rest_unset_required_fields(): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_mesh._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_mesh_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(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.NetworkServicesRestInterceptor, "post_delete_mesh" + ) as post, mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_delete_mesh" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = mesh.DeleteMeshRequest.pb(mesh.DeleteMeshRequest()) + 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 = mesh.DeleteMeshRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_mesh( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_mesh_rest_bad_request( + transport: str = "rest", request_type=mesh.DeleteMeshRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/meshes/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_mesh(request) + + +def test_delete_mesh_rest_flattened(): + client = NetworkServicesClient( + 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/meshes/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_mesh(**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/*/meshes/*}" % client.transport._host, + args[1], + ) + + +def test_delete_mesh_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + 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_mesh( + mesh.DeleteMeshRequest(), + name="name_value", + ) + + +def test_delete_mesh_rest_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkServicesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = NetworkServicesClient( + 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 = NetworkServicesClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkServicesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = NetworkServicesClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.NetworkServicesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.NetworkServicesGrpcTransport, + transports.NetworkServicesGrpcAsyncIOTransport, + transports.NetworkServicesRestTransport, + ], +) +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 = NetworkServicesClient.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 = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.NetworkServicesGrpcTransport, + ) + + +def test_network_services_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.NetworkServicesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_network_services_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.network_services_v1.services.network_services.transports.NetworkServicesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.NetworkServicesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. methods = ( "list_endpoint_policies", "get_endpoint_policy", @@ -12013,6 +24272,7 @@ def test_network_services_transport_auth_adc(transport_class): [ transports.NetworkServicesGrpcTransport, transports.NetworkServicesGrpcAsyncIOTransport, + transports.NetworkServicesRestTransport, ], ) def test_network_services_transport_auth_gdch_credentials(transport_class): @@ -12110,11 +24370,40 @@ def test_network_services_grpc_transport_client_cert_source_for_mtls(transport_c ) +def test_network_services_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.NetworkServicesRestTransport( + 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_network_services_rest_lro_client(): + client = NetworkServicesClient( + 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_network_services_host_no_port(transport_name): @@ -12125,7 +24414,11 @@ def test_network_services_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("networkservices.googleapis.com:443") + assert client.transport._host == ( + "networkservices.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networkservices.googleapis.com" + ) @pytest.mark.parametrize( @@ -12133,6 +24426,7 @@ def test_network_services_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_network_services_host_with_port(transport_name): @@ -12143,7 +24437,147 @@ def test_network_services_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("networkservices.googleapis.com:8000") + assert client.transport._host == ( + "networkservices.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networkservices.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_network_services_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = NetworkServicesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = NetworkServicesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_endpoint_policies._session + session2 = client2.transport.list_endpoint_policies._session + assert session1 != session2 + session1 = client1.transport.get_endpoint_policy._session + session2 = client2.transport.get_endpoint_policy._session + assert session1 != session2 + session1 = client1.transport.create_endpoint_policy._session + session2 = client2.transport.create_endpoint_policy._session + assert session1 != session2 + session1 = client1.transport.update_endpoint_policy._session + session2 = client2.transport.update_endpoint_policy._session + assert session1 != session2 + session1 = client1.transport.delete_endpoint_policy._session + session2 = client2.transport.delete_endpoint_policy._session + assert session1 != session2 + 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_grpc_routes._session + session2 = client2.transport.list_grpc_routes._session + assert session1 != session2 + session1 = client1.transport.get_grpc_route._session + session2 = client2.transport.get_grpc_route._session + assert session1 != session2 + session1 = client1.transport.create_grpc_route._session + session2 = client2.transport.create_grpc_route._session + assert session1 != session2 + session1 = client1.transport.update_grpc_route._session + session2 = client2.transport.update_grpc_route._session + assert session1 != session2 + session1 = client1.transport.delete_grpc_route._session + session2 = client2.transport.delete_grpc_route._session + assert session1 != session2 + session1 = client1.transport.list_http_routes._session + session2 = client2.transport.list_http_routes._session + assert session1 != session2 + session1 = client1.transport.get_http_route._session + session2 = client2.transport.get_http_route._session + assert session1 != session2 + session1 = client1.transport.create_http_route._session + session2 = client2.transport.create_http_route._session + assert session1 != session2 + session1 = client1.transport.update_http_route._session + session2 = client2.transport.update_http_route._session + assert session1 != session2 + session1 = client1.transport.delete_http_route._session + session2 = client2.transport.delete_http_route._session + assert session1 != session2 + session1 = client1.transport.list_tcp_routes._session + session2 = client2.transport.list_tcp_routes._session + assert session1 != session2 + session1 = client1.transport.get_tcp_route._session + session2 = client2.transport.get_tcp_route._session + assert session1 != session2 + session1 = client1.transport.create_tcp_route._session + session2 = client2.transport.create_tcp_route._session + assert session1 != session2 + session1 = client1.transport.update_tcp_route._session + session2 = client2.transport.update_tcp_route._session + assert session1 != session2 + session1 = client1.transport.delete_tcp_route._session + session2 = client2.transport.delete_tcp_route._session + assert session1 != session2 + session1 = client1.transport.list_tls_routes._session + session2 = client2.transport.list_tls_routes._session + assert session1 != session2 + session1 = client1.transport.get_tls_route._session + session2 = client2.transport.get_tls_route._session + assert session1 != session2 + session1 = client1.transport.create_tls_route._session + session2 = client2.transport.create_tls_route._session + assert session1 != session2 + session1 = client1.transport.update_tls_route._session + session2 = client2.transport.update_tls_route._session + assert session1 != session2 + session1 = client1.transport.delete_tls_route._session + session2 = client2.transport.delete_tls_route._session + assert session1 != session2 + session1 = client1.transport.list_service_bindings._session + session2 = client2.transport.list_service_bindings._session + assert session1 != session2 + session1 = client1.transport.get_service_binding._session + session2 = client2.transport.get_service_binding._session + assert session1 != session2 + session1 = client1.transport.create_service_binding._session + session2 = client2.transport.create_service_binding._session + assert session1 != session2 + session1 = client1.transport.delete_service_binding._session + session2 = client2.transport.delete_service_binding._session + assert session1 != session2 + session1 = client1.transport.list_meshes._session + session2 = client2.transport.list_meshes._session + assert session1 != session2 + session1 = client1.transport.get_mesh._session + session2 = client2.transport.get_mesh._session + assert session1 != session2 + session1 = client1.transport.create_mesh._session + session2 = client2.transport.create_mesh._session + assert session1 != session2 + session1 = client1.transport.update_mesh._session + session2 = client2.transport.update_mesh._session + assert session1 != session2 + session1 = client1.transport.delete_mesh._session + session2 = client2.transport.delete_mesh._session + assert session1 != session2 def test_network_services_grpc_transport_channel(): @@ -12427,347 +24861,876 @@ def test_gateway_path(): location=location, gateway=gateway, ) - actual = NetworkServicesClient.gateway_path(project, location, gateway) + actual = NetworkServicesClient.gateway_path(project, location, gateway) + assert expected == actual + + +def test_parse_gateway_path(): + expected = { + "project": "octopus", + "location": "oyster", + "gateway": "nudibranch", + } + path = NetworkServicesClient.gateway_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_gateway_path(path) + assert expected == actual + + +def test_grpc_route_path(): + project = "cuttlefish" + location = "mussel" + grpc_route = "winkle" + expected = "projects/{project}/locations/{location}/grpcRoutes/{grpc_route}".format( + project=project, + location=location, + grpc_route=grpc_route, + ) + actual = NetworkServicesClient.grpc_route_path(project, location, grpc_route) + assert expected == actual + + +def test_parse_grpc_route_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "grpc_route": "abalone", + } + path = NetworkServicesClient.grpc_route_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_grpc_route_path(path) + assert expected == actual + + +def test_http_route_path(): + project = "squid" + location = "clam" + http_route = "whelk" + expected = "projects/{project}/locations/{location}/httpRoutes/{http_route}".format( + project=project, + location=location, + http_route=http_route, + ) + actual = NetworkServicesClient.http_route_path(project, location, http_route) + assert expected == actual + + +def test_parse_http_route_path(): + expected = { + "project": "octopus", + "location": "oyster", + "http_route": "nudibranch", + } + path = NetworkServicesClient.http_route_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_http_route_path(path) + assert expected == actual + + +def test_mesh_path(): + project = "cuttlefish" + location = "mussel" + mesh = "winkle" + expected = "projects/{project}/locations/{location}/meshes/{mesh}".format( + project=project, + location=location, + mesh=mesh, + ) + actual = NetworkServicesClient.mesh_path(project, location, mesh) + assert expected == actual + + +def test_parse_mesh_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "mesh": "abalone", + } + path = NetworkServicesClient.mesh_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_mesh_path(path) + assert expected == actual + + +def test_server_tls_policy_path(): + project = "squid" + location = "clam" + server_tls_policy = "whelk" + expected = "projects/{project}/locations/{location}/serverTlsPolicies/{server_tls_policy}".format( + project=project, + location=location, + server_tls_policy=server_tls_policy, + ) + actual = NetworkServicesClient.server_tls_policy_path( + project, location, server_tls_policy + ) + assert expected == actual + + +def test_parse_server_tls_policy_path(): + expected = { + "project": "octopus", + "location": "oyster", + "server_tls_policy": "nudibranch", + } + path = NetworkServicesClient.server_tls_policy_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_server_tls_policy_path(path) + assert expected == actual + + +def test_service_binding_path(): + project = "cuttlefish" + location = "mussel" + service_binding = "winkle" + expected = "projects/{project}/locations/{location}/serviceBindings/{service_binding}".format( + project=project, + location=location, + service_binding=service_binding, + ) + actual = NetworkServicesClient.service_binding_path( + project, location, service_binding + ) + assert expected == actual + + +def test_parse_service_binding_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "service_binding": "abalone", + } + path = NetworkServicesClient.service_binding_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_service_binding_path(path) + assert expected == actual + + +def test_tcp_route_path(): + project = "squid" + location = "clam" + tcp_route = "whelk" + expected = "projects/{project}/locations/{location}/tcpRoutes/{tcp_route}".format( + project=project, + location=location, + tcp_route=tcp_route, + ) + actual = NetworkServicesClient.tcp_route_path(project, location, tcp_route) + assert expected == actual + + +def test_parse_tcp_route_path(): + expected = { + "project": "octopus", + "location": "oyster", + "tcp_route": "nudibranch", + } + path = NetworkServicesClient.tcp_route_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_tcp_route_path(path) + assert expected == actual + + +def test_tls_route_path(): + project = "cuttlefish" + location = "mussel" + tls_route = "winkle" + expected = "projects/{project}/locations/{location}/tlsRoutes/{tls_route}".format( + project=project, + location=location, + tls_route=tls_route, + ) + actual = NetworkServicesClient.tls_route_path(project, location, tls_route) + assert expected == actual + + +def test_parse_tls_route_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "tls_route": "abalone", + } + path = NetworkServicesClient.tls_route_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_tls_route_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = NetworkServicesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = NetworkServicesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = NetworkServicesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = NetworkServicesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = NetworkServicesClient.common_organization_path(organization) assert expected == actual -def test_parse_gateway_path(): +def test_parse_common_organization_path(): expected = { - "project": "octopus", - "location": "oyster", - "gateway": "nudibranch", + "organization": "nudibranch", } - path = NetworkServicesClient.gateway_path(**expected) + path = NetworkServicesClient.common_organization_path(**expected) # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_gateway_path(path) + actual = NetworkServicesClient.parse_common_organization_path(path) assert expected == actual -def test_grpc_route_path(): +def test_common_project_path(): project = "cuttlefish" - location = "mussel" - grpc_route = "winkle" - expected = "projects/{project}/locations/{location}/grpcRoutes/{grpc_route}".format( + expected = "projects/{project}".format( project=project, - location=location, - grpc_route=grpc_route, ) - actual = NetworkServicesClient.grpc_route_path(project, location, grpc_route) + actual = NetworkServicesClient.common_project_path(project) assert expected == actual -def test_parse_grpc_route_path(): +def test_parse_common_project_path(): expected = { - "project": "nautilus", - "location": "scallop", - "grpc_route": "abalone", + "project": "mussel", } - path = NetworkServicesClient.grpc_route_path(**expected) + path = NetworkServicesClient.common_project_path(**expected) # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_grpc_route_path(path) + actual = NetworkServicesClient.parse_common_project_path(path) assert expected == actual -def test_http_route_path(): - project = "squid" - location = "clam" - http_route = "whelk" - expected = "projects/{project}/locations/{location}/httpRoutes/{http_route}".format( +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( project=project, location=location, - http_route=http_route, ) - actual = NetworkServicesClient.http_route_path(project, location, http_route) + actual = NetworkServicesClient.common_location_path(project, location) assert expected == actual -def test_parse_http_route_path(): +def test_parse_common_location_path(): expected = { - "project": "octopus", - "location": "oyster", - "http_route": "nudibranch", + "project": "scallop", + "location": "abalone", } - path = NetworkServicesClient.http_route_path(**expected) + path = NetworkServicesClient.common_location_path(**expected) # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_http_route_path(path) + actual = NetworkServicesClient.parse_common_location_path(path) assert expected == actual -def test_mesh_path(): - project = "cuttlefish" - location = "mussel" - mesh = "winkle" - expected = "projects/{project}/locations/{location}/meshes/{mesh}".format( - project=project, - location=location, - mesh=mesh, +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.NetworkServicesTransport, "_prep_wrapped_messages" + ) as prep: + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.NetworkServicesTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = NetworkServicesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", ) - actual = NetworkServicesClient.mesh_path(project, location, mesh) - assert expected == actual + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() -def test_parse_mesh_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "mesh": "abalone", - } - path = NetworkServicesClient.mesh_path(**expected) +def test_get_location_rest_bad_request( + transport: str = "rest", request_type=locations_pb2.GetLocationRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_mesh_path(path) - assert expected == actual + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) -def test_server_tls_policy_path(): - project = "squid" - location = "clam" - server_tls_policy = "whelk" - expected = "projects/{project}/locations/{location}/serverTlsPolicies/{server_tls_policy}".format( - project=project, - location=location, - server_tls_policy=server_tls_policy, + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - actual = NetworkServicesClient.server_tls_policy_path( - project, location, server_tls_policy + request_init = {"name": "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 = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + transport: str = "rest", request_type=locations_pb2.ListLocationsRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert expected == actual + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) -def test_parse_server_tls_policy_path(): - expected = { - "project": "octopus", - "location": "oyster", - "server_tls_policy": "nudibranch", + # 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_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1"} + 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 = locations_pb2.ListLocationsResponse() + + # 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.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/edgeCacheKeysets/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "resource": "projects/sample1/locations/sample2/edgeCacheKeysets/sample3" } - path = NetworkServicesClient.server_tls_policy_path(**expected) + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_server_tls_policy_path(path) - assert expected == actual + # 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 -def test_service_binding_path(): - project = "cuttlefish" - location = "mussel" - service_binding = "winkle" - expected = "projects/{project}/locations/{location}/serviceBindings/{service_binding}".format( - project=project, - location=location, - service_binding=service_binding, + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - actual = NetworkServicesClient.service_binding_path( - project, location, service_binding + + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/edgeCacheKeysets/sample3"}, + request, ) - assert expected == actual + # 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.set_iam_policy(request) -def test_parse_service_binding_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "service_binding": "abalone", + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "resource": "projects/sample1/locations/sample2/edgeCacheKeysets/sample3" } - path = NetworkServicesClient.service_binding_path(**expected) + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # 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.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_service_binding_path(path) - assert expected == actual +def test_test_iam_permissions_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_tcp_route_path(): - project = "squid" - location = "clam" - tcp_route = "whelk" - expected = "projects/{project}/locations/{location}/tcpRoutes/{tcp_route}".format( - project=project, - location=location, - tcp_route=tcp_route, + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/edgeCacheKeysets/sample3"}, + request, ) - actual = NetworkServicesClient.tcp_route_path(project, location, tcp_route) - assert expected == actual + # 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.test_iam_permissions(request) -def test_parse_tcp_route_path(): - expected = { - "project": "octopus", - "location": "oyster", - "tcp_route": "nudibranch", + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "resource": "projects/sample1/locations/sample2/edgeCacheKeysets/sample3" } - path = NetworkServicesClient.tcp_route_path(**expected) + 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 = iam_policy_pb2.TestIamPermissionsResponse() - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_tcp_route_path(path) - assert expected == actual + # 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 -def test_tls_route_path(): - project = "cuttlefish" - location = "mussel" - tls_route = "winkle" - expected = "projects/{project}/locations/{location}/tlsRoutes/{tls_route}".format( - project=project, - location=location, - tls_route=tls_route, - ) - actual = NetworkServicesClient.tls_route_path(project, location, tls_route) - assert expected == actual + response = client.test_iam_permissions(request) + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) -def test_parse_tls_route_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "tls_route": "abalone", - } - path = NetworkServicesClient.tls_route_path(**expected) - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_tls_route_path(path) - assert expected == actual +def test_cancel_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.CancelOperationRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - actual = NetworkServicesClient.common_billing_account_path(billing_account) - assert expected == actual + request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = NetworkServicesClient.common_billing_account_path(**expected) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_common_billing_account_path(path) - assert expected == actual + response = client.cancel_operation(request) + # Establish that the response is the type that we expect. + assert response is None -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format( - folder=folder, - ) - actual = NetworkServicesClient.common_folder_path(folder) - assert expected == actual +def test_delete_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = NetworkServicesClient.common_folder_path(**expected) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_common_folder_path(path) - assert expected == actual + # 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_operation(request) -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format( - organization=organization, +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - actual = NetworkServicesClient.common_organization_path(organization) - assert expected == actual + request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = NetworkServicesClient.common_organization_path(**expected) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_common_organization_path(path) - assert expected == actual + response = client.delete_operation(request) + # Establish that the response is the type that we expect. + assert response is None -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format( - project=project, - ) - actual = NetworkServicesClient.common_project_path(project) - assert expected == actual +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = NetworkServicesClient.common_project_path(**expected) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_common_project_path(path) - assert expected == actual + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - actual = NetworkServicesClient.common_location_path(project, location) - assert expected == actual + request_init = {"name": "projects/sample1/locations/sample2/operations/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() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = NetworkServicesClient.common_location_path(**expected) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that the path construction is reversible. - actual = NetworkServicesClient.parse_common_location_path(path) - assert expected == actual + response = client.get_operation(request) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object( - transports.NetworkServicesTransport, "_prep_wrapped_messages" - ) as prep: - client = NetworkServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) +def test_list_operations_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.ListOperationsRequest +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - with mock.patch.object( - transports.NetworkServicesTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = NetworkServicesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = NetworkServicesAsyncClient( + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = NetworkServicesClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport="rest", ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() + request_init = {"name": "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 = operations_pb2.ListOperationsResponse() + + # 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.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) def test_delete_operation(transport: str = "grpc"): @@ -14136,6 +27099,7 @@ async def test_test_iam_permissions_from_dict_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -14153,6 +27117,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: