diff --git a/packages/google-cloud-network-security/google/cloud/network_security/gapic_version.py b/packages/google-cloud-network-security/google/cloud/network_security/gapic_version.py index 1e693ef1b9bd..20a9cd975b02 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security/gapic_version.py +++ b/packages/google-cloud-network-security/google/cloud/network_security/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.9.20" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/gapic_version.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/gapic_version.py index 1e693ef1b9bd..20a9cd975b02 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/gapic_version.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.9.20" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1alpha1/gapic_version.py b/packages/google-cloud-network-security/google/cloud/network_security_v1alpha1/gapic_version.py index 1e693ef1b9bd..20a9cd975b02 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1alpha1/gapic_version.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1alpha1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.9.20" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/gapic_metadata.json b/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/gapic_metadata.json index 8bf9dacdd358..9b081e363ca2 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/gapic_metadata.json +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/gapic_metadata.json @@ -166,6 +166,86 @@ ] } } + }, + "rest": { + "libraryClient": "NetworkSecurityClient", + "rpcs": { + "CreateAuthorizationPolicy": { + "methods": [ + "create_authorization_policy" + ] + }, + "CreateClientTlsPolicy": { + "methods": [ + "create_client_tls_policy" + ] + }, + "CreateServerTlsPolicy": { + "methods": [ + "create_server_tls_policy" + ] + }, + "DeleteAuthorizationPolicy": { + "methods": [ + "delete_authorization_policy" + ] + }, + "DeleteClientTlsPolicy": { + "methods": [ + "delete_client_tls_policy" + ] + }, + "DeleteServerTlsPolicy": { + "methods": [ + "delete_server_tls_policy" + ] + }, + "GetAuthorizationPolicy": { + "methods": [ + "get_authorization_policy" + ] + }, + "GetClientTlsPolicy": { + "methods": [ + "get_client_tls_policy" + ] + }, + "GetServerTlsPolicy": { + "methods": [ + "get_server_tls_policy" + ] + }, + "ListAuthorizationPolicies": { + "methods": [ + "list_authorization_policies" + ] + }, + "ListClientTlsPolicies": { + "methods": [ + "list_client_tls_policies" + ] + }, + "ListServerTlsPolicies": { + "methods": [ + "list_server_tls_policies" + ] + }, + "UpdateAuthorizationPolicy": { + "methods": [ + "update_authorization_policy" + ] + }, + "UpdateClientTlsPolicy": { + "methods": [ + "update_client_tls_policy" + ] + }, + "UpdateServerTlsPolicy": { + "methods": [ + "update_server_tls_policy" + ] + } + } } } } diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/gapic_version.py b/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/gapic_version.py index 1e693ef1b9bd..20a9cd975b02 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/gapic_version.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.9.20" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/services/network_security/client.py b/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/services/network_security/client.py index 48e8ce50d9fa..893239518f61 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/services/network_security/client.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/services/network_security/client.py @@ -90,6 +90,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, NetworkSecurityTransport from .transports.grpc import NetworkSecurityGrpcTransport from .transports.grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport +from .transports.rest import NetworkSecurityRestTransport class NetworkSecurityClientMeta(type): @@ -105,6 +106,7 @@ class NetworkSecurityClientMeta(type): ) # type: Dict[str, Type[NetworkSecurityTransport]] _transport_registry["grpc"] = NetworkSecurityGrpcTransport _transport_registry["grpc_asyncio"] = NetworkSecurityGrpcAsyncIOTransport + _transport_registry["rest"] = NetworkSecurityRestTransport def get_transport_class( cls, diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/services/network_security/transports/__init__.py b/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/services/network_security/transports/__init__.py index ca6661097b03..674be4aacbc7 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/services/network_security/transports/__init__.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/services/network_security/transports/__init__.py @@ -19,14 +19,18 @@ from .base import NetworkSecurityTransport from .grpc import NetworkSecurityGrpcTransport from .grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport +from .rest import NetworkSecurityRestInterceptor, NetworkSecurityRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[NetworkSecurityTransport]] _transport_registry["grpc"] = NetworkSecurityGrpcTransport _transport_registry["grpc_asyncio"] = NetworkSecurityGrpcAsyncIOTransport +_transport_registry["rest"] = NetworkSecurityRestTransport __all__ = ( "NetworkSecurityTransport", "NetworkSecurityGrpcTransport", "NetworkSecurityGrpcAsyncIOTransport", + "NetworkSecurityRestTransport", + "NetworkSecurityRestInterceptor", ) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/services/network_security/transports/rest.py b/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/services/network_security/transports/rest.py index 4c309cd7e1a3..f4d42f4ab941 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/services/network_security/transports/rest.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/services/network_security/transports/rest.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,41 +13,25 @@ # 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 logging +from typing import Any, 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 gapic_v1, operations_v1, 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.longrunning import operations_pb2 # type: ignore +import google.protobuf 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_security_v1beta1.types import ( authorization_policy as gcn_authorization_policy, ) @@ -62,14 +46,31 @@ from google.cloud.network_security_v1beta1.types import server_tls_policy from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import NetworkSecurityTransport +from .rest_base import _BaseNetworkSecurityRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + class NetworkSecurityRestInterceptor: """Interceptor for NetworkSecurity. @@ -215,10 +216,10 @@ def post_update_server_tls_policy(self, response): def pre_create_authorization_policy( self, request: gcn_authorization_policy.CreateAuthorizationPolicyRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ gcn_authorization_policy.CreateAuthorizationPolicyRequest, - Sequence[Tuple[str, str]], + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for create_authorization_policy @@ -232,18 +233,42 @@ def post_create_authorization_policy( ) -> operations_pb2.Operation: """Post-rpc interceptor for create_authorization_policy - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_create_authorization_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the NetworkSecurity server but before - it is returned to user code. + it is returned to user code. This `post_create_authorization_policy` interceptor runs + before the `post_create_authorization_policy_with_metadata` interceptor. """ return response + def post_create_authorization_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_authorization_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_create_authorization_policy_with_metadata` + interceptor in new development instead of the `post_create_authorization_policy` interceptor. + When both interceptors are used, this `post_create_authorization_policy_with_metadata` interceptor runs after the + `post_create_authorization_policy` interceptor. The (possibly modified) response returned by + `post_create_authorization_policy` will be passed to + `post_create_authorization_policy_with_metadata`. + """ + return response, metadata + def pre_create_client_tls_policy( self, request: gcn_client_tls_policy.CreateClientTlsPolicyRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - gcn_client_tls_policy.CreateClientTlsPolicyRequest, Sequence[Tuple[str, str]] + gcn_client_tls_policy.CreateClientTlsPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for create_client_tls_policy @@ -257,18 +282,42 @@ def post_create_client_tls_policy( ) -> operations_pb2.Operation: """Post-rpc interceptor for create_client_tls_policy - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_create_client_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the NetworkSecurity server but before - it is returned to user code. + it is returned to user code. This `post_create_client_tls_policy` interceptor runs + before the `post_create_client_tls_policy_with_metadata` interceptor. """ return response + def post_create_client_tls_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_client_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_create_client_tls_policy_with_metadata` + interceptor in new development instead of the `post_create_client_tls_policy` interceptor. + When both interceptors are used, this `post_create_client_tls_policy_with_metadata` interceptor runs after the + `post_create_client_tls_policy` interceptor. The (possibly modified) response returned by + `post_create_client_tls_policy` will be passed to + `post_create_client_tls_policy_with_metadata`. + """ + return response, metadata + def pre_create_server_tls_policy( self, request: gcn_server_tls_policy.CreateServerTlsPolicyRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - gcn_server_tls_policy.CreateServerTlsPolicyRequest, Sequence[Tuple[str, str]] + gcn_server_tls_policy.CreateServerTlsPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for create_server_tls_policy @@ -282,18 +331,42 @@ def post_create_server_tls_policy( ) -> operations_pb2.Operation: """Post-rpc interceptor for create_server_tls_policy - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_create_server_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the NetworkSecurity server but before - it is returned to user code. + it is returned to user code. This `post_create_server_tls_policy` interceptor runs + before the `post_create_server_tls_policy_with_metadata` interceptor. """ return response + def post_create_server_tls_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_server_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_create_server_tls_policy_with_metadata` + interceptor in new development instead of the `post_create_server_tls_policy` interceptor. + When both interceptors are used, this `post_create_server_tls_policy_with_metadata` interceptor runs after the + `post_create_server_tls_policy` interceptor. The (possibly modified) response returned by + `post_create_server_tls_policy` will be passed to + `post_create_server_tls_policy_with_metadata`. + """ + return response, metadata + def pre_delete_authorization_policy( self, request: authorization_policy.DeleteAuthorizationPolicyRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - authorization_policy.DeleteAuthorizationPolicyRequest, Sequence[Tuple[str, str]] + authorization_policy.DeleteAuthorizationPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for delete_authorization_policy @@ -307,18 +380,42 @@ def post_delete_authorization_policy( ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_authorization_policy - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_delete_authorization_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the NetworkSecurity server but before - it is returned to user code. + it is returned to user code. This `post_delete_authorization_policy` interceptor runs + before the `post_delete_authorization_policy_with_metadata` interceptor. """ return response + def post_delete_authorization_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_authorization_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_delete_authorization_policy_with_metadata` + interceptor in new development instead of the `post_delete_authorization_policy` interceptor. + When both interceptors are used, this `post_delete_authorization_policy_with_metadata` interceptor runs after the + `post_delete_authorization_policy` interceptor. The (possibly modified) response returned by + `post_delete_authorization_policy` will be passed to + `post_delete_authorization_policy_with_metadata`. + """ + return response, metadata + def pre_delete_client_tls_policy( self, request: client_tls_policy.DeleteClientTlsPolicyRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - client_tls_policy.DeleteClientTlsPolicyRequest, Sequence[Tuple[str, str]] + client_tls_policy.DeleteClientTlsPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for delete_client_tls_policy @@ -332,18 +429,42 @@ def post_delete_client_tls_policy( ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_client_tls_policy - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_delete_client_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the NetworkSecurity server but before - it is returned to user code. + it is returned to user code. This `post_delete_client_tls_policy` interceptor runs + before the `post_delete_client_tls_policy_with_metadata` interceptor. """ return response + def post_delete_client_tls_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_client_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_delete_client_tls_policy_with_metadata` + interceptor in new development instead of the `post_delete_client_tls_policy` interceptor. + When both interceptors are used, this `post_delete_client_tls_policy_with_metadata` interceptor runs after the + `post_delete_client_tls_policy` interceptor. The (possibly modified) response returned by + `post_delete_client_tls_policy` will be passed to + `post_delete_client_tls_policy_with_metadata`. + """ + return response, metadata + def pre_delete_server_tls_policy( self, request: server_tls_policy.DeleteServerTlsPolicyRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - server_tls_policy.DeleteServerTlsPolicyRequest, Sequence[Tuple[str, str]] + server_tls_policy.DeleteServerTlsPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for delete_server_tls_policy @@ -357,18 +478,42 @@ def post_delete_server_tls_policy( ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_server_tls_policy - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_delete_server_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the NetworkSecurity server but before - it is returned to user code. + it is returned to user code. This `post_delete_server_tls_policy` interceptor runs + before the `post_delete_server_tls_policy_with_metadata` interceptor. """ return response + def post_delete_server_tls_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_server_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_delete_server_tls_policy_with_metadata` + interceptor in new development instead of the `post_delete_server_tls_policy` interceptor. + When both interceptors are used, this `post_delete_server_tls_policy_with_metadata` interceptor runs after the + `post_delete_server_tls_policy` interceptor. The (possibly modified) response returned by + `post_delete_server_tls_policy` will be passed to + `post_delete_server_tls_policy_with_metadata`. + """ + return response, metadata + def pre_get_authorization_policy( self, request: authorization_policy.GetAuthorizationPolicyRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - authorization_policy.GetAuthorizationPolicyRequest, Sequence[Tuple[str, str]] + authorization_policy.GetAuthorizationPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for get_authorization_policy @@ -382,17 +527,46 @@ def post_get_authorization_policy( ) -> authorization_policy.AuthorizationPolicy: """Post-rpc interceptor for get_authorization_policy - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_get_authorization_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the NetworkSecurity server but before - it is returned to user code. + it is returned to user code. This `post_get_authorization_policy` interceptor runs + before the `post_get_authorization_policy_with_metadata` interceptor. """ return response + def post_get_authorization_policy_with_metadata( + self, + response: authorization_policy.AuthorizationPolicy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + authorization_policy.AuthorizationPolicy, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_authorization_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_get_authorization_policy_with_metadata` + interceptor in new development instead of the `post_get_authorization_policy` interceptor. + When both interceptors are used, this `post_get_authorization_policy_with_metadata` interceptor runs after the + `post_get_authorization_policy` interceptor. The (possibly modified) response returned by + `post_get_authorization_policy` will be passed to + `post_get_authorization_policy_with_metadata`. + """ + return response, metadata + def pre_get_client_tls_policy( self, request: client_tls_policy.GetClientTlsPolicyRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[client_tls_policy.GetClientTlsPolicyRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + client_tls_policy.GetClientTlsPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_client_tls_policy Override in a subclass to manipulate the request or metadata @@ -405,17 +579,45 @@ def post_get_client_tls_policy( ) -> client_tls_policy.ClientTlsPolicy: """Post-rpc interceptor for get_client_tls_policy - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_get_client_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the NetworkSecurity server but before - it is returned to user code. + it is returned to user code. This `post_get_client_tls_policy` interceptor runs + before the `post_get_client_tls_policy_with_metadata` interceptor. """ return response + def post_get_client_tls_policy_with_metadata( + self, + response: client_tls_policy.ClientTlsPolicy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + client_tls_policy.ClientTlsPolicy, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_client_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_get_client_tls_policy_with_metadata` + interceptor in new development instead of the `post_get_client_tls_policy` interceptor. + When both interceptors are used, this `post_get_client_tls_policy_with_metadata` interceptor runs after the + `post_get_client_tls_policy` interceptor. The (possibly modified) response returned by + `post_get_client_tls_policy` will be passed to + `post_get_client_tls_policy_with_metadata`. + """ + return response, metadata + def pre_get_server_tls_policy( self, request: server_tls_policy.GetServerTlsPolicyRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[server_tls_policy.GetServerTlsPolicyRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + server_tls_policy.GetServerTlsPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_server_tls_policy Override in a subclass to manipulate the request or metadata @@ -428,18 +630,44 @@ def post_get_server_tls_policy( ) -> server_tls_policy.ServerTlsPolicy: """Post-rpc interceptor for get_server_tls_policy - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_get_server_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the NetworkSecurity server but before - it is returned to user code. + it is returned to user code. This `post_get_server_tls_policy` interceptor runs + before the `post_get_server_tls_policy_with_metadata` interceptor. """ return response + def post_get_server_tls_policy_with_metadata( + self, + response: server_tls_policy.ServerTlsPolicy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + server_tls_policy.ServerTlsPolicy, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_server_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_get_server_tls_policy_with_metadata` + interceptor in new development instead of the `post_get_server_tls_policy` interceptor. + When both interceptors are used, this `post_get_server_tls_policy_with_metadata` interceptor runs after the + `post_get_server_tls_policy` interceptor. The (possibly modified) response returned by + `post_get_server_tls_policy` will be passed to + `post_get_server_tls_policy_with_metadata`. + """ + return response, metadata + def pre_list_authorization_policies( self, request: authorization_policy.ListAuthorizationPoliciesRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - authorization_policy.ListAuthorizationPoliciesRequest, Sequence[Tuple[str, str]] + authorization_policy.ListAuthorizationPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for list_authorization_policies @@ -453,18 +681,45 @@ def post_list_authorization_policies( ) -> authorization_policy.ListAuthorizationPoliciesResponse: """Post-rpc interceptor for list_authorization_policies - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_authorization_policies_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the NetworkSecurity server but before - it is returned to user code. + it is returned to user code. This `post_list_authorization_policies` interceptor runs + before the `post_list_authorization_policies_with_metadata` interceptor. """ return response + def post_list_authorization_policies_with_metadata( + self, + response: authorization_policy.ListAuthorizationPoliciesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + authorization_policy.ListAuthorizationPoliciesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_authorization_policies + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_list_authorization_policies_with_metadata` + interceptor in new development instead of the `post_list_authorization_policies` interceptor. + When both interceptors are used, this `post_list_authorization_policies_with_metadata` interceptor runs after the + `post_list_authorization_policies` interceptor. The (possibly modified) response returned by + `post_list_authorization_policies` will be passed to + `post_list_authorization_policies_with_metadata`. + """ + return response, metadata + def pre_list_client_tls_policies( self, request: client_tls_policy.ListClientTlsPoliciesRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - client_tls_policy.ListClientTlsPoliciesRequest, Sequence[Tuple[str, str]] + client_tls_policy.ListClientTlsPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for list_client_tls_policies @@ -478,18 +733,45 @@ def post_list_client_tls_policies( ) -> client_tls_policy.ListClientTlsPoliciesResponse: """Post-rpc interceptor for list_client_tls_policies - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_client_tls_policies_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the NetworkSecurity server but before - it is returned to user code. + it is returned to user code. This `post_list_client_tls_policies` interceptor runs + before the `post_list_client_tls_policies_with_metadata` interceptor. """ return response + def post_list_client_tls_policies_with_metadata( + self, + response: client_tls_policy.ListClientTlsPoliciesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + client_tls_policy.ListClientTlsPoliciesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_client_tls_policies + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_list_client_tls_policies_with_metadata` + interceptor in new development instead of the `post_list_client_tls_policies` interceptor. + When both interceptors are used, this `post_list_client_tls_policies_with_metadata` interceptor runs after the + `post_list_client_tls_policies` interceptor. The (possibly modified) response returned by + `post_list_client_tls_policies` will be passed to + `post_list_client_tls_policies_with_metadata`. + """ + return response, metadata + def pre_list_server_tls_policies( self, request: server_tls_policy.ListServerTlsPoliciesRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - server_tls_policy.ListServerTlsPoliciesRequest, Sequence[Tuple[str, str]] + server_tls_policy.ListServerTlsPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for list_server_tls_policies @@ -503,19 +785,45 @@ def post_list_server_tls_policies( ) -> server_tls_policy.ListServerTlsPoliciesResponse: """Post-rpc interceptor for list_server_tls_policies - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_server_tls_policies_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the NetworkSecurity server but before - it is returned to user code. + it is returned to user code. This `post_list_server_tls_policies` interceptor runs + before the `post_list_server_tls_policies_with_metadata` interceptor. """ return response + def post_list_server_tls_policies_with_metadata( + self, + response: server_tls_policy.ListServerTlsPoliciesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + server_tls_policy.ListServerTlsPoliciesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_server_tls_policies + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_list_server_tls_policies_with_metadata` + interceptor in new development instead of the `post_list_server_tls_policies` interceptor. + When both interceptors are used, this `post_list_server_tls_policies_with_metadata` interceptor runs after the + `post_list_server_tls_policies` interceptor. The (possibly modified) response returned by + `post_list_server_tls_policies` will be passed to + `post_list_server_tls_policies_with_metadata`. + """ + return response, metadata + def pre_update_authorization_policy( self, request: gcn_authorization_policy.UpdateAuthorizationPolicyRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ gcn_authorization_policy.UpdateAuthorizationPolicyRequest, - Sequence[Tuple[str, str]], + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for update_authorization_policy @@ -529,18 +837,42 @@ def post_update_authorization_policy( ) -> operations_pb2.Operation: """Post-rpc interceptor for update_authorization_policy - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_update_authorization_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the NetworkSecurity server but before - it is returned to user code. + it is returned to user code. This `post_update_authorization_policy` interceptor runs + before the `post_update_authorization_policy_with_metadata` interceptor. """ return response + def post_update_authorization_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_authorization_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_update_authorization_policy_with_metadata` + interceptor in new development instead of the `post_update_authorization_policy` interceptor. + When both interceptors are used, this `post_update_authorization_policy_with_metadata` interceptor runs after the + `post_update_authorization_policy` interceptor. The (possibly modified) response returned by + `post_update_authorization_policy` will be passed to + `post_update_authorization_policy_with_metadata`. + """ + return response, metadata + def pre_update_client_tls_policy( self, request: gcn_client_tls_policy.UpdateClientTlsPolicyRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - gcn_client_tls_policy.UpdateClientTlsPolicyRequest, Sequence[Tuple[str, str]] + gcn_client_tls_policy.UpdateClientTlsPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for update_client_tls_policy @@ -554,18 +886,42 @@ def post_update_client_tls_policy( ) -> operations_pb2.Operation: """Post-rpc interceptor for update_client_tls_policy - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_update_client_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the NetworkSecurity server but before - it is returned to user code. + it is returned to user code. This `post_update_client_tls_policy` interceptor runs + before the `post_update_client_tls_policy_with_metadata` interceptor. """ return response + def post_update_client_tls_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_client_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_update_client_tls_policy_with_metadata` + interceptor in new development instead of the `post_update_client_tls_policy` interceptor. + When both interceptors are used, this `post_update_client_tls_policy_with_metadata` interceptor runs after the + `post_update_client_tls_policy` interceptor. The (possibly modified) response returned by + `post_update_client_tls_policy` will be passed to + `post_update_client_tls_policy_with_metadata`. + """ + return response, metadata + def pre_update_server_tls_policy( self, request: gcn_server_tls_policy.UpdateServerTlsPolicyRequest, - metadata: Sequence[Tuple[str, str]], + metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - gcn_server_tls_policy.UpdateServerTlsPolicyRequest, Sequence[Tuple[str, str]] + gcn_server_tls_policy.UpdateServerTlsPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Pre-rpc interceptor for update_server_tls_policy @@ -579,17 +935,42 @@ def post_update_server_tls_policy( ) -> operations_pb2.Operation: """Post-rpc interceptor for update_server_tls_policy - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_update_server_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the NetworkSecurity server but before - it is returned to user code. + it is returned to user code. This `post_update_server_tls_policy` interceptor runs + before the `post_update_server_tls_policy_with_metadata` interceptor. """ return response + def post_update_server_tls_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_server_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_update_server_tls_policy_with_metadata` + interceptor in new development instead of the `post_update_server_tls_policy` interceptor. + When both interceptors are used, this `post_update_server_tls_policy_with_metadata` interceptor runs after the + `post_update_server_tls_policy` interceptor. The (possibly modified) response returned by + `post_update_server_tls_policy` will be passed to + `post_update_server_tls_policy_with_metadata`. + """ + return response, metadata + def pre_get_location( self, request: locations_pb2.GetLocationRequest, - metadata: Sequence[Tuple[str, str]], - ) -> locations_pb2.Location: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_location Override in a subclass to manipulate the request or metadata @@ -598,7 +979,7 @@ def pre_get_location( return request, metadata def post_get_location( - self, response: locations_pb2.GetLocationRequest + self, response: locations_pb2.Location ) -> locations_pb2.Location: """Post-rpc interceptor for get_location @@ -611,8 +992,10 @@ def post_get_location( def pre_list_locations( self, request: locations_pb2.ListLocationsRequest, - metadata: Sequence[Tuple[str, str]], - ) -> locations_pb2.ListLocationsResponse: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_locations Override in a subclass to manipulate the request or metadata @@ -621,7 +1004,7 @@ def pre_list_locations( return request, metadata def post_list_locations( - self, response: locations_pb2.ListLocationsRequest + self, response: locations_pb2.ListLocationsResponse ) -> locations_pb2.ListLocationsResponse: """Post-rpc interceptor for list_locations @@ -634,8 +1017,10 @@ def post_list_locations( def pre_get_iam_policy( self, request: iam_policy_pb2.GetIamPolicyRequest, - metadata: Sequence[Tuple[str, str]], - ) -> policy_pb2.Policy: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_iam_policy Override in a subclass to manipulate the request or metadata @@ -643,9 +1028,7 @@ def pre_get_iam_policy( """ return request, metadata - def post_get_iam_policy( - self, response: iam_policy_pb2.GetIamPolicyRequest - ) -> policy_pb2.Policy: + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """Post-rpc interceptor for get_iam_policy Override in a subclass to manipulate the response @@ -657,8 +1040,10 @@ def post_get_iam_policy( def pre_set_iam_policy( self, request: iam_policy_pb2.SetIamPolicyRequest, - metadata: Sequence[Tuple[str, str]], - ) -> policy_pb2.Policy: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for set_iam_policy Override in a subclass to manipulate the request or metadata @@ -666,9 +1051,7 @@ def pre_set_iam_policy( """ return request, metadata - def post_set_iam_policy( - self, response: iam_policy_pb2.SetIamPolicyRequest - ) -> policy_pb2.Policy: + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """Post-rpc interceptor for set_iam_policy Override in a subclass to manipulate the response @@ -680,8 +1063,11 @@ def post_set_iam_policy( def pre_test_iam_permissions( self, request: iam_policy_pb2.TestIamPermissionsRequest, - metadata: Sequence[Tuple[str, str]], - ) -> iam_policy_pb2.TestIamPermissionsResponse: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for test_iam_permissions Override in a subclass to manipulate the request or metadata @@ -690,7 +1076,7 @@ def pre_test_iam_permissions( return request, metadata def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsRequest + self, response: iam_policy_pb2.TestIamPermissionsResponse ) -> iam_policy_pb2.TestIamPermissionsResponse: """Post-rpc interceptor for test_iam_permissions @@ -703,8 +1089,10 @@ def post_test_iam_permissions( def pre_cancel_operation( self, request: operations_pb2.CancelOperationRequest, - metadata: Sequence[Tuple[str, str]], - ) -> None: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for cancel_operation Override in a subclass to manipulate the request or metadata @@ -712,9 +1100,7 @@ def pre_cancel_operation( """ return request, metadata - def post_cancel_operation( - self, response: operations_pb2.CancelOperationRequest - ) -> None: + def post_cancel_operation(self, response: None) -> None: """Post-rpc interceptor for cancel_operation Override in a subclass to manipulate the response @@ -726,8 +1112,10 @@ def post_cancel_operation( def pre_delete_operation( self, request: operations_pb2.DeleteOperationRequest, - metadata: Sequence[Tuple[str, str]], - ) -> None: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_operation Override in a subclass to manipulate the request or metadata @@ -735,9 +1123,7 @@ def pre_delete_operation( """ return request, metadata - def post_delete_operation( - self, response: operations_pb2.DeleteOperationRequest - ) -> None: + def post_delete_operation(self, response: None) -> None: """Post-rpc interceptor for delete_operation Override in a subclass to manipulate the response @@ -749,8 +1135,10 @@ def post_delete_operation( def pre_get_operation( self, request: operations_pb2.GetOperationRequest, - metadata: Sequence[Tuple[str, str]], - ) -> operations_pb2.Operation: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_operation Override in a subclass to manipulate the request or metadata @@ -759,7 +1147,7 @@ def pre_get_operation( return request, metadata def post_get_operation( - self, response: operations_pb2.GetOperationRequest + self, response: operations_pb2.Operation ) -> operations_pb2.Operation: """Post-rpc interceptor for get_operation @@ -772,8 +1160,10 @@ def post_get_operation( def pre_list_operations( self, request: operations_pb2.ListOperationsRequest, - metadata: Sequence[Tuple[str, str]], - ) -> operations_pb2.ListOperationsResponse: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_operations Override in a subclass to manipulate the request or metadata @@ -782,7 +1172,7 @@ def pre_list_operations( return request, metadata def post_list_operations( - self, response: operations_pb2.ListOperationsRequest + self, response: operations_pb2.ListOperationsResponse ) -> operations_pb2.ListOperationsResponse: """Post-rpc interceptor for list_operations @@ -800,8 +1190,8 @@ class NetworkSecurityRestStub: _interceptor: NetworkSecurityRestInterceptor -class NetworkSecurityRestTransport(NetworkSecurityTransport): - """REST backend transport for NetworkSecurity. +class NetworkSecurityRestTransport(_BaseNetworkSecurityRestTransport): + """REST backend synchronous transport for NetworkSecurity. Network Security API provides resources to configure authentication and authorization policies. Refer to per API @@ -812,7 +1202,6 @@ class NetworkSecurityRestTransport(NetworkSecurityTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -834,16 +1223,17 @@ def __init__( Args: host (Optional[str]): - The hostname to connect to. + The hostname to connect to (default: 'networksecurity.googleapis.com'). 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 + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. 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 @@ -866,21 +1256,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -945,21 +1326,35 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateAuthorizationPolicy(NetworkSecurityRestStub): + class _CreateAuthorizationPolicy( + _BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy, + NetworkSecurityRestStub, + ): def __hash__(self): - return hash("CreateAuthorizationPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - "authorizationPolicyId": "", - } - - @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 - } + return hash("NetworkSecurityRestTransport.CreateAuthorizationPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -967,7 +1362,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the create authorization policy method over HTTP. @@ -976,12 +1371,13 @@ def __call__( request (~.gcn_authorization_policy.CreateAuthorizationPolicyRequest): The request object. Request used by the CreateAuthorizationPolicy 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -991,52 +1387,64 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{parent=projects/*/locations/*}/authorizationPolicies", - "body": "authorization_policy", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_create_authorization_policy( request, metadata ) - pb_request = gcn_authorization_policy.CreateAuthorizationPolicyRequest.pb( - request + transcoded_request = _BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy._get_transcoded_request( + http_options, 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, + body = _BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy._get_request_body_json( + transcoded_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 = _BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.CreateAuthorizationPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "CreateAuthorizationPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) # 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, + response = ( + NetworkSecurityRestTransport._CreateAuthorizationPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1047,24 +1455,64 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_authorization_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_authorization_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.create_authorization_policy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "CreateAuthorizationPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _CreateClientTlsPolicy(NetworkSecurityRestStub): + class _CreateClientTlsPolicy( + _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy, + NetworkSecurityRestStub, + ): def __hash__(self): - return hash("CreateClientTlsPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - "clientTlsPolicyId": "", - } - - @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 - } + return hash("NetworkSecurityRestTransport.CreateClientTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1072,7 +1520,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the create client tls policy method over HTTP. @@ -1080,12 +1528,13 @@ def __call__( request (~.gcn_client_tls_policy.CreateClientTlsPolicyRequest): The request object. Request used by the CreateClientTlsPolicy 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -1095,50 +1544,64 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{parent=projects/*/locations/*}/clientTlsPolicies", - "body": "client_tls_policy", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_create_client_tls_policy( request, metadata ) - pb_request = gcn_client_tls_policy.CreateClientTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, + body = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_request_body_json( + transcoded_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 = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.CreateClientTlsPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "CreateClientTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) # 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, + response = ( + NetworkSecurityRestTransport._CreateClientTlsPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1149,24 +1612,64 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_client_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_client_tls_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.create_client_tls_policy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "CreateClientTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _CreateServerTlsPolicy(NetworkSecurityRestStub): + class _CreateServerTlsPolicy( + _BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy, + NetworkSecurityRestStub, + ): def __hash__(self): - return hash("CreateServerTlsPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - "serverTlsPolicyId": "", - } - - @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 - } + return hash("NetworkSecurityRestTransport.CreateServerTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1174,7 +1677,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the create server tls policy method over HTTP. @@ -1182,12 +1685,13 @@ def __call__( request (~.gcn_server_tls_policy.CreateServerTlsPolicyRequest): The request object. Request used by the CreateServerTlsPolicy 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -1197,50 +1701,64 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{parent=projects/*/locations/*}/serverTlsPolicies", - "body": "server_tls_policy", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_create_server_tls_policy( request, metadata ) - pb_request = gcn_server_tls_policy.CreateServerTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, + body = _BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy._get_request_body_json( + transcoded_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 = _BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.CreateServerTlsPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "CreateServerTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) # 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, + response = ( + NetworkSecurityRestTransport._CreateServerTlsPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1251,22 +1769,63 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_server_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_server_tls_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.create_server_tls_policy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "CreateServerTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _DeleteAuthorizationPolicy(NetworkSecurityRestStub): + class _DeleteAuthorizationPolicy( + _BaseNetworkSecurityRestTransport._BaseDeleteAuthorizationPolicy, + NetworkSecurityRestStub, + ): def __hash__(self): - return hash("DeleteAuthorizationPolicy") - - __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 - } + return hash("NetworkSecurityRestTransport.DeleteAuthorizationPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1274,7 +1833,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the delete authorization policy method over HTTP. @@ -1283,12 +1842,13 @@ def __call__( request (~.authorization_policy.DeleteAuthorizationPolicyRequest): The request object. Request used by the DeleteAuthorizationPolicy 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -1298,43 +1858,59 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1beta1/{name=projects/*/locations/*/authorizationPolicies/*}", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseDeleteAuthorizationPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_authorization_policy( request, metadata ) - pb_request = authorization_policy.DeleteAuthorizationPolicyRequest.pb( - request + transcoded_request = _BaseNetworkSecurityRestTransport._BaseDeleteAuthorizationPolicy._get_transcoded_request( + http_options, 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 = _BaseNetworkSecurityRestTransport._BaseDeleteAuthorizationPolicy._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.DeleteAuthorizationPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "DeleteAuthorizationPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) # 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), + response = ( + NetworkSecurityRestTransport._DeleteAuthorizationPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1345,22 +1921,63 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_authorization_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_authorization_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.delete_authorization_policy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "DeleteAuthorizationPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _DeleteClientTlsPolicy(NetworkSecurityRestStub): + class _DeleteClientTlsPolicy( + _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy, + NetworkSecurityRestStub, + ): def __hash__(self): - return hash("DeleteClientTlsPolicy") - - __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 - } + return hash("NetworkSecurityRestTransport.DeleteClientTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1368,7 +1985,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the delete client tls policy method over HTTP. @@ -1376,12 +1993,13 @@ def __call__( request (~.client_tls_policy.DeleteClientTlsPolicyRequest): The request object. Request used by the DeleteClientTlsPolicy 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -1391,41 +2009,59 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1beta1/{name=projects/*/locations/*/clientTlsPolicies/*}", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_client_tls_policy( request, metadata ) - pb_request = client_tls_policy.DeleteClientTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_transcoded_request( + http_options, request + ) # 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 = _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.DeleteClientTlsPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "DeleteClientTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) # 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), + response = ( + NetworkSecurityRestTransport._DeleteClientTlsPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1436,22 +2072,63 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_client_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_client_tls_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.delete_client_tls_policy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "DeleteClientTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _DeleteServerTlsPolicy(NetworkSecurityRestStub): + class _DeleteServerTlsPolicy( + _BaseNetworkSecurityRestTransport._BaseDeleteServerTlsPolicy, + NetworkSecurityRestStub, + ): def __hash__(self): - return hash("DeleteServerTlsPolicy") - - __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 - } + return hash("NetworkSecurityRestTransport.DeleteServerTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1459,7 +2136,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the delete server tls policy method over HTTP. @@ -1467,12 +2144,13 @@ def __call__( request (~.server_tls_policy.DeleteServerTlsPolicyRequest): The request object. Request used by the DeleteServerTlsPolicy 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -1482,41 +2160,59 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1beta1/{name=projects/*/locations/*/serverTlsPolicies/*}", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseDeleteServerTlsPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_server_tls_policy( request, metadata ) - pb_request = server_tls_policy.DeleteServerTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseNetworkSecurityRestTransport._BaseDeleteServerTlsPolicy._get_transcoded_request( + http_options, request + ) # 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 = _BaseNetworkSecurityRestTransport._BaseDeleteServerTlsPolicy._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.DeleteServerTlsPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "DeleteServerTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) # 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), + response = ( + NetworkSecurityRestTransport._DeleteServerTlsPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1527,22 +2223,63 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_server_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_server_tls_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.delete_server_tls_policy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "DeleteServerTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _GetAuthorizationPolicy(NetworkSecurityRestStub): + class _GetAuthorizationPolicy( + _BaseNetworkSecurityRestTransport._BaseGetAuthorizationPolicy, + NetworkSecurityRestStub, + ): def __hash__(self): - return hash("GetAuthorizationPolicy") - - __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 - } + return hash("NetworkSecurityRestTransport.GetAuthorizationPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1550,7 +2287,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> authorization_policy.AuthorizationPolicy: r"""Call the get authorization policy method over HTTP. @@ -1558,12 +2295,13 @@ def __call__( request (~.authorization_policy.GetAuthorizationPolicyRequest): The request object. Request used by the GetAuthorizationPolicy 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.authorization_policy.AuthorizationPolicy: @@ -1577,41 +2315,59 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/authorizationPolicies/*}", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseGetAuthorizationPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_get_authorization_policy( request, metadata ) - pb_request = authorization_policy.GetAuthorizationPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetAuthorizationPolicy._get_transcoded_request( + http_options, request + ) # 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 = _BaseNetworkSecurityRestTransport._BaseGetAuthorizationPolicy._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.GetAuthorizationPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "GetAuthorizationPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) # 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), + response = ( + NetworkSecurityRestTransport._GetAuthorizationPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1624,22 +2380,65 @@ def __call__( pb_resp = authorization_policy.AuthorizationPolicy.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_authorization_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_authorization_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = authorization_policy.AuthorizationPolicy.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.get_authorization_policy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "GetAuthorizationPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _GetClientTlsPolicy(NetworkSecurityRestStub): + class _GetClientTlsPolicy( + _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy, + NetworkSecurityRestStub, + ): def __hash__(self): - return hash("GetClientTlsPolicy") - - __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 - } + return hash("NetworkSecurityRestTransport.GetClientTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1647,7 +2446,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> client_tls_policy.ClientTlsPolicy: r"""Call the get client tls policy method over HTTP. @@ -1655,12 +2454,13 @@ def __call__( request (~.client_tls_policy.GetClientTlsPolicyRequest): The request object. Request used by the GetClientTlsPolicy 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.client_tls_policy.ClientTlsPolicy: @@ -1673,41 +2473,57 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/clientTlsPolicies/*}", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_get_client_tls_policy( request, metadata ) - pb_request = client_tls_policy.GetClientTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_transcoded_request( + http_options, request + ) # 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 = _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.GetClientTlsPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "GetClientTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) # 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), + response = NetworkSecurityRestTransport._GetClientTlsPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1720,22 +2536,65 @@ def __call__( pb_resp = client_tls_policy.ClientTlsPolicy.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_client_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_client_tls_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = client_tls_policy.ClientTlsPolicy.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.get_client_tls_policy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "GetClientTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _GetServerTlsPolicy(NetworkSecurityRestStub): + class _GetServerTlsPolicy( + _BaseNetworkSecurityRestTransport._BaseGetServerTlsPolicy, + NetworkSecurityRestStub, + ): def __hash__(self): - return hash("GetServerTlsPolicy") - - __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 - } + return hash("NetworkSecurityRestTransport.GetServerTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1743,7 +2602,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> server_tls_policy.ServerTlsPolicy: r"""Call the get server tls policy method over HTTP. @@ -1751,12 +2610,13 @@ def __call__( request (~.server_tls_policy.GetServerTlsPolicyRequest): The request object. Request used by the GetServerTlsPolicy 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.server_tls_policy.ServerTlsPolicy: @@ -1770,41 +2630,57 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/serverTlsPolicies/*}", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseGetServerTlsPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_get_server_tls_policy( request, metadata ) - pb_request = server_tls_policy.GetServerTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetServerTlsPolicy._get_transcoded_request( + http_options, request + ) # 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 = _BaseNetworkSecurityRestTransport._BaseGetServerTlsPolicy._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.GetServerTlsPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "GetServerTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) # 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), + response = NetworkSecurityRestTransport._GetServerTlsPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1817,22 +2693,65 @@ def __call__( pb_resp = server_tls_policy.ServerTlsPolicy.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_server_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_server_tls_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = server_tls_policy.ServerTlsPolicy.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.get_server_tls_policy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "GetServerTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _ListAuthorizationPolicies(NetworkSecurityRestStub): + class _ListAuthorizationPolicies( + _BaseNetworkSecurityRestTransport._BaseListAuthorizationPolicies, + NetworkSecurityRestStub, + ): def __hash__(self): - return hash("ListAuthorizationPolicies") - - __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 - } + return hash("NetworkSecurityRestTransport.ListAuthorizationPolicies") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1840,7 +2759,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> authorization_policy.ListAuthorizationPoliciesResponse: r"""Call the list authorization policies method over HTTP. @@ -1849,12 +2768,13 @@ def __call__( request (~.authorization_policy.ListAuthorizationPoliciesRequest): The request object. Request used with the ListAuthorizationPolicies 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.authorization_policy.ListAuthorizationPoliciesResponse: @@ -1863,43 +2783,59 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{parent=projects/*/locations/*}/authorizationPolicies", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseListAuthorizationPolicies._get_http_options() + ) + request, metadata = self._interceptor.pre_list_authorization_policies( request, metadata ) - pb_request = authorization_policy.ListAuthorizationPoliciesRequest.pb( - request + transcoded_request = _BaseNetworkSecurityRestTransport._BaseListAuthorizationPolicies._get_transcoded_request( + http_options, 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 = _BaseNetworkSecurityRestTransport._BaseListAuthorizationPolicies._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.ListAuthorizationPolicies", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "ListAuthorizationPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) # 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), + response = ( + NetworkSecurityRestTransport._ListAuthorizationPolicies._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1912,22 +2848,67 @@ def __call__( pb_resp = authorization_policy.ListAuthorizationPoliciesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_authorization_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_authorization_policies_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + authorization_policy.ListAuthorizationPoliciesResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.list_authorization_policies", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "ListAuthorizationPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _ListClientTlsPolicies(NetworkSecurityRestStub): + class _ListClientTlsPolicies( + _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies, + NetworkSecurityRestStub, + ): def __hash__(self): - return hash("ListClientTlsPolicies") - - __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 - } + return hash("NetworkSecurityRestTransport.ListClientTlsPolicies") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1935,7 +2916,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> client_tls_policy.ListClientTlsPoliciesResponse: r"""Call the list client tls policies method over HTTP. @@ -1943,12 +2924,13 @@ def __call__( request (~.client_tls_policy.ListClientTlsPoliciesRequest): The request object. Request used by the ListClientTlsPolicies 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.client_tls_policy.ListClientTlsPoliciesResponse: @@ -1957,41 +2939,59 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{parent=projects/*/locations/*}/clientTlsPolicies", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_http_options() + ) + request, metadata = self._interceptor.pre_list_client_tls_policies( request, metadata ) - pb_request = client_tls_policy.ListClientTlsPoliciesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_transcoded_request( + http_options, request + ) # 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 = _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.ListClientTlsPolicies", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "ListClientTlsPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) # 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), + response = ( + NetworkSecurityRestTransport._ListClientTlsPolicies._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2004,22 +3004,67 @@ def __call__( pb_resp = client_tls_policy.ListClientTlsPoliciesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_client_tls_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_client_tls_policies_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + client_tls_policy.ListClientTlsPoliciesResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.list_client_tls_policies", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "ListClientTlsPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _ListServerTlsPolicies(NetworkSecurityRestStub): + class _ListServerTlsPolicies( + _BaseNetworkSecurityRestTransport._BaseListServerTlsPolicies, + NetworkSecurityRestStub, + ): def __hash__(self): - return hash("ListServerTlsPolicies") - - __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 - } + return hash("NetworkSecurityRestTransport.ListServerTlsPolicies") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -2027,7 +3072,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> server_tls_policy.ListServerTlsPoliciesResponse: r"""Call the list server tls policies method over HTTP. @@ -2035,12 +3080,13 @@ def __call__( request (~.server_tls_policy.ListServerTlsPoliciesRequest): The request object. Request used by the ListServerTlsPolicies 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.server_tls_policy.ListServerTlsPoliciesResponse: @@ -2049,41 +3095,59 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{parent=projects/*/locations/*}/serverTlsPolicies", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseListServerTlsPolicies._get_http_options() + ) + request, metadata = self._interceptor.pre_list_server_tls_policies( request, metadata ) - pb_request = server_tls_policy.ListServerTlsPoliciesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseNetworkSecurityRestTransport._BaseListServerTlsPolicies._get_transcoded_request( + http_options, request + ) # 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 = _BaseNetworkSecurityRestTransport._BaseListServerTlsPolicies._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.ListServerTlsPolicies", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "ListServerTlsPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) # 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), + response = ( + NetworkSecurityRestTransport._ListServerTlsPolicies._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2096,22 +3160,68 @@ def __call__( pb_resp = server_tls_policy.ListServerTlsPoliciesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_server_tls_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_server_tls_policies_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + server_tls_policy.ListServerTlsPoliciesResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.list_server_tls_policies", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "ListServerTlsPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _UpdateAuthorizationPolicy(NetworkSecurityRestStub): + class _UpdateAuthorizationPolicy( + _BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy, + NetworkSecurityRestStub, + ): def __hash__(self): - return hash("UpdateAuthorizationPolicy") - - __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 - } + return hash("NetworkSecurityRestTransport.UpdateAuthorizationPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -2119,7 +3229,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the update authorization policy method over HTTP. @@ -2128,12 +3238,13 @@ def __call__( request (~.gcn_authorization_policy.UpdateAuthorizationPolicyRequest): The request object. Request used by the UpdateAuthorizationPolicy 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -2143,52 +3254,64 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1beta1/{authorization_policy.name=projects/*/locations/*/authorizationPolicies/*}", - "body": "authorization_policy", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_update_authorization_policy( request, metadata ) - pb_request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest.pb( - request + transcoded_request = _BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy._get_transcoded_request( + http_options, 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, + body = _BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy._get_request_body_json( + transcoded_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 = _BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.UpdateAuthorizationPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "UpdateAuthorizationPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) # 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, + response = ( + NetworkSecurityRestTransport._UpdateAuthorizationPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2199,22 +3322,64 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_authorization_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_authorization_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.update_authorization_policy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "UpdateAuthorizationPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _UpdateClientTlsPolicy(NetworkSecurityRestStub): + class _UpdateClientTlsPolicy( + _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy, + NetworkSecurityRestStub, + ): def __hash__(self): - return hash("UpdateClientTlsPolicy") - - __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 - } + return hash("NetworkSecurityRestTransport.UpdateClientTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -2222,7 +3387,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the update client tls policy method over HTTP. @@ -2230,12 +3395,13 @@ def __call__( request (~.gcn_client_tls_policy.UpdateClientTlsPolicyRequest): The request object. Request used by UpdateClientTlsPolicy 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -2245,50 +3411,64 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1beta1/{client_tls_policy.name=projects/*/locations/*/clientTlsPolicies/*}", - "body": "client_tls_policy", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_update_client_tls_policy( request, metadata ) - pb_request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, + body = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_request_body_json( + transcoded_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 = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.UpdateClientTlsPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "UpdateClientTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) # 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, + response = ( + NetworkSecurityRestTransport._UpdateClientTlsPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2299,22 +3479,64 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_client_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_client_tls_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.update_client_tls_policy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "UpdateClientTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp - class _UpdateServerTlsPolicy(NetworkSecurityRestStub): + class _UpdateServerTlsPolicy( + _BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy, + NetworkSecurityRestStub, + ): def __hash__(self): - return hash("UpdateServerTlsPolicy") - - __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 - } + return hash("NetworkSecurityRestTransport.UpdateServerTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -2322,7 +3544,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the update server tls policy method over HTTP. @@ -2330,12 +3552,13 @@ def __call__( request (~.gcn_server_tls_policy.UpdateServerTlsPolicyRequest): The request object. Request used by UpdateServerTlsPolicy 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -2345,50 +3568,64 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1beta1/{server_tls_policy.name=projects/*/locations/*/serverTlsPolicies/*}", - "body": "server_tls_policy", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_update_server_tls_policy( request, metadata ) - pb_request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, + body = _BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy._get_request_body_json( + transcoded_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 = _BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.UpdateServerTlsPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "UpdateServerTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) # 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, + response = ( + NetworkSecurityRestTransport._UpdateServerTlsPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2399,7 +3636,33 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_server_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_server_tls_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.update_server_tls_policy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "UpdateServerTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property @@ -2563,14 +3826,41 @@ def update_server_tls_policy( def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(NetworkSecurityRestStub): + class _GetLocation( + _BaseNetworkSecurityRestTransport._BaseGetLocation, NetworkSecurityRestStub + ): + def __hash__(self): + return hash("NetworkSecurityRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.GetLocationRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> locations_pb2.Location: r"""Call the get location method over HTTP. @@ -2580,39 +3870,64 @@ def __call__( 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: locations_pb2.Location: Response from GetLocation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*}", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseGetLocation._get_http_options() + ) 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"] + transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseNetworkSecurityRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.GetLocation", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) - 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), + # Send the request + response = NetworkSecurityRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2620,23 +3935,72 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) return resp @property def list_locations(self): return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(NetworkSecurityRestStub): + class _ListLocations( + _BaseNetworkSecurityRestTransport._BaseListLocations, NetworkSecurityRestStub + ): + def __hash__(self): + return hash("NetworkSecurityRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.ListLocationsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> locations_pb2.ListLocationsResponse: r"""Call the list locations method over HTTP. @@ -2646,39 +4010,64 @@ def __call__( 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*}/locations", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseListLocations._get_http_options() + ) 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"] + transcoded_request = _BaseNetworkSecurityRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseNetworkSecurityRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.ListLocations", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) - 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), + # Send the request + response = NetworkSecurityRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2686,23 +4075,72 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) return resp @property def get_iam_policy(self): return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - class _GetIamPolicy(NetworkSecurityRestStub): + class _GetIamPolicy( + _BaseNetworkSecurityRestTransport._BaseGetIamPolicy, NetworkSecurityRestStub + ): + def __hash__(self): + return hash("NetworkSecurityRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: iam_policy_pb2.GetIamPolicyRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Call the get iam policy method over HTTP. @@ -2712,47 +4150,64 @@ def __call__( 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: policy_pb2.Policy: Response from GetIamPolicy method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy", - }, - { - "method": "get", - "uri": "/v1beta1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy", - }, - { - "method": "get", - "uri": "/v1beta1/{resource=projects/*/locations/*/clientTlsPolicies/*}:getIamPolicy", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseGetIamPolicy._get_http_options() + ) 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"] + transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseNetworkSecurityRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request + ) - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) - 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), + # Send the request + response = NetworkSecurityRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2760,23 +4215,73 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityAsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) return resp @property def set_iam_policy(self): return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - class _SetIamPolicy(NetworkSecurityRestStub): + class _SetIamPolicy( + _BaseNetworkSecurityRestTransport._BaseSetIamPolicy, NetworkSecurityRestStub + ): + def __hash__(self): + return hash("NetworkSecurityRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + def __call__( self, request: iam_policy_pb2.SetIamPolicyRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Call the set iam policy method over HTTP. @@ -2786,52 +4291,69 @@ def __call__( 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: policy_pb2.Policy: Response from SetIamPolicy method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy", - "body": "*", - }, - { - "method": "post", - "uri": "/v1beta1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy", - "body": "*", - }, - { - "method": "post", - "uri": "/v1beta1/{resource=projects/*/locations/*/clientTlsPolicies/*}:setIamPolicy", - "body": "*", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_http_options() + ) 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) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) - body = json.loads(json.dumps(transcoded_request["body"])) - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request + ) - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) - 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, + # Send the request + response = NetworkSecurityRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2839,23 +4361,74 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityAsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) return resp @property def test_iam_permissions(self): return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - class _TestIamPermissions(NetworkSecurityRestStub): + class _TestIamPermissions( + _BaseNetworkSecurityRestTransport._BaseTestIamPermissions, + NetworkSecurityRestStub, + ): + def __hash__(self): + return hash("NetworkSecurityRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + def __call__( self, request: iam_policy_pb2.TestIamPermissionsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Call the test iam permissions method over HTTP. @@ -2865,54 +4438,71 @@ def __call__( 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", - "body": "*", - }, - { - "method": "post", - "uri": "/v1beta1/{resource=projects/*/locations/*/serverTlsPolicies/*}:testIamPermissions", - "body": "*", - }, - { - "method": "post", - "uri": "/v1beta1/{resource=projects/*/locations/*/clientTlsPolicies/*}:testIamPermissions", - "body": "*", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_http_options() + ) 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) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) - body = json.loads(json.dumps(transcoded_request["body"])) - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request + ) - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) - 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, + # Send the request + response = NetworkSecurityRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2920,23 +4510,73 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityAsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) return resp @property def cancel_operation(self): return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - class _CancelOperation(NetworkSecurityRestStub): + class _CancelOperation( + _BaseNetworkSecurityRestTransport._BaseCancelOperation, NetworkSecurityRestStub + ): + def __hash__(self): + return hash("NetworkSecurityRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + def __call__( self, request: operations_pb2.CancelOperationRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Call the cancel operation method over HTTP. @@ -2946,41 +4586,68 @@ def __call__( 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}:cancel", - "body": "*", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_http_options() + ) request, metadata = self._interceptor.pre_cancel_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) - body = json.loads(json.dumps(transcoded_request["body"])) - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.CancelOperation", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) - 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, + # Send the request + response = NetworkSecurityRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2994,14 +4661,41 @@ def __call__( def delete_operation(self): return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(NetworkSecurityRestStub): + class _DeleteOperation( + _BaseNetworkSecurityRestTransport._BaseDeleteOperation, NetworkSecurityRestStub + ): + def __hash__(self): + return hash("NetworkSecurityRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.DeleteOperationRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: r"""Call the delete operation method over HTTP. @@ -3011,38 +4705,63 @@ def __call__( 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseDeleteOperation._get_http_options() + ) 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"] + transcoded_request = _BaseNetworkSecurityRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseNetworkSecurityRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) - 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), + # Send the request + response = NetworkSecurityRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3056,14 +4775,41 @@ def __call__( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(NetworkSecurityRestStub): + class _GetOperation( + _BaseNetworkSecurityRestTransport._BaseGetOperation, NetworkSecurityRestStub + ): + def __hash__(self): + return hash("NetworkSecurityRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the get operation method over HTTP. @@ -3073,39 +4819,64 @@ def __call__( 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseGetOperation._get_http_options() + ) 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"] + transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseNetworkSecurityRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.GetOperation", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) - 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), + # Send the request + response = NetworkSecurityRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3113,23 +4884,72 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) return resp @property def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(NetworkSecurityRestStub): + class _ListOperations( + _BaseNetworkSecurityRestTransport._BaseListOperations, NetworkSecurityRestStub + ): + def __hash__(self): + return hash("NetworkSecurityRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.ListOperationsResponse: r"""Call the list operations method over HTTP. @@ -3139,39 +4959,64 @@ def __call__( 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*}/operations", - }, - ] + http_options = ( + _BaseNetworkSecurityRestTransport._BaseListOperations._get_http_options() + ) 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"] + transcoded_request = _BaseNetworkSecurityRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseNetworkSecurityRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1beta1.NetworkSecurityClient.ListOperations", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) - 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), + # Send the request + response = NetworkSecurityRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3179,9 +5024,31 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1beta1.NetworkSecurityAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) return resp @property diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/services/network_security/transports/rest_base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/services/network_security/transports/rest_base.py new file mode 100644 index 000000000000..4ac12a4df1cf --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/services/network_security/transports/rest_base.py @@ -0,0 +1,1156 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +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 # type: ignore +from google.protobuf import json_format + +from google.cloud.network_security_v1beta1.types import ( + authorization_policy as gcn_authorization_policy, +) +from google.cloud.network_security_v1beta1.types import ( + client_tls_policy as gcn_client_tls_policy, +) +from google.cloud.network_security_v1beta1.types import ( + server_tls_policy as gcn_server_tls_policy, +) +from google.cloud.network_security_v1beta1.types import authorization_policy +from google.cloud.network_security_v1beta1.types import client_tls_policy +from google.cloud.network_security_v1beta1.types import server_tls_policy + +from .base import DEFAULT_CLIENT_INFO, NetworkSecurityTransport + + +class _BaseNetworkSecurityRestTransport(NetworkSecurityTransport): + """Base REST backend transport for NetworkSecurity. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 = "networksecurity.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + credentials (Optional[Any]): 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. + 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 + 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, + ) + + class _BaseCreateAuthorizationPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "authorizationPolicyId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*}/authorizationPolicies", + "body": "authorization_policy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_authorization_policy.CreateAuthorizationPolicyRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateClientTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "clientTlsPolicyId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*}/clientTlsPolicies", + "body": "client_tls_policy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_client_tls_policy.CreateClientTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateServerTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "serverTlsPolicyId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*}/serverTlsPolicies", + "body": "server_tls_policy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_server_tls_policy.CreateServerTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteAuthorizationPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/authorizationPolicies/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = authorization_policy.DeleteAuthorizationPolicyRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseNetworkSecurityRestTransport._BaseDeleteAuthorizationPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteClientTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/clientTlsPolicies/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = client_tls_policy.DeleteClientTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteServerTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/serverTlsPolicies/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = server_tls_policy.DeleteServerTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseNetworkSecurityRestTransport._BaseDeleteServerTlsPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAuthorizationPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/authorizationPolicies/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = authorization_policy.GetAuthorizationPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseNetworkSecurityRestTransport._BaseGetAuthorizationPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetClientTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/clientTlsPolicies/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = client_tls_policy.GetClientTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetServerTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/serverTlsPolicies/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = server_tls_policy.GetServerTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseNetworkSecurityRestTransport._BaseGetServerTlsPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAuthorizationPolicies: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*}/authorizationPolicies", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = authorization_policy.ListAuthorizationPoliciesRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseNetworkSecurityRestTransport._BaseListAuthorizationPolicies._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListClientTlsPolicies: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*}/clientTlsPolicies", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = client_tls_policy.ListClientTlsPoliciesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListServerTlsPolicies: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*}/serverTlsPolicies", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = server_tls_policy.ListServerTlsPoliciesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseNetworkSecurityRestTransport._BaseListServerTlsPolicies._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAuthorizationPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{authorization_policy.name=projects/*/locations/*/authorizationPolicies/*}", + "body": "authorization_policy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateClientTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{client_tls_policy.name=projects/*/locations/*/clientTlsPolicies/*}", + "body": "client_tls_policy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateServerTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{server_tls_policy.name=projects/*/locations/*/serverTlsPolicies/*}", + "body": "server_tls_policy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1beta1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1beta1/{resource=projects/*/locations/*/clientTlsPolicies/*}:getIamPolicy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/locations/*/clientTlsPolicies/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/locations/*/serverTlsPolicies/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/locations/*/clientTlsPolicies/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseNetworkSecurityRestTransport",) diff --git a/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json b/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json index a48ffde1ba20..715864820471 100644 --- a/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json +++ b/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-network-security", - "version": "0.9.20" + "version": "0.0.0" }, "snippets": [ { diff --git a/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1alpha1.json b/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1alpha1.json index 87d77d9e4627..5cb7c37fe1ee 100644 --- a/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1alpha1.json +++ b/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1alpha1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-network-security", - "version": "0.9.20" + "version": "0.0.0" }, "snippets": [ { diff --git a/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json b/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json index d448a83233fb..bfe107cb214c 100644 --- a/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json +++ b/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-network-security", - "version": "0.9.20" + "version": "0.0.0" }, "snippets": [ { diff --git a/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1beta1/test_network_security.py b/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1beta1/test_network_security.py index 6769d7f2fa90..98ba15c4f5a1 100644 --- a/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1beta1/test_network_security.py +++ b/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1beta1/test_network_security.py @@ -22,15 +22,19 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import AsyncIterable, Iterable import json import math from google.api_core import api_core_version +from google.protobuf import json_format 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 try: from google.auth.aio import credentials as ga_credentials_async @@ -399,6 +403,7 @@ def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): [ (NetworkSecurityClient, "grpc"), (NetworkSecurityAsyncClient, "grpc_asyncio"), + (NetworkSecurityClient, "rest"), ], ) def test_network_security_client_from_service_account_info( @@ -414,7 +419,11 @@ def test_network_security_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("networksecurity.googleapis.com:443") + assert client.transport._host == ( + "networksecurity.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com" + ) @pytest.mark.parametrize( @@ -422,6 +431,7 @@ def test_network_security_client_from_service_account_info( [ (transports.NetworkSecurityGrpcTransport, "grpc"), (transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.NetworkSecurityRestTransport, "rest"), ], ) def test_network_security_client_service_account_always_use_jwt( @@ -447,6 +457,7 @@ def test_network_security_client_service_account_always_use_jwt( [ (NetworkSecurityClient, "grpc"), (NetworkSecurityAsyncClient, "grpc_asyncio"), + (NetworkSecurityClient, "rest"), ], ) def test_network_security_client_from_service_account_file( @@ -469,13 +480,18 @@ def test_network_security_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("networksecurity.googleapis.com:443") + assert client.transport._host == ( + "networksecurity.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com" + ) def test_network_security_client_get_transport_class(): transport = NetworkSecurityClient.get_transport_class() available_transports = [ transports.NetworkSecurityGrpcTransport, + transports.NetworkSecurityRestTransport, ] assert transport in available_transports @@ -492,6 +508,7 @@ def test_network_security_client_get_transport_class(): transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", ), + (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest"), ], ) @mock.patch.object( @@ -661,6 +678,18 @@ def test_network_security_client_client_options( "grpc_asyncio", "false", ), + ( + NetworkSecurityClient, + transports.NetworkSecurityRestTransport, + "rest", + "true", + ), + ( + NetworkSecurityClient, + transports.NetworkSecurityRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -975,6 +1004,7 @@ def test_network_security_client_client_api_endpoint(client_class): transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", ), + (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest"), ], ) def test_network_security_client_client_options_scopes( @@ -1017,6 +1047,7 @@ def test_network_security_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest", None), ], ) def test_network_security_client_client_options_credentials_file( @@ -7060,490 +7091,7115 @@ async def test_delete_client_tls_policy_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): +def test_list_authorization_policies_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = NetworkSecurityClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NetworkSecurityClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + transport="rest", ) - # It is an error to provide an api_key and a transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = NetworkSecurityClient( - client_options=options, - transport=transport, - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = NetworkSecurityClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + # Ensure method has been cached + assert ( + client._transport.list_authorization_policies + in client._transport._wrapped_methods ) - # It is an error to provide scopes and a transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NetworkSecurityClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client._transport._wrapped_methods[ + client._transport.list_authorization_policies + ] = mock_rpc + request = {} + client.list_authorization_policies(request) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = NetworkSecurityClient(transport=transport) - assert client.transport is transport + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.list_authorization_policies(request) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - transport = transports.NetworkSecurityGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel +def test_list_authorization_policies_rest_required_fields( + request_type=authorization_policy.ListAuthorizationPoliciesRequest, +): + transport_class = transports.NetworkSecurityRestTransport -@pytest.mark.parametrize( - "transport_class", - [ - transports.NetworkSecurityGrpcTransport, - transports.NetworkSecurityGrpcAsyncIOTransport, - ], -) -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() + 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, use_integers_for_enums=False) + ) + # verify fields with default values are dropped -def test_transport_kind_grpc(): - transport = NetworkSecurityClient.get_transport_class("grpc")( + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" + ).list_authorization_policies._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -def test_initialize_client_w_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None - + jsonified_request["parent"] = "parent_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_authorization_policies_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_authorization_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) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), "__call__" - ) as call: - call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() - client.list_authorization_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.ListAuthorizationPoliciesRequest() - - assert args[0] == request_msg - + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_authorization_policy_empty_call_grpc(): client = NetworkSecurityClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = authorization_policy.ListAuthorizationPoliciesResponse() + # 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 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_authorization_policy), "__call__" - ) as call: - call.return_value = authorization_policy.AuthorizationPolicy() - client.get_authorization_policy(request=None) + response_value = Response() + response_value.status_code = 200 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.GetAuthorizationPolicyRequest() + # Convert return value to protobuf type + return_value = authorization_policy.ListAuthorizationPoliciesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) - assert args[0] == request_msg + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_authorization_policies(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_authorization_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_authorization_policy), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_authorization_policy(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_authorization_policy.CreateAuthorizationPolicyRequest() +def test_list_authorization_policies_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - assert args[0] == request_msg + unset_fields = transport.list_authorization_policies._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_authorization_policy_empty_call_grpc(): +def test_list_authorization_policies_rest_flattened(): client = NetworkSecurityClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_authorization_policy), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() - - assert args[0] == request_msg + # 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 = authorization_policy.ListAuthorizationPoliciesResponse() + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_authorization_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorization_policy), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_authorization_policy(request=None) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = authorization_policy.ListAuthorizationPoliciesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.DeleteAuthorizationPolicyRequest() + client.list_authorization_policies(**mock_args) - assert args[0] == request_msg + # 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/v1beta1/{parent=projects/*/locations/*}/authorizationPolicies" + % client.transport._host, + args[1], + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_server_tls_policies_empty_call_grpc(): +def test_list_authorization_policies_rest_flattened_error(transport: str = "rest"): client = NetworkSecurityClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), "__call__" - ) as call: - call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() - client.list_server_tls_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.ListServerTlsPoliciesRequest() - - assert args[0] == request_msg + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_authorization_policies( + authorization_policy.ListAuthorizationPoliciesRequest(), + parent="parent_value", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_server_tls_policy_empty_call_grpc(): +def test_list_authorization_policies_rest_pager(transport: str = "rest"): client = NetworkSecurityClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + 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 = ( + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + next_page_token="abc", + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[], + next_page_token="def", + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + ], + next_page_token="ghi", + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + authorization_policy.ListAuthorizationPoliciesResponse.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_authorization_policies(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, authorization_policy.AuthorizationPolicy) for i in results + ) + + pages = list(client.list_authorization_policies(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_authorization_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_authorization_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_authorization_policy + ] = mock_rpc + + request = {} + client.get_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_authorization_policy_rest_required_fields( + request_type=authorization_policy.GetAuthorizationPolicyRequest, +): + transport_class = transports.NetworkSecurityRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_authorization_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_authorization_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 = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = authorization_policy.AuthorizationPolicy() + # 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 + + # Convert return value to protobuf type + return_value = authorization_policy.AuthorizationPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_authorization_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_authorization_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_authorization_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_authorization_policy_rest_flattened(): + client = NetworkSecurityClient( + 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 = authorization_policy.AuthorizationPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/authorizationPolicies/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 + # Convert return value to protobuf type + return_value = authorization_policy.AuthorizationPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_authorization_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/v1beta1/{name=projects/*/locations/*/authorizationPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_get_authorization_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkSecurityClient( + 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_authorization_policy( + authorization_policy.GetAuthorizationPolicyRequest(), + name="name_value", + ) + + +def test_create_authorization_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_authorization_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_authorization_policy + ] = mock_rpc + + request = {} + client.create_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_authorization_policy_rest_required_fields( + request_type=gcn_authorization_policy.CreateAuthorizationPolicyRequest, +): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["authorization_policy_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "authorizationPolicyId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_authorization_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "authorizationPolicyId" in jsonified_request + assert ( + jsonified_request["authorizationPolicyId"] + == request_init["authorization_policy_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["authorizationPolicyId"] = "authorization_policy_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_authorization_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("authorization_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 "authorizationPolicyId" in jsonified_request + assert jsonified_request["authorizationPolicyId"] == "authorization_policy_id_value" + + client = NetworkSecurityClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_authorization_policy(request) + + expected_params = [ + ( + "authorizationPolicyId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_authorization_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_authorization_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("authorizationPolicyId",)) + & set( + ( + "parent", + "authorizationPolicyId", + "authorizationPolicy", + ) + ) + ) + + +def test_create_authorization_policy_rest_flattened(): + client = NetworkSecurityClient( + 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", + authorization_policy=gcn_authorization_policy.AuthorizationPolicy( + name="name_value" + ), + authorization_policy_id="authorization_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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_authorization_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/v1beta1/{parent=projects/*/locations/*}/authorizationPolicies" + % client.transport._host, + args[1], + ) + + +def test_create_authorization_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkSecurityClient( + 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_authorization_policy( + gcn_authorization_policy.CreateAuthorizationPolicyRequest(), + parent="parent_value", + authorization_policy=gcn_authorization_policy.AuthorizationPolicy( + name="name_value" + ), + authorization_policy_id="authorization_policy_id_value", + ) + + +def test_update_authorization_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_authorization_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_authorization_policy + ] = mock_rpc + + request = {} + client.update_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_authorization_policy_rest_required_fields( + request_type=gcn_authorization_policy.UpdateAuthorizationPolicyRequest, +): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_authorization_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_authorization_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 = NetworkSecurityClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_authorization_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_authorization_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_authorization_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("authorizationPolicy",))) + + +def test_update_authorization_policy_rest_flattened(): + client = NetworkSecurityClient( + 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 = { + "authorization_policy": { + "name": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + authorization_policy=gcn_authorization_policy.AuthorizationPolicy( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_authorization_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/v1beta1/{authorization_policy.name=projects/*/locations/*/authorizationPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_update_authorization_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkSecurityClient( + 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_authorization_policy( + gcn_authorization_policy.UpdateAuthorizationPolicyRequest(), + authorization_policy=gcn_authorization_policy.AuthorizationPolicy( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_authorization_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_authorization_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_authorization_policy + ] = mock_rpc + + request = {} + client.delete_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_authorization_policy_rest_required_fields( + request_type=authorization_policy.DeleteAuthorizationPolicyRequest, +): + transport_class = transports.NetworkSecurityRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_authorization_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_authorization_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 = NetworkSecurityClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_authorization_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_authorization_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_authorization_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_authorization_policy_rest_flattened(): + client = NetworkSecurityClient( + 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/authorizationPolicies/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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_authorization_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/v1beta1/{name=projects/*/locations/*/authorizationPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_authorization_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkSecurityClient( + 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_authorization_policy( + authorization_policy.DeleteAuthorizationPolicyRequest(), + name="name_value", + ) + + +def test_list_server_tls_policies_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_server_tls_policies + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_server_tls_policies + ] = mock_rpc + + request = {} + client.list_server_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_server_tls_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_server_tls_policies_rest_required_fields( + request_type=server_tls_policy.ListServerTlsPoliciesRequest, +): + transport_class = transports.NetworkSecurityRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_server_tls_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_server_tls_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 = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = server_tls_policy.ListServerTlsPoliciesResponse() + # 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 + + # Convert return value to protobuf type + return_value = server_tls_policy.ListServerTlsPoliciesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_server_tls_policies(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_server_tls_policies_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_server_tls_policies._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_server_tls_policies_rest_flattened(): + client = NetworkSecurityClient( + 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 = server_tls_policy.ListServerTlsPoliciesResponse() + + # 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 + # Convert return value to protobuf type + return_value = server_tls_policy.ListServerTlsPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_server_tls_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/v1beta1/{parent=projects/*/locations/*}/serverTlsPolicies" + % client.transport._host, + args[1], + ) + + +def test_list_server_tls_policies_rest_flattened_error(transport: str = "rest"): + client = NetworkSecurityClient( + 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_server_tls_policies( + server_tls_policy.ListServerTlsPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_server_tls_policies_rest_pager(transport: str = "rest"): + client = NetworkSecurityClient( + 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 = ( + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token="abc", + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[], + next_page_token="def", + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token="ghi", + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + server_tls_policy.ListServerTlsPoliciesResponse.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_server_tls_policies(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, server_tls_policy.ServerTlsPolicy) for i in results) + + pages = list(client.list_server_tls_policies(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_server_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_server_tls_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_server_tls_policy + ] = mock_rpc + + request = {} + client.get_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_server_tls_policy_rest_required_fields( + request_type=server_tls_policy.GetServerTlsPolicyRequest, +): + transport_class = transports.NetworkSecurityRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_server_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_server_tls_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 = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = server_tls_policy.ServerTlsPolicy() + # 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 + + # Convert return value to protobuf type + return_value = server_tls_policy.ServerTlsPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_server_tls_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_server_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_server_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_server_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + 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 = server_tls_policy.ServerTlsPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/serverTlsPolicies/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 + # Convert return value to protobuf type + return_value = server_tls_policy.ServerTlsPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_server_tls_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/v1beta1/{name=projects/*/locations/*/serverTlsPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_get_server_tls_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkSecurityClient( + 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_server_tls_policy( + server_tls_policy.GetServerTlsPolicyRequest(), + name="name_value", + ) + + +def test_create_server_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_server_tls_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_server_tls_policy + ] = mock_rpc + + request = {} + client.create_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_server_tls_policy_rest_required_fields( + request_type=gcn_server_tls_policy.CreateServerTlsPolicyRequest, +): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["server_tls_policy_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "serverTlsPolicyId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_server_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "serverTlsPolicyId" in jsonified_request + assert ( + jsonified_request["serverTlsPolicyId"] == request_init["server_tls_policy_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["serverTlsPolicyId"] = "server_tls_policy_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_server_tls_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("server_tls_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 "serverTlsPolicyId" in jsonified_request + assert jsonified_request["serverTlsPolicyId"] == "server_tls_policy_id_value" + + client = NetworkSecurityClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_server_tls_policy(request) + + expected_params = [ + ( + "serverTlsPolicyId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_server_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_server_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("serverTlsPolicyId",)) + & set( + ( + "parent", + "serverTlsPolicyId", + "serverTlsPolicy", + ) + ) + ) + + +def test_create_server_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + 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", + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name="name_value"), + server_tls_policy_id="server_tls_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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_server_tls_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/v1beta1/{parent=projects/*/locations/*}/serverTlsPolicies" + % client.transport._host, + args[1], + ) + + +def test_create_server_tls_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkSecurityClient( + 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_server_tls_policy( + gcn_server_tls_policy.CreateServerTlsPolicyRequest(), + parent="parent_value", + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name="name_value"), + server_tls_policy_id="server_tls_policy_id_value", + ) + + +def test_update_server_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_server_tls_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_server_tls_policy + ] = mock_rpc + + request = {} + client.update_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_server_tls_policy_rest_required_fields( + request_type=gcn_server_tls_policy.UpdateServerTlsPolicyRequest, +): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_server_tls_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_server_tls_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 = NetworkSecurityClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_server_tls_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_server_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_server_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("serverTlsPolicy",))) + + +def test_update_server_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + 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 = { + "server_tls_policy": { + "name": "projects/sample1/locations/sample2/serverTlsPolicies/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_server_tls_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/v1beta1/{server_tls_policy.name=projects/*/locations/*/serverTlsPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_update_server_tls_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkSecurityClient( + 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_server_tls_policy( + gcn_server_tls_policy.UpdateServerTlsPolicyRequest(), + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_server_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_server_tls_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_server_tls_policy + ] = mock_rpc + + request = {} + client.delete_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_server_tls_policy_rest_required_fields( + request_type=server_tls_policy.DeleteServerTlsPolicyRequest, +): + transport_class = transports.NetworkSecurityRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_server_tls_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_server_tls_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 = NetworkSecurityClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_server_tls_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_server_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_server_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_server_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + 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/serverTlsPolicies/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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_server_tls_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/v1beta1/{name=projects/*/locations/*/serverTlsPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_server_tls_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkSecurityClient( + 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_server_tls_policy( + server_tls_policy.DeleteServerTlsPolicyRequest(), + name="name_value", + ) + + +def test_list_client_tls_policies_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_client_tls_policies + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_client_tls_policies + ] = mock_rpc + + request = {} + client.list_client_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_client_tls_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_client_tls_policies_rest_required_fields( + request_type=client_tls_policy.ListClientTlsPoliciesRequest, +): + transport_class = transports.NetworkSecurityRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_client_tls_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_client_tls_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 = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = client_tls_policy.ListClientTlsPoliciesResponse() + # 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 + + # Convert return value to protobuf type + return_value = client_tls_policy.ListClientTlsPoliciesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_client_tls_policies(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_client_tls_policies_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_client_tls_policies._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_client_tls_policies_rest_flattened(): + client = NetworkSecurityClient( + 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 = client_tls_policy.ListClientTlsPoliciesResponse() + + # 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 + # Convert return value to protobuf type + return_value = client_tls_policy.ListClientTlsPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_client_tls_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/v1beta1/{parent=projects/*/locations/*}/clientTlsPolicies" + % client.transport._host, + args[1], + ) + + +def test_list_client_tls_policies_rest_flattened_error(transport: str = "rest"): + client = NetworkSecurityClient( + 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_client_tls_policies( + client_tls_policy.ListClientTlsPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_client_tls_policies_rest_pager(transport: str = "rest"): + client = NetworkSecurityClient( + 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 = ( + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token="abc", + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[], + next_page_token="def", + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token="ghi", + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + client_tls_policy.ListClientTlsPoliciesResponse.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_client_tls_policies(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) for i in results) + + pages = list(client.list_client_tls_policies(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_client_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_client_tls_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_client_tls_policy + ] = mock_rpc + + request = {} + client.get_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_client_tls_policy_rest_required_fields( + request_type=client_tls_policy.GetClientTlsPolicyRequest, +): + transport_class = transports.NetworkSecurityRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_client_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_client_tls_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 = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = client_tls_policy.ClientTlsPolicy() + # 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 + + # Convert return value to protobuf type + return_value = client_tls_policy.ClientTlsPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_client_tls_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_client_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_client_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_client_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + 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 = client_tls_policy.ClientTlsPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/clientTlsPolicies/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 + # Convert return value to protobuf type + return_value = client_tls_policy.ClientTlsPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_client_tls_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/v1beta1/{name=projects/*/locations/*/clientTlsPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_get_client_tls_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkSecurityClient( + 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_client_tls_policy( + client_tls_policy.GetClientTlsPolicyRequest(), + name="name_value", + ) + + +def test_create_client_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_client_tls_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_client_tls_policy + ] = mock_rpc + + request = {} + client.create_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_client_tls_policy_rest_required_fields( + request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest, +): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["client_tls_policy_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "clientTlsPolicyId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_client_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "clientTlsPolicyId" in jsonified_request + assert ( + jsonified_request["clientTlsPolicyId"] == request_init["client_tls_policy_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["clientTlsPolicyId"] = "client_tls_policy_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_client_tls_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("client_tls_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 "clientTlsPolicyId" in jsonified_request + assert jsonified_request["clientTlsPolicyId"] == "client_tls_policy_id_value" + + client = NetworkSecurityClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_client_tls_policy(request) + + expected_params = [ + ( + "clientTlsPolicyId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_client_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_client_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("clientTlsPolicyId",)) + & set( + ( + "parent", + "clientTlsPolicyId", + "clientTlsPolicy", + ) + ) + ) + + +def test_create_client_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + 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", + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name="name_value"), + client_tls_policy_id="client_tls_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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_client_tls_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/v1beta1/{parent=projects/*/locations/*}/clientTlsPolicies" + % client.transport._host, + args[1], + ) + + +def test_create_client_tls_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkSecurityClient( + 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_client_tls_policy( + gcn_client_tls_policy.CreateClientTlsPolicyRequest(), + parent="parent_value", + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name="name_value"), + client_tls_policy_id="client_tls_policy_id_value", + ) + + +def test_update_client_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_client_tls_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_client_tls_policy + ] = mock_rpc + + request = {} + client.update_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_client_tls_policy_rest_required_fields( + request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest, +): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_client_tls_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_client_tls_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 = NetworkSecurityClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_client_tls_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_client_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_client_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("clientTlsPolicy",))) + + +def test_update_client_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + 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 = { + "client_tls_policy": { + "name": "projects/sample1/locations/sample2/clientTlsPolicies/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_client_tls_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/v1beta1/{client_tls_policy.name=projects/*/locations/*/clientTlsPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_update_client_tls_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkSecurityClient( + 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_client_tls_policy( + gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_client_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_client_tls_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_client_tls_policy + ] = mock_rpc + + request = {} + client.delete_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_client_tls_policy_rest_required_fields( + request_type=client_tls_policy.DeleteClientTlsPolicyRequest, +): + transport_class = transports.NetworkSecurityRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_client_tls_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_client_tls_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 = NetworkSecurityClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_client_tls_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_client_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_client_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_client_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + 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/clientTlsPolicies/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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_client_tls_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/v1beta1/{name=projects/*/locations/*/clientTlsPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_client_tls_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkSecurityClient( + 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_client_tls_policy( + client_tls_policy.DeleteClientTlsPolicyRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkSecurityClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = NetworkSecurityClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = NetworkSecurityClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkSecurityClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = NetworkSecurityClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.NetworkSecurityGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.NetworkSecurityGrpcTransport, + transports.NetworkSecurityGrpcAsyncIOTransport, + transports.NetworkSecurityRestTransport, + ], +) +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() + + +def test_transport_kind_grpc(): + transport = NetworkSecurityClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_authorization_policies_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), "__call__" + ) as call: + call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() + client.list_authorization_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.ListAuthorizationPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_authorization_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), "__call__" + ) as call: + call.return_value = authorization_policy.AuthorizationPolicy() + client.get_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.GetAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_authorization_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_authorization_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_authorization_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.DeleteAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_server_tls_policies_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), "__call__" + ) as call: + call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() + client.list_server_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.ListServerTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_server_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), "__call__" + ) as call: + call.return_value = server_tls_policy.ServerTlsPolicy() + client.get_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.GetServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_server_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_server_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_server_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.DeleteServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_client_tls_policies_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), "__call__" + ) as call: + call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() + client.list_client_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.ListClientTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_client_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), "__call__" + ) as call: + call.return_value = client_tls_policy.ClientTlsPolicy() + client.get_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.GetClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_client_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_client_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_client_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = NetworkSecurityAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_authorization_policies_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + authorization_policy.ListAuthorizationPoliciesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_authorization_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.ListAuthorizationPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_authorization_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + authorization_policy.AuthorizationPolicy( + name="name_value", + description="description_value", + action=authorization_policy.AuthorizationPolicy.Action.ALLOW, + ) + ) + await client.get_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.GetAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_authorization_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_authorization_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_authorization_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.DeleteAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_server_tls_policies_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + server_tls_policy.ListServerTlsPoliciesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_server_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.ListServerTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_server_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + server_tls_policy.ServerTlsPolicy( + name="name_value", + description="description_value", + allow_open=True, + ) + ) + await client.get_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.GetServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_server_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_server_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_server_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.DeleteServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_client_tls_policies_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + client_tls_policy.ListClientTlsPoliciesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_client_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.ListClientTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_client_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + client_tls_policy.ClientTlsPolicy( + name="name_value", + description="description_value", + sni="sni_value", + ) + ) + await client.get_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.GetClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_client_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_client_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_client_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_server_tls_policy), "__call__" - ) as call: - call.return_value = server_tls_policy.ServerTlsPolicy() - client.get_server_tls_policy(request=None) + type(client.transport.delete_client_tls_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = NetworkSecurityClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_authorization_policies_rest_bad_request( + request_type=authorization_policy.ListAuthorizationPoliciesRequest, +): + client = NetworkSecurityClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_authorization_policies(request) + + +@pytest.mark.parametrize( + "request_type", + [ + authorization_policy.ListAuthorizationPoliciesRequest, + dict, + ], +) +def test_list_authorization_policies_rest_call_success(request_type): + client = NetworkSecurityClient( + 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 = authorization_policy.ListAuthorizationPoliciesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = authorization_policy.ListAuthorizationPoliciesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_authorization_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAuthorizationPoliciesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_authorization_policies_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_list_authorization_policies" + ) as post, mock.patch.object( + transports.NetworkSecurityRestInterceptor, + "post_list_authorization_policies_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.NetworkSecurityRestInterceptor, "pre_list_authorization_policies" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = authorization_policy.ListAuthorizationPoliciesRequest.pb( + authorization_policy.ListAuthorizationPoliciesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = authorization_policy.ListAuthorizationPoliciesResponse.to_json( + authorization_policy.ListAuthorizationPoliciesResponse() + ) + req.return_value.content = return_value + + request = authorization_policy.ListAuthorizationPoliciesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = authorization_policy.ListAuthorizationPoliciesResponse() + post_with_metadata.return_value = ( + authorization_policy.ListAuthorizationPoliciesResponse(), + metadata, + ) + + client.list_authorization_policies( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_authorization_policy_rest_bad_request( + request_type=authorization_policy.GetAuthorizationPolicyRequest, +): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/authorizationPolicies/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_authorization_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + authorization_policy.GetAuthorizationPolicyRequest, + dict, + ], +) +def test_get_authorization_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/authorizationPolicies/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 = authorization_policy.AuthorizationPolicy( + name="name_value", + description="description_value", + action=authorization_policy.AuthorizationPolicy.Action.ALLOW, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = authorization_policy.AuthorizationPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_authorization_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, authorization_policy.AuthorizationPolicy) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.action == authorization_policy.AuthorizationPolicy.Action.ALLOW + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_authorization_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_get_authorization_policy" + ) as post, mock.patch.object( + transports.NetworkSecurityRestInterceptor, + "post_get_authorization_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.NetworkSecurityRestInterceptor, "pre_get_authorization_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = authorization_policy.GetAuthorizationPolicyRequest.pb( + authorization_policy.GetAuthorizationPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = authorization_policy.AuthorizationPolicy.to_json( + authorization_policy.AuthorizationPolicy() + ) + req.return_value.content = return_value + + request = authorization_policy.GetAuthorizationPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = authorization_policy.AuthorizationPolicy() + post_with_metadata.return_value = ( + authorization_policy.AuthorizationPolicy(), + metadata, + ) + + client.get_authorization_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_authorization_policy_rest_bad_request( + request_type=gcn_authorization_policy.CreateAuthorizationPolicyRequest, +): + client = NetworkSecurityClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_authorization_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_authorization_policy.CreateAuthorizationPolicyRequest, + dict, + ], +) +def test_create_authorization_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["authorization_policy"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "action": 1, + "rules": [ + { + "sources": [ + { + "principals": ["principals_value1", "principals_value2"], + "ip_blocks": ["ip_blocks_value1", "ip_blocks_value2"], + } + ], + "destinations": [ + { + "hosts": ["hosts_value1", "hosts_value2"], + "ports": [569, 570], + "methods": ["methods_value1", "methods_value2"], + "http_header_match": { + "regex_match": "regex_match_value", + "header_name": "header_name_value", + }, + } + ], + } + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_authorization_policy.CreateAuthorizationPolicyRequest.meta.fields[ + "authorization_policy" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "authorization_policy" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["authorization_policy"][field])): + del request_init["authorization_policy"][field][i][subfield] + else: + del request_init["authorization_policy"][field][subfield] + 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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_authorization_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_authorization_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_create_authorization_policy" + ) as post, mock.patch.object( + transports.NetworkSecurityRestInterceptor, + "post_create_authorization_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.NetworkSecurityRestInterceptor, "pre_create_authorization_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_authorization_policy.CreateAuthorizationPolicyRequest.pb( + gcn_authorization_policy.CreateAuthorizationPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_authorization_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_authorization_policy_rest_bad_request( + request_type=gcn_authorization_policy.UpdateAuthorizationPolicyRequest, +): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "authorization_policy": { + "name": "projects/sample1/locations/sample2/authorizationPolicies/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_authorization_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_authorization_policy.UpdateAuthorizationPolicyRequest, + dict, + ], +) +def test_update_authorization_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "authorization_policy": { + "name": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + } + } + request_init["authorization_policy"] = { + "name": "projects/sample1/locations/sample2/authorizationPolicies/sample3", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "action": 1, + "rules": [ + { + "sources": [ + { + "principals": ["principals_value1", "principals_value2"], + "ip_blocks": ["ip_blocks_value1", "ip_blocks_value2"], + } + ], + "destinations": [ + { + "hosts": ["hosts_value1", "hosts_value2"], + "ports": [569, 570], + "methods": ["methods_value1", "methods_value2"], + "http_header_match": { + "regex_match": "regex_match_value", + "header_name": "header_name_value", + }, + } + ], + } + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_authorization_policy.UpdateAuthorizationPolicyRequest.meta.fields[ + "authorization_policy" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "authorization_policy" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["authorization_policy"][field])): + del request_init["authorization_policy"][field][i][subfield] + else: + del request_init["authorization_policy"][field][subfield] + 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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_authorization_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_authorization_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_update_authorization_policy" + ) as post, mock.patch.object( + transports.NetworkSecurityRestInterceptor, + "post_update_authorization_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.NetworkSecurityRestInterceptor, "pre_update_authorization_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_authorization_policy.UpdateAuthorizationPolicyRequest.pb( + gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_authorization_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_authorization_policy_rest_bad_request( + request_type=authorization_policy.DeleteAuthorizationPolicyRequest, +): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/authorizationPolicies/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_authorization_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + authorization_policy.DeleteAuthorizationPolicyRequest, + dict, + ], +) +def test_delete_authorization_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/authorizationPolicies/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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_authorization_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_authorization_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_delete_authorization_policy" + ) as post, mock.patch.object( + transports.NetworkSecurityRestInterceptor, + "post_delete_authorization_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.NetworkSecurityRestInterceptor, "pre_delete_authorization_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = authorization_policy.DeleteAuthorizationPolicyRequest.pb( + authorization_policy.DeleteAuthorizationPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = authorization_policy.DeleteAuthorizationPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_authorization_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_server_tls_policies_rest_bad_request( + request_type=server_tls_policy.ListServerTlsPoliciesRequest, +): + client = NetworkSecurityClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_server_tls_policies(request) + + +@pytest.mark.parametrize( + "request_type", + [ + server_tls_policy.ListServerTlsPoliciesRequest, + dict, + ], +) +def test_list_server_tls_policies_rest_call_success(request_type): + client = NetworkSecurityClient( + 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 = server_tls_policy.ListServerTlsPoliciesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = server_tls_policy.ListServerTlsPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_server_tls_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServerTlsPoliciesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_server_tls_policies_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_list_server_tls_policies" + ) as post, mock.patch.object( + transports.NetworkSecurityRestInterceptor, + "post_list_server_tls_policies_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.NetworkSecurityRestInterceptor, "pre_list_server_tls_policies" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = server_tls_policy.ListServerTlsPoliciesRequest.pb( + server_tls_policy.ListServerTlsPoliciesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = server_tls_policy.ListServerTlsPoliciesResponse.to_json( + server_tls_policy.ListServerTlsPoliciesResponse() + ) + req.return_value.content = return_value + + request = server_tls_policy.ListServerTlsPoliciesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = server_tls_policy.ListServerTlsPoliciesResponse() + post_with_metadata.return_value = ( + server_tls_policy.ListServerTlsPoliciesResponse(), + metadata, + ) + + client.list_server_tls_policies( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_server_tls_policy_rest_bad_request( + request_type=server_tls_policy.GetServerTlsPolicyRequest, +): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/serverTlsPolicies/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_server_tls_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + server_tls_policy.GetServerTlsPolicyRequest, + dict, + ], +) +def test_get_server_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/serverTlsPolicies/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 = server_tls_policy.ServerTlsPolicy( + name="name_value", + description="description_value", + allow_open=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = server_tls_policy.ServerTlsPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_server_tls_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, server_tls_policy.ServerTlsPolicy) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.allow_open is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_server_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_get_server_tls_policy" + ) as post, mock.patch.object( + transports.NetworkSecurityRestInterceptor, + "post_get_server_tls_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.NetworkSecurityRestInterceptor, "pre_get_server_tls_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = server_tls_policy.GetServerTlsPolicyRequest.pb( + server_tls_policy.GetServerTlsPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = server_tls_policy.ServerTlsPolicy.to_json( + server_tls_policy.ServerTlsPolicy() + ) + req.return_value.content = return_value + + request = server_tls_policy.GetServerTlsPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = server_tls_policy.ServerTlsPolicy() + post_with_metadata.return_value = server_tls_policy.ServerTlsPolicy(), metadata + + client.get_server_tls_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_server_tls_policy_rest_bad_request( + request_type=gcn_server_tls_policy.CreateServerTlsPolicyRequest, +): + client = NetworkSecurityClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_server_tls_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_server_tls_policy.CreateServerTlsPolicyRequest, + dict, + ], +) +def test_create_server_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["server_tls_policy"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "allow_open": True, + "server_certificate": { + "grpc_endpoint": {"target_uri": "target_uri_value"}, + "certificate_provider_instance": { + "plugin_instance": "plugin_instance_value" + }, + }, + "mtls_policy": { + "client_validation_ca": [ + {"grpc_endpoint": {}, "certificate_provider_instance": {}} + ] + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_server_tls_policy.CreateServerTlsPolicyRequest.meta.fields[ + "server_tls_policy" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["server_tls_policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["server_tls_policy"][field])): + del request_init["server_tls_policy"][field][i][subfield] + else: + del request_init["server_tls_policy"][field][subfield] + 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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_server_tls_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_server_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_create_server_tls_policy" + ) as post, mock.patch.object( + transports.NetworkSecurityRestInterceptor, + "post_create_server_tls_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.NetworkSecurityRestInterceptor, "pre_create_server_tls_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_server_tls_policy.CreateServerTlsPolicyRequest.pb( + gcn_server_tls_policy.CreateServerTlsPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_server_tls_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_server_tls_policy_rest_bad_request( + request_type=gcn_server_tls_policy.UpdateServerTlsPolicyRequest, +): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "server_tls_policy": { + "name": "projects/sample1/locations/sample2/serverTlsPolicies/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_server_tls_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_server_tls_policy.UpdateServerTlsPolicyRequest, + dict, + ], +) +def test_update_server_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "server_tls_policy": { + "name": "projects/sample1/locations/sample2/serverTlsPolicies/sample3" + } + } + request_init["server_tls_policy"] = { + "name": "projects/sample1/locations/sample2/serverTlsPolicies/sample3", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "allow_open": True, + "server_certificate": { + "grpc_endpoint": {"target_uri": "target_uri_value"}, + "certificate_provider_instance": { + "plugin_instance": "plugin_instance_value" + }, + }, + "mtls_policy": { + "client_validation_ca": [ + {"grpc_endpoint": {}, "certificate_provider_instance": {}} + ] + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_server_tls_policy.UpdateServerTlsPolicyRequest.meta.fields[ + "server_tls_policy" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["server_tls_policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["server_tls_policy"][field])): + del request_init["server_tls_policy"][field][i][subfield] + else: + del request_init["server_tls_policy"][field][subfield] + 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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_server_tls_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_server_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_update_server_tls_policy" + ) as post, mock.patch.object( + transports.NetworkSecurityRestInterceptor, + "post_update_server_tls_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.NetworkSecurityRestInterceptor, "pre_update_server_tls_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_server_tls_policy.UpdateServerTlsPolicyRequest.pb( + gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_server_tls_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_server_tls_policy_rest_bad_request( + request_type=server_tls_policy.DeleteServerTlsPolicyRequest, +): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/serverTlsPolicies/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_server_tls_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + server_tls_policy.DeleteServerTlsPolicyRequest, + dict, + ], +) +def test_delete_server_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/serverTlsPolicies/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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_server_tls_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_server_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_delete_server_tls_policy" + ) as post, mock.patch.object( + transports.NetworkSecurityRestInterceptor, + "post_delete_server_tls_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.NetworkSecurityRestInterceptor, "pre_delete_server_tls_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = server_tls_policy.DeleteServerTlsPolicyRequest.pb( + server_tls_policy.DeleteServerTlsPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = server_tls_policy.DeleteServerTlsPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_server_tls_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_client_tls_policies_rest_bad_request( + request_type=client_tls_policy.ListClientTlsPoliciesRequest, +): + client = NetworkSecurityClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_client_tls_policies(request) + + +@pytest.mark.parametrize( + "request_type", + [ + client_tls_policy.ListClientTlsPoliciesRequest, + dict, + ], +) +def test_list_client_tls_policies_rest_call_success(request_type): + client = NetworkSecurityClient( + 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 = client_tls_policy.ListClientTlsPoliciesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = client_tls_policy.ListClientTlsPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_client_tls_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClientTlsPoliciesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_client_tls_policies_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_list_client_tls_policies" + ) as post, mock.patch.object( + transports.NetworkSecurityRestInterceptor, + "post_list_client_tls_policies_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.NetworkSecurityRestInterceptor, "pre_list_client_tls_policies" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = client_tls_policy.ListClientTlsPoliciesRequest.pb( + client_tls_policy.ListClientTlsPoliciesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = client_tls_policy.ListClientTlsPoliciesResponse.to_json( + client_tls_policy.ListClientTlsPoliciesResponse() + ) + req.return_value.content = return_value + + request = client_tls_policy.ListClientTlsPoliciesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = client_tls_policy.ListClientTlsPoliciesResponse() + post_with_metadata.return_value = ( + client_tls_policy.ListClientTlsPoliciesResponse(), + metadata, + ) + + client.list_client_tls_policies( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_client_tls_policy_rest_bad_request( + request_type=client_tls_policy.GetClientTlsPolicyRequest, +): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/clientTlsPolicies/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_client_tls_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + client_tls_policy.GetClientTlsPolicyRequest, + dict, + ], +) +def test_get_client_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/clientTlsPolicies/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 = client_tls_policy.ClientTlsPolicy( + name="name_value", + description="description_value", + sni="sni_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = client_tls_policy.ClientTlsPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_client_tls_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, client_tls_policy.ClientTlsPolicy) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.sni == "sni_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_client_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_get_client_tls_policy" + ) as post, mock.patch.object( + transports.NetworkSecurityRestInterceptor, + "post_get_client_tls_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.NetworkSecurityRestInterceptor, "pre_get_client_tls_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = client_tls_policy.GetClientTlsPolicyRequest.pb( + client_tls_policy.GetClientTlsPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = client_tls_policy.ClientTlsPolicy.to_json( + client_tls_policy.ClientTlsPolicy() + ) + req.return_value.content = return_value + + request = client_tls_policy.GetClientTlsPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = client_tls_policy.ClientTlsPolicy() + post_with_metadata.return_value = client_tls_policy.ClientTlsPolicy(), metadata + + client.get_client_tls_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_client_tls_policy_rest_bad_request( + request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest, +): + client = NetworkSecurityClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_client_tls_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_client_tls_policy.CreateClientTlsPolicyRequest, + dict, + ], +) +def test_create_client_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["client_tls_policy"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "sni": "sni_value", + "client_certificate": { + "grpc_endpoint": {"target_uri": "target_uri_value"}, + "certificate_provider_instance": { + "plugin_instance": "plugin_instance_value" + }, + }, + "server_validation_ca": [ + {"grpc_endpoint": {}, "certificate_provider_instance": {}} + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_client_tls_policy.CreateClientTlsPolicyRequest.meta.fields[ + "client_tls_policy" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["client_tls_policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["client_tls_policy"][field])): + del request_init["client_tls_policy"][field][i][subfield] + else: + del request_init["client_tls_policy"][field][subfield] + 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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_client_tls_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_client_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_create_client_tls_policy" + ) as post, mock.patch.object( + transports.NetworkSecurityRestInterceptor, + "post_create_client_tls_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.NetworkSecurityRestInterceptor, "pre_create_client_tls_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_client_tls_policy.CreateClientTlsPolicyRequest.pb( + gcn_client_tls_policy.CreateClientTlsPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_client_tls_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_client_tls_policy_rest_bad_request( + request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest, +): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "client_tls_policy": { + "name": "projects/sample1/locations/sample2/clientTlsPolicies/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_client_tls_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_client_tls_policy.UpdateClientTlsPolicyRequest, + dict, + ], +) +def test_update_client_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "client_tls_policy": { + "name": "projects/sample1/locations/sample2/clientTlsPolicies/sample3" + } + } + request_init["client_tls_policy"] = { + "name": "projects/sample1/locations/sample2/clientTlsPolicies/sample3", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "sni": "sni_value", + "client_certificate": { + "grpc_endpoint": {"target_uri": "target_uri_value"}, + "certificate_provider_instance": { + "plugin_instance": "plugin_instance_value" + }, + }, + "server_validation_ca": [ + {"grpc_endpoint": {}, "certificate_provider_instance": {}} + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.meta.fields[ + "client_tls_policy" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["client_tls_policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["client_tls_policy"][field])): + del request_init["client_tls_policy"][field][i][subfield] + else: + del request_init["client_tls_policy"][field][subfield] + 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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_client_tls_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_client_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_update_client_tls_policy" + ) as post, mock.patch.object( + transports.NetworkSecurityRestInterceptor, + "post_update_client_tls_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.NetworkSecurityRestInterceptor, "pre_update_client_tls_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.pb( + gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_client_tls_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_client_tls_policy_rest_bad_request( + request_type=client_tls_policy.DeleteClientTlsPolicyRequest, +): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/clientTlsPolicies/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_client_tls_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + client_tls_policy.DeleteClientTlsPolicyRequest, + dict, + ], +) +def test_delete_client_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/clientTlsPolicies/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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_client_tls_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_client_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_delete_client_tls_policy" + ) as post, mock.patch.object( + transports.NetworkSecurityRestInterceptor, + "post_delete_client_tls_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.NetworkSecurityRestInterceptor, "pre_delete_client_tls_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = client_tls_policy.DeleteClientTlsPolicyRequest.pb( + client_tls_policy.DeleteClientTlsPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = client_tls_policy.DeleteClientTlsPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_client_tls_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + 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(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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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( + request_type=locations_pb2.ListLocationsRequest, +): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = NetworkSecurityClient( + 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(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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(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 = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.GetServerTlsPolicyRequest() + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) - assert args[0] == request_msg +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + }, + request, + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_server_tls_policy_empty_call_grpc(): + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): client = NetworkSecurityClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_server_tls_policy), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_server_tls_policy(request=None) + request_init = { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") - assert args[0] == request_msg + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_server_tls_policy_empty_call_grpc(): + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): client = NetworkSecurityClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + }, + request, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_server_tls_policy), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() - - assert args[0] == request_msg + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_server_tls_policy_empty_call_grpc(): +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): client = NetworkSecurityClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_server_tls_policy), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_server_tls_policy(request=None) + request_init = { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.DeleteServerTlsPolicyRequest() + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") - assert args[0] == request_msg + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.test_iam_permissions(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_client_tls_policies_empty_call_grpc(): + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): client = NetworkSecurityClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), "__call__" - ) as call: - call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() - client.list_client_tls_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.ListClientTlsPoliciesRequest() - - assert args[0] == request_msg + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_client_tls_policy_empty_call_grpc(): +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): client = NetworkSecurityClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), "__call__" - ) as call: - call.return_value = client_tls_policy.ClientTlsPolicy() - client.get_client_tls_policy(request=None) + 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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.GetClientTlsPolicyRequest() + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") - assert args[0] == request_msg + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.cancel_operation(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_client_tls_policy_empty_call_grpc(): + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): client = NetworkSecurityClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_client_tls_policy(request=None) + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - assert args[0] == request_msg +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + 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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_client_tls_policy_empty_call_grpc(): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): client = NetworkSecurityClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_client_tls_policy(request=None) + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - assert args[0] == request_msg +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + 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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_client_tls_policy_empty_call_grpc(): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): client = NetworkSecurityClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_client_tls_policy(request=None) + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() - assert args[0] == request_msg +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + 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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() -def test_transport_kind_grpc_asyncio(): - transport = NetworkSecurityAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" + # Wrap the value into a proper Response obj + response_value = mock.Mock() + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} -def test_initialize_client_w_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_authorization_policies_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_authorization_policies_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.list_authorization_policies), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - authorization_policy.ListAuthorizationPoliciesResponse( - next_page_token="next_page_token_value", - ) - ) - await client.list_authorization_policies(request=None) + client.list_authorization_policies(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -7555,26 +14211,17 @@ async def test_list_authorization_policies_empty_call_grpc_asyncio(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_authorization_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_get_authorization_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.get_authorization_policy), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - authorization_policy.AuthorizationPolicy( - name="name_value", - description="description_value", - action=authorization_policy.AuthorizationPolicy.Action.ALLOW, - ) - ) - await client.get_authorization_policy(request=None) + client.get_authorization_policy(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -7586,22 +14233,17 @@ async def test_get_authorization_policy_empty_call_grpc_asyncio(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_authorization_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_create_authorization_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.create_authorization_policy), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.create_authorization_policy(request=None) + client.create_authorization_policy(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -7613,22 +14255,17 @@ async def test_create_authorization_policy_empty_call_grpc_asyncio(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_authorization_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_update_authorization_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.update_authorization_policy), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.update_authorization_policy(request=None) + client.update_authorization_policy(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -7640,22 +14277,17 @@ async def test_update_authorization_policy_empty_call_grpc_asyncio(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_authorization_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_delete_authorization_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.delete_authorization_policy), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.delete_authorization_policy(request=None) + client.delete_authorization_policy(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -7667,24 +14299,17 @@ async def test_delete_authorization_policy_empty_call_grpc_asyncio(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_server_tls_policies_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_server_tls_policies_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.list_server_tls_policies), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - server_tls_policy.ListServerTlsPoliciesResponse( - next_page_token="next_page_token_value", - ) - ) - await client.list_server_tls_policies(request=None) + client.list_server_tls_policies(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -7696,26 +14321,17 @@ async def test_list_server_tls_policies_empty_call_grpc_asyncio(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_server_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_get_server_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.get_server_tls_policy), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - server_tls_policy.ServerTlsPolicy( - name="name_value", - description="description_value", - allow_open=True, - ) - ) - await client.get_server_tls_policy(request=None) + client.get_server_tls_policy(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -7727,22 +14343,17 @@ async def test_get_server_tls_policy_empty_call_grpc_asyncio(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_server_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_create_server_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.create_server_tls_policy), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.create_server_tls_policy(request=None) + client.create_server_tls_policy(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -7754,22 +14365,17 @@ async def test_create_server_tls_policy_empty_call_grpc_asyncio(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_server_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_update_server_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.update_server_tls_policy), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.update_server_tls_policy(request=None) + client.update_server_tls_policy(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -7781,22 +14387,17 @@ async def test_update_server_tls_policy_empty_call_grpc_asyncio(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_server_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_delete_server_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.delete_server_tls_policy), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.delete_server_tls_policy(request=None) + client.delete_server_tls_policy(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -7808,24 +14409,17 @@ async def test_delete_server_tls_policy_empty_call_grpc_asyncio(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_client_tls_policies_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_client_tls_policies_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.list_client_tls_policies), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - client_tls_policy.ListClientTlsPoliciesResponse( - next_page_token="next_page_token_value", - ) - ) - await client.list_client_tls_policies(request=None) + client.list_client_tls_policies(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -7837,26 +14431,17 @@ async def test_list_client_tls_policies_empty_call_grpc_asyncio(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_client_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_get_client_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.get_client_tls_policy), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - client_tls_policy.ClientTlsPolicy( - name="name_value", - description="description_value", - sni="sni_value", - ) - ) - await client.get_client_tls_policy(request=None) + client.get_client_tls_policy(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -7868,22 +14453,17 @@ async def test_get_client_tls_policy_empty_call_grpc_asyncio(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_client_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_create_client_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.create_client_tls_policy), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.create_client_tls_policy(request=None) + client.create_client_tls_policy(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -7895,22 +14475,17 @@ async def test_create_client_tls_policy_empty_call_grpc_asyncio(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_client_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_update_client_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.update_client_tls_policy), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.update_client_tls_policy(request=None) + client.update_client_tls_policy(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -7922,22 +14497,17 @@ async def test_update_client_tls_policy_empty_call_grpc_asyncio(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_client_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_delete_client_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Mock the actual call, and fake the request. with mock.patch.object( type(client.transport.delete_client_tls_policy), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.delete_client_tls_policy(request=None) + client.delete_client_tls_policy(request=None) # Establish that the underlying stub method was called. call.assert_called() @@ -7947,6 +14517,23 @@ async def test_delete_client_tls_policy_empty_call_grpc_asyncio(): assert args[0] == request_msg +def test_network_security_rest_lro_client(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an 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 + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = NetworkSecurityClient( @@ -8095,6 +14682,7 @@ def test_network_security_transport_auth_adc(transport_class): [ transports.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport, + transports.NetworkSecurityRestTransport, ], ) def test_network_security_transport_auth_gdch_credentials(transport_class): @@ -8192,11 +14780,23 @@ def test_network_security_grpc_transport_client_cert_source_for_mtls(transport_c ) +def test_network_security_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.NetworkSecurityRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_network_security_host_no_port(transport_name): @@ -8207,7 +14807,11 @@ def test_network_security_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("networksecurity.googleapis.com:443") + assert client.transport._host == ( + "networksecurity.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com" + ) @pytest.mark.parametrize( @@ -8215,6 +14819,7 @@ def test_network_security_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_network_security_host_with_port(transport_name): @@ -8225,7 +14830,75 @@ def test_network_security_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("networksecurity.googleapis.com:8000") + assert client.transport._host == ( + "networksecurity.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_network_security_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = NetworkSecurityClient( + credentials=creds1, + transport=transport_name, + ) + client2 = NetworkSecurityClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_authorization_policies._session + session2 = client2.transport.list_authorization_policies._session + assert session1 != session2 + session1 = client1.transport.get_authorization_policy._session + session2 = client2.transport.get_authorization_policy._session + assert session1 != session2 + session1 = client1.transport.create_authorization_policy._session + session2 = client2.transport.create_authorization_policy._session + assert session1 != session2 + session1 = client1.transport.update_authorization_policy._session + session2 = client2.transport.update_authorization_policy._session + assert session1 != session2 + session1 = client1.transport.delete_authorization_policy._session + session2 = client2.transport.delete_authorization_policy._session + assert session1 != session2 + session1 = client1.transport.list_server_tls_policies._session + session2 = client2.transport.list_server_tls_policies._session + assert session1 != session2 + session1 = client1.transport.get_server_tls_policy._session + session2 = client2.transport.get_server_tls_policy._session + assert session1 != session2 + session1 = client1.transport.create_server_tls_policy._session + session2 = client2.transport.create_server_tls_policy._session + assert session1 != session2 + session1 = client1.transport.update_server_tls_policy._session + session2 = client2.transport.update_server_tls_policy._session + assert session1 != session2 + session1 = client1.transport.delete_server_tls_policy._session + session2 = client2.transport.delete_server_tls_policy._session + assert session1 != session2 + session1 = client1.transport.list_client_tls_policies._session + session2 = client2.transport.list_client_tls_policies._session + assert session1 != session2 + session1 = client1.transport.get_client_tls_policy._session + session2 = client2.transport.get_client_tls_policy._session + assert session1 != session2 + session1 = client1.transport.create_client_tls_policy._session + session2 = client2.transport.create_client_tls_policy._session + assert session1 != session2 + session1 = client1.transport.update_client_tls_policy._session + session2 = client2.transport.update_client_tls_policy._session + assert session1 != session2 + session1 = client1.transport.delete_client_tls_policy._session + session2 = client2.transport.delete_client_tls_policy._session + assert session1 != session2 def test_network_security_grpc_transport_channel(): @@ -9985,8 +16658,21 @@ async def test_transport_close_grpc_asyncio(): close.assert_called_once() +def test_transport_close_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: